Fundamentals of Programming CS-114 Lab Manual ...

98
Fundamentals of Programming CS-114 Lab Manual COLLEGE OF ELECTRICAL & MECHANICAL ENGINEERING NUST

Transcript of Fundamentals of Programming CS-114 Lab Manual ...

Fundamentals of Programming

CS-114

Lab Manual

COLLEGE OF ELECTRICAL &

MECHANICAL ENGINEERING NUST

Lab & Project Rubrics

Trait Exceptional [10-8]

Acceptable [7-5]

Amateur [4-3]

Unsatisfactory [2-0]

Compilation 15%

Program compiles with zero error and zero warnings.

Program has few syntax error but logically correct.

Program has few syntax error but not even logically correct.

Application does not compile or compiles but crashes.

Functionality And efficiency

30%

The program works and meets all of the specifications and is extremely efficient without sacrificing readability and understanding.

The code is fairly efficient without sacrificing readability and understanding and also meets almost all of its specifications but not all.

The code is unnecessarily long and inefficient and meets only few of its specifications

The code is huge and does not meet any specifications

Output 5%

The program produces correct results and display them correctly in an organized way.

The program works and produces the correct results and displays them correctly

The program produces correct results but does not display them correctly

The program is producing incorrect results.

Input

Validation*

20%

All the inputs entered by

user are properly

validated, in case of

wrong input entered by

user the program

displays to the user to

enter the correct input.

In case of wrong input the

programs continues

execution.

Some of the inputs are

validated leaving the

others.

No input validation.

Delivery 30%

The code was delivered

within the deadline.

The code was delivered

within the deadline

The code was delivered

few hours passed the

deadline.

The code was more than 2

days overdue.

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #01: Introduction

Name:____________________ Reg #: ___________________

Lab Objective:

Introduction to programming

Lab Description:

C++ Program Structure

Let us look at a simple code that would print the words Hello World.

#include <iostream>

using namespace std;

// main() is where program execution begins.

int main() {

cout << "Hello World"; // prints Hello World

return 0;

}

Let us look at the various parts of the above program −

The C++ language defines several headers, which contain information that is either

necessary or useful to your program. For this program, the header <iostream> is

needed.

The line using namespace std; tells the compiler to use the std namespace.

Namespaces are a relatively recent addition to C++.

The next line '// main() is where program execution begins.' is a single-line comment

available in C++. Single-line comments begin with // and stop at the end of the line.

The line int main() is the main function where program execution begins.

The next line cout << "Hello World"; causes the message "Hello World" to be

displayed on the screen.

The next line return 0; terminates main( )function and causes it to return the value 0

to the calling process.

In C++, the semicolon is a statement terminator. That is, each individual statement

must be ended with a semicolon. It indicates the end of one logical entity.

Program comments are explanatory statements that you can include in the C++ code.

These comments help anyone reading the source code. All programming languages

allow for some form of comments. C++ supports single-line and multi-line comments.

All characters available inside any comment are ignored by C++ compiler. C++

comments start with /* and end with */. A comment can also start with //, extending

to the end of the line.

TASK1: Run the following program and check the output

#include<iostream> using namespace std; int main() { cout << "hello world" << endl; //prints hello world and endl means end the line system("pause"); //to stop output window return 0; }

TASK2:

Write a C++ program to print the following lines: You are 10 years old. You are too young to play the game.

TASK3:

Write five C++ statements to print the asterisk pattern as shown below.

*

**

***

****

*****

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #02:

Name:____________________ Reg #: ___________________

Lab Objective:

Learning datatypes, variables, constants, arithmetic

operators.

Lab Description:

Data Types:

A variable provides us with named storage that our

programs can manipulate. Each variable in C++ has a

specific type, which determines the size and layout of

the variable's memory, this type is known as data type

of that variable.

The name of a variable can be composed of letters,

digits, and the underscore character. It must begin

with either a letter or an underscore. Upper and

lowercase letters are distinct because C++ is case-

sensitive.

Figure 1: Basic Data Types

Variable Declaration in C++

A variable declaration provides assurance to the

compiler that there is one variable existing with the

given type and name so that compiler proceed for

further compilation.

int a;

char b;

float c;

Variable Initialization in C++

A variable can be initialized at the time of declaration or even after

that. Basically initialization means storing some actual meaningful

data inside the variable.

int a=2;

char b=’x’;

float c=2.907;

Constants

Constants refer to fixed values that the program may not alter during its execution. These fixed values are

also called literals.

Defining Constants

There are two simple ways in C++ to define constants:

Using #define preprocessor

Using const keyword

#define LENGTH 10

#define WIDTH 5

const int LENGTH = 10;

const int WIDTH = 5;

Legal Identifiers:

Regardless of which style you adopt, be consistent and make your variable names as sensible as

possible. Here are some specific rules that must be followed with all identifiers.

• The first character must be one of the letters a through z, A through Z, or an underscore

character (_).

• After the first character you may use the letters a through z or A through Z, the digits 0 through

9, or underscores.

• Uppercase and lowercase characters are distinct. This means ItemsOrdered is not the same as

itemsordered.

Escape Sequence:

cout << "\t";

Fundamental Arithmetic Operators:

LAB

Task-1:

Type and save the following programs in Visual Studio. Run these programs and observe their

output.

Task2:

Take two integers as input from the user apply athematic operations on them(+,-,*,/) as print

them on screen.

Task3:

Write the output of the following code

Task 4: Write a C++ program to calculate the distance between the two points. Note: x1, y1, x2, y2 are all double values.

Formula:

Output:

Task 5:

1. Calculate the Area of a Circle (area = PI * r2)

2. Calculate the Area of a Rectangle (area = length * width)

3. Calculate the Area of a Triangle (area = base * height * .5)

Task 6:

Total Purchase A customer in a store is purchasing five items. The prices of the five items are:

Price of item 1 = $12.95

Price of item 2 = $24.95

Price of item 3 = $6.95

Price of item 4 = $14.95

Price of item 5 = $3.95

Write a program that holds the prices of the five items in five variables. Display each items

price, the subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is

6%.

Bonus Task:

Break Number:

Write a program that inputs a five-digit integer, separates the integer into its individual

digits and prints the digits separated from one another by three spaces each.

Home Tasks:

Task 1:

Exchange Write a program that reads in two variables and swaps the value of these variables.

For example if a variable ‘var1’ contains 10 and variable ‘var2’ contains 20, after the swap

operation the variable ‘var1’ contains 20 (value of var2) and variable ‘var2’ contains 10 (value

of var1).

Task 2:

Make Upper Write a program that prompts the user to enter an alphabet in small caps (a, b,

c, … … … z) and display the entered alphabet into its upper caps (A, B, C, … … … Z).

(hint ASCII)

“When you are not practicing, remember, someone somewhere is

practicing, and when you meet him he will win”

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #03:

Name:____________________ Reg #: ___________________

Lab Objective:

Expressions, type casting, coercion, formatting, random numbers.

Lab Description:

Implicit conversion (coercion)

Implicit conversions are automatically performed when a value is copied to a compatible

type. For example

Short a= 2000;

Int b;

b=a;

When an operator works with two values of different data types, the lower-ranking value is promoted to the type of the higher-ranking value.

When the final value of an expression is assigned to a variable, it will be converted to the

data type of that variable.

Type casting

C++ is a strong-typed language. Many conversions, specially those that imply a different

interpretation of the value, require an explicit conversion, known in C++ as type-casting. There exist

two main syntaxes for generic type-casting: functional and c-like:

double x = 10.3;

int y;

y = int (x); // functional notation

y = (int) x; // c-like cast notation

Expressions:

Multiplication, mode and division have higher precedence than addition and subtraction.

Associativity: left to right.

Random Function:

Cout << rand();

Library used <cstdlib>

Formatting:

LAB:

Task 1:

Assume that the following variables are defined:

int age;

double pay;

char section;

Write a single cin statement that will read input into each of these variables.

Task 2:

Complete the following table by writing the value of each expression in the Value column

according C++ language rules.

Task 3:

Assume a program has the following variable definitions:

int units;

float mass;

double weight;

weight = mass * units;

Which automatic data type conversion will take place?

A. mass is demoted to an int, units remains an int, and the result of mass * units is an int.

B. units is promoted to a float, mass remains a float, and the result of mass * units is a float.

C. units is promoted to a float, mass remains a float, and the result of mass * units is a

double.

Task 4:

Assume a program has the following variable definitions:

int a, b = 2; float c = 4.2;

and the following statement: a = b * c;

What value will be stored in a?

A. 8.4 B. 8 C. 0 D. None of the above

Task 5:

Assume that qty and salesReps are both integers. Use a type cast expression to rewrite the

following statement so it will no longer perform integer division.

unitsEach = qty / salesReps;

Task 6:

Math Tutor: (hint rand())

Write a program that can be used as a math tutor for a young student. The program should

display two random numbers to be added, such as

247

+ 129

---------

The program should then pause while the student works on the problem. When the student

is ready to check the answer, he or she can press a key and the program will display the

correct solution:

247

+ 129

--------

376

Home Tasks:

Task 1:

Each of the following programs has some errors. Locate as many as you can.

Program-1

using namespace std;

void main ()

{

double number1, number2, sum;

cout << "Enter a number: ";

Cin << number1;

cout << "Enter another number: ";

cin << number2;

number1 + number2 = sum;

cout "The sum of the two numbers is " << sum

}

Program-2

#include <iostream>

using namespace std;

void main()

{

int number1, number2;

float quotient;

cout << "Enter two numbers and I will divide\n";

cout << "the first by the second for you.\n";

cin >> number1, number2;

quotient = float<static_cast>(number1) / number2;

cout << quotient

}

Task 2:

Average of Values to get the average of a series of values, you add the values up and then

divide the sum by the number of values. Write a program that stores the following values in

five different variables: 28, 32, 37, 24, and 33. The program should first calculate the sum of

these five variables and store the result in a separate variable named sum. Then, the

program should divide the sum variable by 5 to get the average. Display the average on the

screen.

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #04: If statement

Name:____________________ Reg #: ___________________

Lab Objective:

Learn how to use if in programming.

Lab Description:

Use

To specify the conditions under which a statement or group

of statements should be executed.

if (testExpression)

{

// statements

}

The if statement evaluates the test expression inside parenthesis. If test expression is evaluated to true, statements inside the body of if is executed. If test expression is evaluated to false, statements inside the body of if is skipped.

How if statement works?

Flowchart of if Statement

if...else

The if else executes the codes inside the body of if statement if the test expression is true and skips the codes inside the body of else.If the test expression is false, it executes the codes inside the body

of else statement and skips the codes inside the body of if.

How if...else statement works?

Flowchart of if...else

C++ Nested if...else

The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.

The nested if...else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

Syntax of Nested if...else

if (testExpression1) { // statements to be executed if testExpression1 is true } else if(testExpression2) { // statements to be executed if testExpression1 is false and testExpression2 is true } else if (testExpression 3) { // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true } . . else { // statements to be executed if all test expressions are false }

Nested If:

In C++ we can use if statement in the

another else block. or we can also include if

block in the another if block.

Syntax : C++ Nested If

if( boolean_expression 1)

{

// Executes when the boolean expression 1 is true

if(boolean_expression 2)

{

// Executes when the boolean expression 2 is true

}

}

Example : Nested If

We can nest else if…else in the similar way as you

have nested if statement.

Example : Nested If-else

#include <iostream>

using namespace std;

int main ()

{

int marks = 55;

if( marks >= 80) {

cout << "U are 1st class !!";

}

else {

if( marks >= 60) {

cout << "U are 2nd class !!";

}

else {

if( marks >= 40) {

cout << "U are 3rd class !!";

}

else {

cout << "U are fail !!";

}

}

}

return 0;

}

Task1:

Write a program to print positive number entered by the user.

If the user enters negative number print number entered is positive otherwise print number is

negative.

Task2:

Program to check whether an integer is positive, negative or zero.

Task3:

Input : Mark

Process : If mark greater than and equal to 75, score will be A

If mark less than 75 and greater than and equal to 60, score will be B

If mark less than 60 and greater than and equal to 45, score will be C

If mark less than 30, score will be D

Output : Print the grade of your score.

Task4:

Find Largest Number Using Nested if...else statement.

Check whether the number entered by the user is positive or not. If it is positive then calculate

how many digits the number have.

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #05: INTRODUCTION TO FOR LOOPS, SWITCH CASE

Name:____________________ Reg #: ___________________

Lab Objective:

To practice for loops and switch cases and to get better understanding of

how to use them.

Lab Description:

A for loop is a repetition control structure that allows you to

efficiently write a loop that needs to execute a specific

number of times.

Syntax:

The syntax of a for loop in C++ is −

for ( init; condition; increment ) { statement(s); }

Figure 2: the loop’s logic.

Example int main (){

}

Output:

Other Forms of the Update Expression :

You are not limited to using increment statements in the update expression. Here is a loop that

displays all the even numbers from 2 through 100 by adding 2 to its counter:

And here is a loop that counts backward from 10 down to 0:

Defining a Variable in the for Loop’s Initialization Expression:

Not only may the counter variable be initialized in the initialization expression, it may be defined

there as well. The following code shows an example.

Using Multiple Statements in the Initialization and Update Expressions:

It is possible to execute more than one statement in the initialization expression and the update

expression. When using multiple statements in either of these expressions, simply separate the

statements with commas. For example

Omitting the for Loop’s Expressions:

The initialization expression may be omitted from inside the for loop’s parentheses if it has already

been performed or no initialization is needed. Here is an example

Nested Loops:

A loop that is inside another loop is called a nested loop. A clock is a good example of something

that works like a nested loop. The second hand, minute hand, and hour hand all spin around the face

of the clock. Each time the hour hand increments, the minute hand increments 60 times. Each time

the minute hand increments, the second hand increments 60 times. Here is a program segment with

a for loop that partially simulates a digital clock. It displays the seconds from 0 to 59:

Example

Output:

Switch case

switch...case is a branching statement used to perform action based on available choices,

instead of making decisions based on conditions. Using switch...case you can write more

clean and optimal code than if...else statement. switch...case only works with integer,

character and enumeration constants.

Lab Tasks:

Task1: C++ program to Print Table of any Number.

The concept of generating table of any number is multiply particular number from 1 to 10.

num * 1

num * 2

num * 3

num * 4

num * 5

num * 6

num * 7

num * 8

num * 9

num * 10

Task2: Find power of any number using for loop.

Task3: Sum of Natural Numbers using loop.

Task4:C++ program to find sum of digits of a number.

Sum of digits means add all the digits of any number, for example we take any number like

358. Its sum of all digit is 3+5+8=16. Using given code we can easily write c++ program.

Task 5: Program to Generate Factorial a Certain Number

Factorial of any number is the product of an integer and all the integers below it for example

factorial of 4 is 4! = 4 * 3 * 2 * 1 = 24

Task7: Write a C++ program that will print the following pattern. * ** *** **** ***** ****** *******

Write a C program print total number of days in a month using switch case. Write a C program to check whether an alphabet is vowel or consonant using

switch case.

Think??

What will be the output of the C program?

#include<stdio.h>

int main()

{

for(5;2;2)

{

cout<<"Hello";

}

return 0;

}

What will be the output of the C program, if input is 6?

#include<stdio.h>

int main()

{

int i;

for(i = 0; i>9; i+=3)

{

cout<<"for ";

}

return 0;

}

What will be the output of the C ++ program.

#include<stdio.h>

int main()

{

for(;;)

{

cout<<”10”;

}

return 0;

}

What will be the output of the C program?

int main()

{

int fun=5;

cout<<"C++ for loop ";

int x = 5;

for(x=0;x<=fun;x++)

{

cout<<x;

}

return 0;

}

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #06: While & Do While Loops

Name:____________________ Reg #: ___________________

Lab Objective:

To have better understanding regarding loops.

Lab Description:

A loop is part of a program that repeats. The while loop

has two important parts: (1) an expression that is

tested for a true or false value, and (2) a statement or

block that is repeated as long as the expression is true.

The while Loop Is a Pretest Loop ,which means it tests

its expression before each iteration whereas the do-

while loop is a posttest loop, which means its expression

is tested after each iteration.

Infinite Loops:

If a loop does not have a way of stopping, it is

called an infinite loop. An infinite loop continues to

repeat until the program is interrupted. Here is an

example of an infinite loop:

We can make this loop finite by adding a line as

shown below

Examples: The following example averages a series of three test scores for

a student. After the average is displayed, it asks the user if he or she wants

to average another set of test scores. The program repeats as long as the

user enters Y for yes.

Example OUTPUT

Lab Tasks:

Task1: program to print all natural numbers from 1 to n using while loop

Task2: program to print natural numbers in reverse from n to 1 using while loop

Task3: program to print all even numbers between i to n using while loop.

Task4: Program to Generate Fibonacci Sequence up to a Certain Number. The Fibonacci

sequence is a series of numbers where a number is found by adding up the two

numbers before it. Starting with 0 and 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and

so forth.

Task 5: Take i and n two inputs from user and print n^i of the number.

Task6: Write a method with a while loop that computes the sum of first n positive integers:

sum = 1 + 2 + 3 + … + n.

Task7: Write a do-while loop that asks the user to enter two numbers. The numbers should

be added and the sum displayed. The user should be asked if he or she wishes to perform

the operation again. If so, the loop should repeat; otherwise it should terminate.

Task8: Convert the following while loop to a do-while loop:

int x = 1;

while (x > 0)

{

cout << "enter a number: ";

cin >> x;

}

Think??

What will the following program segments display?

What’s wrong with the following while loop?

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #07: FUNCTIONS

Name:____________________ Reg #: ___________________

Lab Objective:

To have better understanding regarding functions and .

Lab Description:

A function is a collection of statements that performs a

specific task. So far you have experienced functions as

you have created a function named main in every

program you’ve written. Functions are commonly used

to break a problem down into small manageable pieces.

This approach is sometimes called divide and conquer

because a large problem is divided into several smaller

problems that are easily solved.

This benefit of using functions is known as code reuse

because you are writing the code to perform a task once

and then reusing it each time you need to perform the

task

Defining and Calling Functions:

A function call is a statement that causes a function to

execute. A function definition contains the statements

that make up the function. When creating a function,

you must write its definition. All function definitions

have the following parts:

1. Return type: A function can send a value to the

part of the program that executed it. The return

type is the data type of the value that is sent

from the function.

2. Name: You should give each function a

descriptive name. In general, the same rules that

apply to variable names also apply to function

names.

3. Parameter list: The program can send data into a

function. The parameter list is a list of variables

that hold the values being passed to the function.

4. Body: The body of a function is the set of

statements that perform the function’s operation.

They are enclosed in a set of braces.

Void Functions:

It isn’t necessary for all functions to return a value,

however. Some functions simply perform one or

more statements, which follows terminate. These

are called void functions. The display Message

function, which follows, is an example.

Calling a Function:

A function is executed when it is called. Function

main is called automatically when a program starts,

but all other functions must be executed by

function call statements. When a function is called,

the program branches to that function and

executes the statements in its body

Function Header void displayMessage()

Function Call displayMessage();

Functions may also be called in a hierarchical, or layered, fashion.

Function prototype:

A function prototype eliminates the need to place a

function definition before all calls to the function.

You must place either the function definition or either/the function prototype ahead of all calls to

the function. Otherwise the program will not compile.

Sending Data into a Function:

When a function is called, the program may send

values into the function. Values that are sent into a

function are called arguments. In the following

statement the function pow is being called and two

arguments, 2.0 and 4.0, are passed to it:

result = pow(2.0, 4.0);

By using parameters, you can design your own

functions that accept data this way. A parameter is

a special variable that holds a value being passed

into a function. Here is the definition of a function

that uses a parameter:

void displayValue(int num)

{ cout << "The value is " << num << endl; }

The return Statement and Returning a Value from a Function :

The return statement causes a function to end immediately. A

function may send a value back to the part of the program that

called the function this is known as returning a value. Here is an

example of a function that returns an int value:

However, we could have eliminated the result variable and returned

the expression num1 + num2, as shown in the following code:

A function can also return a Boolean value instead of integer or

double or character. The following example shows that.

Examples: The following example demonstrates a function with a parameter.

Example OUTPUT

I am passing several values to displayValue. The value is 5 The value is 10 The value is 2 The value is 16

Lab Tasks:

Task1: Write a function named times Ten . The function should have an integer

parameter named number. When times Ten is called, it should display the

product of number times ten. (Note: just write the function. Do not write a

complete program.)

Task2: Write a function asks the user to enter the radius of the circle and then returns that number as a double. Write another function that takes this radius as input and returns the area of circle.

Task3: Write a function accepts an integer argument and tests it to be even or odd. The function returns true if the argument is even or false if the argument is odd. The return value should be bool. In main take a integer input from user and pass it to the function.

Task4: Write a program with a function that takes two int parameters, adds them together, then returns the sum. The program should ask the user for two numbers, then call the function with the numbers as arguments, and tell the user the sum.

Task 5: Write a value returning function that receives three integers and returns the largest of the three. Assume the integers are not equal to one another.

Task6: Write a program in C++ to swap two numbers using function.

Task7: Write a function which converts an uppercase letter 'A'{'Z' to the corresponding lowercase letter. If the parameter is not a letter it must be returned unchanged. Write a main program which calls the function.

Task8: Write a program will ask the user to enter the width and length of a rectangle and then display the rectangle’s area. The program calls the following functions:

1. getLength – This function should ask the user to enter the rectangle’s length and then return that value as a double.

2. getWidth – This function should ask the user to enter the rectangle’s width and then return that value as a double .

3. getArea – This function should accept the rectangle’s length and width as arguments and return the rectangle’s area. The area is calculated by multiplying the length by the width.

4. displayData – This function should accept the rectangle’s length, width, and area as arguments and display them in an appropriate message on the screen. INITIAL array:

Think??

What is the output of the following program?

Indicate which of the following is the function prototype, the function header,

and the function call: void showNum(double num)

void showNum(double); showNum(45.67);

The following program skeleton asks for the number of hours you’ve worked and your hourly pay rate. It then calculates and displays your wages. The function showDollars, which you are to write, formats the output of the wages.

How many return values may a function have?

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #08: Arrays

Name:____________________ Reg #: ___________________

Lab Objective:

To be able to declare an array.

To be able to perform fundamental operations on a two-dimensional array.

To be able to pass two-dimensional arrays as parameters.

To be able to view a two-dimensional array as an array of arrays.

Lab Description:

An array is a series of elements of the same type placed

in contiguous memory locations that can be individually

referenced by adding an index to a unique identifier.

That means that, for example, five values of

type int can be declared as an array without having to

declare 5 different variables (each with its own

identifier). Instead, using an array, the five int values

are stored in contiguous memory locations, and all five

can be accessed using the same identifier, with the

proper index.

For example, an array containing 5 integer values of

type int called foo could be represented as:

where each blank panel represents an element of the

array. In this case, these are values of type int. These

elements are numbered from 0 to 4, being 0 the first

and 4 the last; In C++, the first element in an array is

always numbered with a zero (not a one), no matter its

length.

Initializing arrays:

By default, regular arrays of local scope (for example,

those declared within a function) are left uninitialized. This means that none of its elements are set to any

particular value; their contents are undetermined at the point the array is declared.

But the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those

initial values in braces {}. For example:

int foo [5] = { 16, 2, 77, 40, 12071 };

This statement declares an array that can be

represented like this:

The number of values between braces {} shall not be

greater than the number of elements in the array. For example, in the example above, foo was declared

having 5 elements (as specified by the number enclosed in square brackets, []), and the braces {} contained

exactly 5 values, one for each element. If declared with less, the remaining elements are set to their default

values (which for fundamental types, means they are

filled with zeroes). For example:

int bar [5] = { 10, 20, 30 };

Will create an array like this:

The initializer can even have no values, just the braces:

int baz [5] = { };

This creates an array of five int values, each initialized

with a value of zero:

Accessing the values of an array:

The values of any of the elements in an array can be

accessed just like the value of a regular variable of the

same type. The syntax is:

name[index]

Following the previous examples in which foo had 5

elements and each of those elements was of type int,

the name which can be used to refer to each element is

the following:

For example, the following statement stores the value

75 in the third element of foo:

foo [2] = 75;

and, for example, the following copies the value of the

third element of foo to a variable called x:

x = foo[2];

Therefore, the expression foo[2] is itself a variable of

type int.

Examples: the following examples displays the sum of elements of array.

Example OUTPUT

12206

The following example shows how to Find the Highest

and Lowest Values in a Numeric Array

HIGHEST LOWEST

Implicit Array Sizing:

It’s possible to define an array without specifying its

size, as long as you provide an initialization list. C++

automatically makes the array large enough to hold all

the initialization values. For example, the following

definition creates an array with five elements:

double ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

Printing the Contents of an Array:

Suppose we have the following array definition:

onst int SIZE = 5; int numbers [SIZE] = {10, 20, 30, 40, 50};

You now know that an array’s name is seen as the

array’s beginning memory address. This explains why

the following statement cannot be used to display the

contents of array :

cout << numbers << endl; //Wrong!

When this statement executes, cout will display the

array’s memory address, not the array’s contents. You

must use a loop to display the contents of each of the array’s elements, as follows.

for (int count = 0; count < SIZE; count++)

cout << numbers[count] << endl;

Two-Dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a

multidimensional array declaration −

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional

5 . 10 . 4 integer array −

int threeD[5][10][4];

The simplest form of the multidimensional array is the two-

dimensional array. A two-dimensional array is, in essence, a list of

one-dimensional arrays. To declare a two-dimensional integer array

of size x,y, you would write something as follows −

type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be

a valid C++ identifier.

A two-dimensional array can be think as a table, which will have x

number of rows and y number of columns. A 2-dimensional array a,

which contains three rows and four columns can be shown as below

Thus, every element in array a is identified by an element name of

the form a[ i ][ j ], where a is the name of the array, and i and j are

the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays

Multidimensioned arrays may be initialized by specifying bracketed

values for each row. Following is an array with 3 rows and each row

have 4 columns.

int a[3][4] = {

{0, 1, 2, 3} , /* initializers for row indexed by 0 */

{4, 5, 6, 7} , /* initializers for row indexed by 1 */

{8, 9, 10, 11} /* initializers for row indexed by 2 */

};

The nested braces, which indicate the intended row, are optional.

The following initialization is equivalent to previous example −

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the

subscripts, i.e., row index and column index of the array. For

example −

int val = a[2][3];

Example:

Example OUTPUT

Lab Tasks:

Task1: Write a program that asks for the number of hours worked by six employees.

It stores the values in an array.

Task2: Write a program that asks the user to type 10 integers of an array. The program must compute and write how many integers are greater than or equal to 10.

Task3: Write a C++ program to swap first and last element of an integer 1-d array.

Task4: Write a C++ function that multiplies two matrices using arrays.

Task5: Write a C++ function to add two matrices using multidimensional arrays.

Task 6: Write a program in C++ to find the transpose of a matrix.

Task 7: Write a function in C++ to find out the highest number in a 2 Dimensional array.

Think??

Correct the errors in the following program

What's wrong with the following array definitions?

The following program skeleton contains a 20-element array of int s called fish.

When completed, the program should ask how many fish were caught by fishermen 1 through 20, and store this data in the array. Complete the program.

Is each of the following a valid or invalid array definition? (If a definition is invalid, explain why.)

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #09: Pointers

Name:____________________ Reg #: ___________________

Lab Objective:

To have better understanding regarding pointers.

Lab Description:

Pointers are powerful features of C++ that differentiates it from

other programming languages like Java and Python.

Pointers are used in C++ program to access the memory and

manipulate the address.

Address in C++

To understand pointers, you should first know how data is stored

on the computer.

Each variable you create in your program is assigned a location in

the computer's memory. The value the variable stores is actually

stored in the location assigned.

To know where the data is stored, C++ has an & operator.

The & (reference) operator gives you the address occupied by a

variable.

If var is a variable then, &var gives the address of that variable.

Example:

In the following example, you may not get the same result on your

system.

The 0x in the beginning represents the address is in hexadecimal

form.

Notice that first address differs from second by 4-bytes and second

address differs from third by 4-bytes.

This is because the size of integer (variable of type int) is 4 bytes in

64-bit system.

Example OUTPUT

Pointers Variables

C++ gives you the power to manipulate the data in the

computer's memory directly. You can assign and de-assign

any space in the memory as you wish. This is done using

Pointer variables.

Pointers variables are variables that points to a specific

address in the memory pointed by another variable.

How to declare a pointer?

int *p

Or,

int* p

The statement above defines a pointer variable p. It holds the

memory address.

The asterisk is a dereference operator which means pointer

to.Here, pointer p is a pointer to int, i.e., it is pointing to an integer

value in the memory address.

Reference operator (&) and Deference operator (*)

Reference operator (&) as discussed above gives the address of a

variable.To get the value stored in the memory address, we use the

dereference operator (*).

For example: If a number variable is stored in the memory

address 0x123, and it contains a value 5.

The reference (&) operator gives value 0x123, while

the dereference (*) operator gives the the value 5.

The (*) sign used in the declaration of C++ pointer is not the

dereference pointer. It is just a similar notation that creates a

pointer.

Example:

Following Program to demonstrate the working of pointer

Example OUTPUT

int main() {

int *pc, c;

c = 5;

cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c

cout<<"Address that pointer pc holds(pc):"<<pc<<endl;

cout<<"Content of the address pointer pc holds (*pc): "<< *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.

cout<<"Address pointer pc holds (pc):"<<pc<<endl;

cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;

cout << "Address of c (&c): " << &c << endl;

cout << "Value of c (c): " << c << endl << endl;

return 0;}

;

The “void” type pointer:

void * p;

The pointer variable “p” can hold the memory address of variable

of any data type.

Pointers and Arrays:

There is a close relationship between pointers and arrays.when

an array is declared the array name is the starting address of the

array. For example

int x[5];

int * p;

p=x;

A pointer to a pointer

A pointer to a pointer is a form of multiple indirection or a chain

of pointers. Normally, a pointer contains the address of a

variable. When we define a pointer to a pointer, the first pointer

contains the address of the second pointer, which points to the

location that contains the actual value as shown below.

A variable that is a pointer to a pointer must be declared as such.

This is done by placing an additional asterisk in front of its name.

For example, following is the declaration to declare a pointer to

a pointer of type int as

int **var;

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c. Then,

1. int c, *pc;

2. pc=c; /* Wrong! pc is address whereas, c is not an address. */

3. *pc=&c; /* Wrong! *pc is the value pointed by address whereas,

%amp;c is an address. */

4. pc=&c; /* Correct! pc is an address and, %amp;pc is also an

address. */

5. *pc=c; /* Correct! *pc is the value pointed by address and, c is

also a value. */

Call by Reference

You learned about passing arguments to a function. This method

used is called passing by value because the actual value is passed.

However, there is another way of passing an argument to a

function, where the actual value of the argument is not passed.

Instead, only the reference to that value is passed.

Example: Passing by reference without pointers Example OUTPUT

Before swapping a = 1 b = 2 After swapping a = 2 b = 1

Example: Passing by reference with pointers Example OUTPUT

Before swapping a = 1 b = 2 After swapping a = 2 b = 1

Lab Tasks:

Task1: Write a C++ program to accept five integer values in an array using pointer

offset notation.

Task2: Write a C++ function to sort an array of ten integer values in ascending order.

Task 3: Write a program in C++ to find the maximum number between two numbers using a

pointer.

Test Data :

Input the first number : 5

Input the second number : 6

Expected Output :6 is the maximum number.

Task 4: Write a program in C++ to print all permutations of a given string using pointers.

Expected Output :

The permutations of the string are :

abcd abdc acbd acdb adcb adbc bacd badc bcad bcda bdca bdac cbad cbda cabd

cadb cdab cdba db

ca dbac dcba dcab dacb dabc

Task 5: Write a program in C to swap elements using call by reference. Go to the editor

Test Data :

Input the value of 1st element : 5

Input the value of 2nd element : 6

Input the value of 3rd element : 7

Expected Output : The value before swapping are : element 1 = 5 element 2 = 6 element 3 = 7 The value after swapping are : element 1 = 7 element 2 = 5 element 3 = 6

Task6: Write a program to convert kilogram to grams by passing pointers as arguments to

the function.

Task7: Write a program to print the string character by character.

Task8: Write a program to find the length of a string by using pointers.

Think??

Point out error(s) if any in the following programs.

A.

What is the output of the program?

A.

B.

C.

Which of the following statements correctly declare a function that receives a pointer to pointer to a pointer to a float and returns a pointer to a pointer to a pointer to a pointer to a float?

A. float **fun(float***);

B. float *fun(float**);

C. float fun(float***);

D. float ****fun(float***);

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #10: Structures

Name:____________________ Reg #: ___________________

Lab Objective:

To have better knowledge about structures and how to use

them.

Lab Description:

C++ arrays allow you to define variables that combine several

data items of the same kind, but structure is another user

defined data type which allows you to combine data items of

different kinds.

Structures are used to represent a record, suppose you want

to keep track of your books in a library. You might want to

track the following attributes about each book −

Title

Author

Subject

Book ID

Defining a Structure

To define a structure, you must use the struct statement. The

struct statement defines a new data type, with more than one

member, for your program.

struct Books {

char title[50];

char author[50];

char subject[100];

int book_id;

};

Accessing Structure Members :

The dot operator (.) allows you to access structure members in

a program. C++ provides the dot operator (a period) to access

the individual members of a structure. the following statement

demonstrates how to access:

Books b;

b. book_id=5;

Examples: The following example demonstrates use of structures.

Example OUTPUT

Comparing Structure Variables:

You cannot perform comparison operations directly on structure variables.

For example, assume that circle1 and circle2 are Circle structure

variables. The following statement will cause an error.

if (circle1 == circle2) // Error!

In order to compare two structures, you must compare the individual

members, as shown in the following code.

if (circle1.radius == circle2.radius && circle1.diameter ==

circle2.diameter && circle1.area == circle2.area)

Initializing a Structure:

The members of a structure variable may be initialized with starting values when the structure variable is defined. A structure variable may be initialized when it is defined, in a fashion similar to the initialization of an array. Assume the following structure declaration exists in a program:

A variable may then be defined with an initialization list, as shown in the following:

CityInfo location = {"Asheville", "NC", 50000, 28};

This statement defines the variable location. The first value in the initialization list is assigned to the first declared member, the second value in the initialization list is assigned to the second member, and so on. The location variable is initialized in the following manner:

The string“Asheville” is assigned to location.cityName

The string“NC” is assigned to location.state

50000 is assigned to location.

population 28 is assigned to location.distance

You do not have to provide initializers for all the members of a structure variable. For example, the following statement only initializes the cityName member of location :

CityInfo location = {"Tampa"};

The state, population, and distance members are left uninitialized. The following statement only initializes the cityName and state members, while leaving population and distance uninitialized:

CityInfo location = {"Atlanta", "GA"};

If you leave a structure member uninitialized, you must leave all the members that follow it uninitialized as well. C++ does not provide a way to skip members in a structure. For example, the following statement, which attempts to skip the initialization of the population member, is not legal:

CityInfo location = {"Knoxville", "TN", , 90}; // Illegal!

Arrays of Structures:

Arrays of structures can simplify some programming tasks.

An array of structures is defined like any other array. Assume the following structure declaration exists in a program:

The following statement defines an array, bookList, that has 20 elements. Each element is a BookInfo structure.

BookInfo bookList[20];

Each element of the array may be accessed through a subscript. For example, bookList[0] is the first structure in the array, bookList[1] is the second, and so forth.

To access a member of any element, simply place the dot operator and member name after the subscript. For example, the following expression refers to the title member of bookList[5]

bookList[5].title

The following loop steps through the array, displaying the data stored in each element:

Example:

The following example uses an array of structures.

Example OUTPUT

Lab Tasks:

Task1: Write C++ Program to Store Information of a Student in a Structure. It stores the information (name, roll and marks entered by the user) of a student in a structure and displays it on the screen.

Task2: Write a C++ program to calculate difference between two time period.

Task3: Write a C++ Program to Add Complex Numbers by Passing Structure to a

Function. Where a complex number can be represented as a+bi .

Task4: Write a C++ program to calculate distance between two points (on Cartesian plane) using Euclidean distance i.e. sqrt((x2-x1)^2+(y2-y1)^2).

Task 5: Write a C++ program that creates a structure array and store the information of 10 employees. Employee is a structure having employeeName and employeeID and Salary as attributes. Write a function

o void DisplayEmployeesRecord (employee a[ ], int s) that displays the array.

o Void StoreToFile (employee a[ ], ofstream f, int s) that store each employee information in a file in the following format

employeeName1 employeeid1 salary1

employeeName2 employeeid2 salary2

employeeName3 employeeid1 salary3

o Void storeToArray(employee a[ ], ifstream f, int s) that reads the file and store data to array

Task6: Write a program in C++ to stores data about a circle (radius, diameter & diameter) in a structure. Create two circle objects and compare if the two circles are equal or not.

Task7: Write a structure declaration to hold the following data about a savings account: Account Number ( string object) Account Balance ( double ) Interest Rate ( double ) Average Monthly Balance ( double )

Task8: Write a program that uses a structure to store the following weather data for a particular month: Total Rainfall High Temperature Low Temperature Average Temperature The program should have an array of 12 structures to hold weather data for an entire year. When the program runs, it should ask the user to enter data for each month. (The average temperature should be calculated.) Once the data are entered for all the months, the program should calculate and display the average monthly rainfall, the

total rainfall for the year, the highest and lowest temperatures for the year (and the months they occurred in), and the average of all the monthly average temperatures.

Think??

Look at the following structure declaration. struct Point { int x;

int y; }; Write statements that A) Define a Point structure variable named center B) Assign 12 to the x member of center C) Assign 7 to the y member of center D) Display the contents of the x and y members of center

Point out the errors in the following programs.

A.

B.

C.

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #11: Strings

Name:____________________ Reg #: ___________________

Lab Objective:

To have better knowledge about strings and how to use

them.

Lab Description:

C++ provides following two types of string representations − • The C-style character string. • The string class type introduced with Standard C++.

The C-Style Character String The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello." char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; If you follow the rule of array initialization, then you can write the above statement as follows − char greeting[] = "Hello"; Following is the memory presentation of above defined string in C/C++ −

Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string − Live Demo #include <iostream> using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: "; cout << greeting << endl; return 0; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello C++ supports a wide range of functions that manipulate null-terminated strings −

Sr.No Function & Purpose

1 strcpy(s1, s2);

Copies string s2 into string s1.

2 strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3 strlen(s1);

Returns the length of string s1.

4 strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5 strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6 strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions − Live Demo #include <iostream> #include <cstring> using namespace std; int main () { char str1[10] = "Hello"; char str2[10] = "World"; char str3[10];

int len ; // copy str1 into str3 strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl; // concatenates str1 and str2 strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl; // total lenghth of str1 after concatenation len = strlen(str1); cout << "strlen(str1) : " << len << endl; return 0; } When the above code is compiled and executed, it produces result something as follows − strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10

The String Class in C++ The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example − Live Demo #include <iostream> #include <string> using namespace std; int main () { string str1 = "Hello"; string str2 = "World"; string str3; int len ; // copy str1 into str3 str3 = str1; cout << "str3 : " << str3 << endl; // concatenates str1 and str2 str3 = str1 + str2; cout << "str1 + str2 : " << str3 << endl; // total length of str3 after concatenation len = str3.size();

cout << "str3.size() : " << len << endl; return 0; } When the above code is compiled and executed, it produces result something as follows − str3 : Hello str1 + str2 : HelloWorld str3.size() : 10

Tasks

1. String Length

Write a function that returns an integer and accepts a pointer to a C-string as an argu- ment. The function should count the number of characters in the string and return that number. Demonstrate the function in a simple program that asks the user to input a string, passes it to the function, and then displays the function’s return value.

2. Backward String

Write a function that accepts a pointer to a C-string as an argument and displays its contents backward. For instance, if the string argument is “Gravity” the function should display “ytivarG”. Demonstrate the function in a program that asks the user to input a string and then passes it to the function.

3. Word Counter

Write a function that accepts a pointer to a C-string as an argument and returns the number of words contained in the string. For instance, if the string argument is “Four score and seven years ago” the function should return the number 6. Demonstrate the function in a program that asks the user to input a string and then passes it to the func- tion. The number of words in the string should be displayed on the screen. Optional Exercise: Write an overloaded version of this function that accepts a string class object as its argument.

4. Average Number of Letters

Modify the program you wrote for Problem 3 (Word Counter), so it also displays the average number of letters in each word.

5. Sentence Capitalizer

Write a function that accepts a pointer to a C-string as an argument and capitalizes the first character of each sentence in the string. For instance, if the string argument is “hello. my name is Joe. what is your name?” the function should manipu- late the string so it contains “Hello. My name is Joe. What is your name?”

NUST COLLEGE OF ELECTRICAL & MECHANICAL

ENGINEERING

LAB #12: Recursion and Files

Name:____________________ Reg #: ___________________

Lab Objective:

To have better knowledge about recursion and files.

Lab Description:

Recursion

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.

Base_condition

In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of smaller problems.

int fact(int n)

{

if (n < = 1) // base case

return 1;

else

return n*fact(n-1);

}

In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached.

The idea is represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop recursion. For example, we compute factorial n if we know factorial of (n-1). Base case for factorial would be n = 0. We return 1 when n = 0.

File:

A file is a collection of data that is usually stored on a computer’s disk.

Data can be saved to files and then later reused.The information/data

stored under a specific name on a storage device, is called a file.

ifstream : Input File Stream : This data type can be used only to

read data from files into memory.

ofstream Output File Stream : This data type can be used to

create files and write data to them.

fstream File Stream : his data type can be used to create files,

write data to them, and read data from them.

Using the fstream Data Type You define an fstream object just as

you define objects of other data types. The following statement

defines an fstream object named dataFile .

fstream dataFile;

Opening of the file:

As with ifstream and ofstream objects, you use an fstream object’s

open function to open a file. An fstream object’s open function

requires two arguments, however. The first argument is a string

containing the name of the file. The second argument is a file access

flag that indicates the mode in which you wish to open the file. Here is

an example.

dataFile.open("info.txt", ios::out);

The first argument in this function call is the name of the file, info.txt

.The second argument is the file access flag ios::out . This tells C++ to

open the file in output mode. Output mode allows data to be written

to a file. The following statement uses the ios::in access flag to open

a file in input mode, which allows data to be read from the file.

dataFile.open("info.txt", ios::in);

NOTE: When used by itself, the ios::out flag causes the file’s contents to be deleted if

the file already exists. When used with the ios::in flag, however, the file’s existing

contents are preserved. If the file does not already exist, it will be created.

Example:

This program uses an fstream object to write data to a file.

Example OUTPUT

Example:

This program uses an fstream object to read data from a file.

Example OUTPUT

The getline Function

The problem with above Program can be solved by using the getline

function. The function reads a “line” of data, including whitespace

characters. Here is an example of the function call:

getline(dataFile, str,'\n');

The three arguments in this statement are explained as follows:

dataFile :

This is the name of the file stream object. It specifies the stream

object from which the data is to be read.

str:

This is the name of a string object. The data read from the file will be

stored here.

' \ n' :

This is a delimiter character of your choice. If this delimiter is

encountered, it will cause the function to stop reading. (This

argument is optional. If it’s left out, ' \ n' is the default.) The

statement is an instruction to read a line of characters from the file.

The function will read until it encounters a \n. The line of characters

will be stored in the str object.

Example:

This program demonstrate the working of getline.

Example OUTPUT

Example:

This program uses an fstream object to write data to a file. The file is closed, and an end-of-

file character is automatically written. When the file is reopened, the new output is

appended to the end of the file

Example OUTPUT

Checking for a File’s Existence

Before Opening It Sometimes you want to determine whether a file already exists before

opening it for output. You can do this by first attempting to open the file for input. If the file

does not exist, the open operation will fail. In that case, you can create the file by opening it

for output. The following code gives an example.

Example OUTPUT

Tasks

1. Write a C++ program to write the following contents in the file and then display the

file. The delimiter is $.

Contents of names2.txt Jayne Murphy$47 Jones Circle$Almond, NC 28702\n$Bobbie

Smith$ 217 Halifax Drive$Canton, NC 28716\n$Bill Hammet$PO Box 121$

Springfield, NC 28357\n$ 2. Iterative Factorial

Write an iterative version (using a loop instead of recursion) of the factorial function. Test it with a driver program.

3. Recursive Array Sum

Write a function that accepts an array of integers and a number indicating the number of elements as arguments. The function should recursively calculate the sum of all the numbers in the array. Demonstrate the function in a driver program.

4. Recursive Multiplication

Write a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Remember, multiplication can be performed as repeated addition:

7*4=4+4+4+ 4+4+4+4

5. Recursive Power Function

Write a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. Demonstrate the function in a program.