You are on page 1of 84

LABORATORY

MANUAL
EXPERIMENTS IN

FUNDAMENTALS OF PROGRAMMING

FACULTY OF ENGINEERING

UNIVERSITY OF CENTRAL PUNJAB

1
LIST OF AUTHORS

Sr. # Name Date Modified Contributions


1 Haleema Asif 01/03/2018 Made from scratch.
2
3
4
5
6
7
8
9
10

2
LABORATORY MANUAL

EXPERIMENTS IN

FUNDAMENTALS OF PROGRAMMING
Dr. Ali Faisal

Prof. Haleema Asif


Assistant Professor

University of Central Punjab, Lahore

3
EXPERIMENTS IN

FUNDAMENTALS OF PROGRAMMING

Copyrights © Reserved with the Electrical Engineering Department (EED)

This manual or parts, thereof, may not be reproduced in any from without Permission
of the EED.

4
PREFACE

Dr. Ali Faisal Mr. Ali Faisal Murtaza received the B.Sc. degree from National
University of Sciences and Technology (NUST), Rawalpindi, Pakistan, the M.Sc.
degree from University of Engineering and Technology (UET), Lahore, Pakistan, and
the Ph.D Degree from the Politecnico di Torino, Torino, Italy.
He is currently working as Assistant Professor in the Faculty of Engineering
(Electrical), University of Central Punjab (UCP), Lahore, Pakistan. At UCP, a research
group “Efficient Electrical Energy Systems” is active under his supervision. He is also
an active member of a research group “MPPTRAC” that works in collaboration with
Energy department of Politecnico di Torino, Italy.
His research interests include the design of stand-alone Solar Photovoltaic (PV) systems
including DC micro-grids, DC-DC converters, I-V Curve tracing, Maximum power
point trackers for PV systems, PV plant energy evaluation and partial shading effects.
He has authored/co-authored several research articles in leading journals and
conferences of his field.

5
FUNDAMENTAL OF PROGRAMMING LABORATORY

TABLE OF CONTENTS

EXP# NAME OF EXPERIMENT PAGE#


Implementation of data types, variables, conditional
1 statements and loops 7

Implementation of Nested if-else and Switch statements


2 16

Implementation of For, While and Do-While loops


3 25

Implementation of Nested For, Nested While and Nested


4 Do-While loops

Implementation of Infinite loops, break, goto, continue


5 statements

6 Implementation of 1-D arrays

7 Implementation of 2-D arrays

8 Implementation of Bubble and Selection sorting

Implementation of Linear and Binary searching


9

Implementation of Strings
10

Implementation of Pointers
11

Implementation of Functions
12

Implementation of functions with 1-D arrays


13

Implementation of functions with 2-D arrays and header


14 files

6
Lab 1: Implementation of Data types, variables, conditional statements and
loops

Objectives
1. To understand the basics of program design and algorithm development.
2. To learn the basics of an editor and compiler and be able to compile and run existing
programs.
3. To learn the basics of pseudo codes, flowchart and C++ program.
4. To give quick review of data types, variables, conditional statements and Loops.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory

Data types
C++ provides built-in data types that correspond to integers, characters, floating-point values,
and boolean values. These are the ways that data is commonly stored and manipulated by a
program.

Type Typical Width Bit Typical Range


Char 1 byte -127 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -127 to 127
Int 4 bytes -2147483648 to 2147483647
unsigned int 4 bytes 0 to 4294967295
signed int 2 bytes -2147483648 to 2147483647
short int Range -32768 to 32767
unsigned short int Range 0 to 65,535
signed short int 4 bytes -32768 to 32767
long int 4 bytes -2147483648 to 2147483647
signed long int 4 bytes Same as long int
Float 4 bytes +/- 3.4e +/- 38 (~7 digits)
double 8 bytes +/- 1.7e +/- 308 (~15 digits)
long double 8 bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t 2 or 4 bytes 1 wide character

7
Prog 1.a (Example 1)
#include<iostream>
using namespace std;
int main ()
{
int length, width; //this declare two variables length and width.
cout<< “Enter the length : ”; // cout will print the string
cin>> length; //input the value of length from keyboard.
cout<< “Enter the width : ”;
cin>> width; //input the value of width from keyboard.
cout<<”The area is ”;
cout<< length*width; //display the area.
return 0;
}

Here is a sample run:


Enter the length: 8
Enter the width: 3
The area is 24

Prog 1.b (Example 2)


//this program displays the alphabets.
#include<iostream>
using namespace std;
int main ( )
{
char letter;
for ( letter = ‘A’; letter<= ‘Z’ ; letter++)
{
cout<<letter <<” ”;
}
return 0;
}

Here is a sample run:


ABCDEFGHIJKLMNOPQRSTUVWXYZ

Prog 1.c (Example 3)


/* using Pythagorean theorem to find the length of the
hypotenuse given the lengths of two opposite sites. */

#include<iostream>
#include<math.h> //math.h is required to sqrt and pow functions.
using namespace std;
int main ( )

8
{ double x = 5.0, y =4.0, z ;
z = sqrt ( pow(x,2) + pow(y,2) ) ;
cout<< “The Hypotenuse = ” << z;
return 0;
}

Here is a sample run:


The Hypotenuse = 6.7

The IF…..Else Statement


The if statement cause one of two alternative statements to execute depending upon whether
the condition is true. Its syntax is
If (condition)
Statement 1;
else
Statement 2;
Prog 1.d (Example 4)
// the program prints the minimum of the two integers
#include<iostream>
using namespace std;
int main ( )
{ int m, n;
cout<<”enter two integers :”
cin>>m >>n;
if( m > n ) // if runs when the condition is ture
{ cout<<m<<”is greater than ”<<n<<endl; }
else // else has no condition and runs when if is false
{ cout<< m<<”is less than ”<<n<<endl; }
return 0;
}

Here is sample run:


Enter two integers
56
5 is less than 6

The else …….if construct


Compound statement is usually formatted by lining up the else if phrases to emphasize the
parallel nature of the logic.

Prog 1.e (Example 5)


#include<iostream>
using namespace std;
9
int main ( )
{ char ch;
cout<<"enter a character: ";
cin>>ch;

if(ch>=65 && ch<=90)


{
cout<<"the character entered is a capital letter"<<endl;
}
else if(ch>=97 && ch<=122)
{
cout<<"the character entered is a small letter"<<endl;
}
else if(ch>=48 && ch<=57)
{
cout<<"the character entered is a digit"<<endl;
}
else
{
cout<<"this is a special character"<<endl;
}
return 0;
}

The for statement


It is a control flow statement for specifying iteration, which allows code to be executed repeatedly.
The syntax for the for is

for ( initialization; condition; update )


Prog 1.f (Example 6)
// this program calculates the factorial of a number entered by user
#include<iostream>
using namespace std;
int main ( )
{
int fact=1, number ;
cout<<”enter the number to calculate factorial ”;
cin>>number;

for(int i=1; i<=number; i++ ) // counter-controlled loop


{ fact=fact*i ;
}
cout<<”factorial of ”<<number<<”is”<<answer;
return 0;
}

10
The while statement
The syntax for the while is
initialization;
while ( condition )
{ statements;
Update; }

Prog 1.g ( Example 7 )


#include<iostream>
using namespace std;
int main ( )
{ char letter;
cout<<”enter a letter : ”
cin>>letter;
while ( letter != ‘q’ && letter != ‘z’ )
{ cout<<” the corresponding telephone digit is “;
if( letter=’a’ || letter = ‘b’ || letter= ‘c’ )
{ cout<<” 2 \n ”; }
else if( letter=’d’ || letter = ‘e’ || letter= ‘f’ )
{ cout<<” 3 \n ”; }
else if( letter=’g’ || letter = ‘h’ || letter= ‘i’ )
{ cout<<” 4 \n ”; }
else if( letter=’j’ || letter = ‘k’ || letter= ‘l’ )
{ cout<<” 5 \n ”; }
else if( letter=’m’ || letter = ‘n’ || letter= ‘o’ )
{ cout<<” 6 \n ”; }
else if( letter=’p’ || letter = ‘s’ || letter= ‘r’ )
{ cout<<” 7 \n ”; }
else if( letter=’u’ || letter = ‘t’ || letter= ‘v’ )
{ cout<<” 8 \n ”; }
else if( letter=’w’ || letter = ‘x’ || letter= ‘y’ )
{ cout<<” 9 \n ”; }
else
{ cout<<”you entered a bad letter. ”<<endl;}
return 0;
}

Here is sample output:


Enter a letter: W
The corresponding telephone digit is 9

Flow Chart
It is a type of diagram, that represents an algorithm or process showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation
can give a step-by-step solution to a given problem. Data is represented in these boxes, and arrows
11
connecting them represent flow/direction of flow of data. Flow charts are used in analyzing,
designing, documenting or managing a process or program in various fields.
Symbol Operation Meaning
Start / Stop Represent the beginning and end of the
flow chart.

Input / Output Represent the value of end user and the


result to be displayed.

Processing Represent the arithmetic operations to


compute a value.

Decision making Represent the logical checking to decide


/ checking the flow of the sequence.

Looping Represent loops.

Connection Represent the continuity of the flow


chart.

Flow chart to calculate the Factorial of N


N factorial is represented as N! where the exclamation point means factorial.

For example,
1! = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
4! = 1*2*3*4 = 24

12
...
N! = 1*2*3...*N

N is an integer and is the input to the flowchart. This flowchart has a loop that starts with M = 1 and
increments M until M equals the inputted value N. This program calculates N! by doing each
multiplication.

/* this program calculates the factorial of a number


entered by user*/
#include<iostream>
using namespace std;
int main ( )
{
int N, M=1,F=1 ;
cout<<”enter the number to calculate factorial ”;
cin>>N;
for(int M=1; M<=N; M=M+1 )
// counter-controlled loop
{ F=F*M ; }
cout<<”factorial of ”<<number<<”is”<<F;

return 0;
}

Instructions To Be Followed
a. Students will translate their solution to flow chart. The flowchart will be prepared in
such a manner that it will indicate the step-by-step computations required to solve the
problems.
b. Student will write all C++ program using compiler Microsoft Visual Studio 2013.
c. Student will prepare a report in which he/ she will write a flow chart, and then the
C++ program and paste the screen short of the output window of each problem.
d. Student will achieve bonus marks if they will complete challenge problem in 3 hours.
e. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Tasks To Be Performed


1. Write a program that prompts the user to input the x-y coordinates of a point in a
Cartesian plane. The program should then output a message indicating whether the
point is in origin, is located on the x or y-axis, or appears in particular quadrant.

13
2. Write a program that reads a six-digit integer and prints the sum of its six digits. Use
the quotient and remainder operator to extract the digits from the integer.

3. Write a program that uses while loop to compute the sum of a given number of
squares. For example, if 5 is input, then the program will print 55, which equal 12 +
22 + 32 + 42 + 52 .

4. Write a program that uses any loop to find all of the prime numbers between 1 and
100.

5. Write a code that uses for loop that estimates the value of mathematical constant ‘e’
according to the following formula:
1 1 1 1
𝑒 =1+ + + + + …
1! 2! 3! 4!
Adding more terms to calculate ‘e’ will make the value of ‘e’ more accurate. Prompt
the user to enter the number of terms for the desired accuracy of the value of ‘e’.

Challenge Problem

6. Write a C++ program that solves quadratic equation to find its roots. The roots of a
quadratic equation
𝒂𝒙𝟐 + 𝒃𝒙 + 𝒄 = 𝟎
(Where a is not zero) are given by the formula:
−𝒃 ± √𝒃𝟐 − 𝟒𝒂𝒄
𝟐𝒂
2
The value of the discriminant 𝑏 − 4𝑎𝑐 determines the nature of roots. If the value of
the discriminant is zero then the equation has a single real root. If the value of the
discriminant is positive then the equation has two real roots. If the value of the
discriminant is negative, then the equation has two complex roots. The program takes
values of a, b, and c as input and outputs the roots. Be creative in how you output
complex roots. Include a loop that allows the
user to repeat this calculation for new input values until the user says he wants to end
the program.

14
Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

15
Lab 2: Implementation of Nested If-Else and Switch Statements

Objectives
1. To work with relational and logical operators.
2. To learn and use nested if-else statements.
3. To learn and use the switch statement.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory

Nested if...else
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 (Condition 1)
{
// statements to be executed if condition is true
if(Condition a)
{
// statements to be executed if condition 1 and condition a are
true
}
else if (Condition b)
{
// statements to be executed if condition 1 and condition b are true
}

}
else if(Condition 2)
{
// statements to be executed if condition 1 is false and Condition 2 is
true
}
else if (Condition 3)
{
// statements to be executed if condition 1 and condition 2 is false and
condition 3 is true
}
.
.

16
else
{
// statements to be executed if all test expressions are false }

Relational Operators
Relational expressions evaluate to the integer values 1 (true) or 0 (false). All of these
operators are called binary operators because they take two expressions as operands.

Symbol Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== is equal to

Logical Operators
Sometimes we need to test multiple conditions in order to make a decision. Logical operators
are used for combining simple conditions to make complex conditions.

Symbol Meaning
&& AND logic
|| OR logic
! NOT logic

Operator Precedence and Associativity


Precedence Associativity
() left to right/inside-out
++ -- ! + (unary) - (unary) (type) right to left
*/% left to right
+ (addition) - (subtraction) left to right
< <= > >= left to right
== != left to right
&& left to right
|| left to right
= += -= *= /= %= right to left

Given int a = 5, b = 7, c = 17;

Evaluate each expression as True or False.

17
1. c / b == 2

2. c % b <= a % b

3. b + c / a != c - a

4. (b < c) && (c == 7)

5. (c + 1 - b == 0) || (b = 5)

Prog 2.a (Example 1)


// This program illustrates the use of logical operators
#include <iostream>
using namespace std;
int main()
{ char year;
float gpa;
cout << "What year student are you ?" << endl;
cout << "Enter 1 (freshman), 2 (sophomore), 3 (junior)”;
cout<<” or 4 (senior)" << endl;
cin >> year;
cout << "Now enter your GPA" << endl;
cin >> gpa;
if (gpa >= 2.0 && year == '4')
cout << "It is time to graduate soon" << endl;
else if (year != '4'|| gpa <2.0)
cout << "You need more schooling" << endl;
return 0;
}

Comparing if...else Statements with a Series of if Statements


Consider the following C++ program segments, all of which accomplish the same task:

a) if (month == 1) //Line 1
cout << "January" << endl; //Line 2
else if (month == 2) //Line 3
cout << "February" << endl; //Line 4
else if (month == 3) //Line 5
cout << "March" << endl; //Line 6
else if (month == 4) //Line 7
cout << "April" << endl; //Line 8

18
b) if (month == 1)
cout << "January" << endl;
if (month == 2)
cout << "February" << endl;
if (month == 3)
cout << "March" << endl;
if (month == 4)
cout << "April" << endl;

Program segment (a) is written as a sequence of if...else statements; program segment


(b) is written as a series of if statements. Both program segments accomplish the
same thing. If month is 3, then both program segments output March. If month is 1,
then in program segment (a), the expression in the if statement in Line 1 evaluates to
true. The statement (in Line 2) associated with this if then executes; the rest of the
structure, which is the else of this if statement, is skipped; and the remaining if
statements are not evaluated. In program segment (b), the computer has to evaluate
the expression in each if statement because there is no else statement. As a
consequence, program segment (b) executes more slowly than does program segment
(a).

Switch Structures
The first selection structure, which is implemented with if and if...else statements, usually
requires the evaluation of a (logical) expression. The second selection structure, which does
not require the evaluation of a logical expression, is called the switch structure. C++’s switch
structure gives the computer the power to choose from among many alternatives. Its objective
is to check several possible constant values for an expression

Syntax of the switch statement


switch (expression)
{ case value1:
statements1
break;
case value2:
statements2
break;
.
.
.
case value n:
statements n
break;
default:
statements
}

19
Prog 2.b (Example 2)
#include <iostream>
using namespace std;
int main( )
{ char grade;
cout << "What grade did you earn in Programming I?" << endl;
cin >> grade;
switch( grade ) // This is where the switch statement begins
{
case 'A':
cout << "an A - excellent work!" << endl;
break;
case 'B':
cout << "you got a B - good job" << endl;
break;
case 'C':
cout << "earning a C is satisfactory" << endl;
break;
case 'D':
cout << "while D is passing, there is a problem" << endl;
break;
case 'F':
cout << "you failed - better luck next time" << endl;
break;
default:
cout << "You did not enter an A, B, C, D, or F" << endl;
}
return 0;
}

Prog 2.c (Example 3)

// Simple arithmetic calculator using switch() selection.


#include <iostream>
using namespace std;
int main( )
{ float a, b, result;
char operation;
// Get numbers and mathematical operator from user input
cin >> a >> operation >> b;
// Character constants are enclosed in single quotes
switch(operation)
{
case ’+’:
result = a + b;
break;
case ’-’:
result = a - b;

20
break;
case ’*’:
result = a * b;
break;
case ’/’:
result = a / b;
break;
default:
cout << "Invalid operation. Program terminated." << endl;
return -1;
}
// Output result
cout << result << endl;
return 0;
}

Prog 2.d (Example 4)


# include <iostream>
using namespace std;
int main( )
{ int i;
for(i= 0; i < 5; i++)
{
switch (i)
{
case 0:
cout<<”less than one\n”;
break;
case 1:
cout<<”less than two\n”;
break;
case 2:
cout<<”less than three\n”;
break;
case 3:
cout<<”less than four\n”;
break;
case 4:
cout<<”less than five\n”;
break;
}
}
}

21
Prog 2.e (Nested Switch)
switch (ch1)
{
case ’a’:
cout<<”this a is part of outer switch \n”;
switch (ch2)
{ case ‘a’:
cout<<”this a is part of inner switch \n”;
break;
case ‘b’: //……..
}
break;
case ’b’:
\\.....

Instructions To Be Followed
a. Student will choose an appropriate selection structure by analyzing the problem
statement.
b. Student will achieve bonus marks if he will complete challenge problem in 3 hours.
c. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Tasks To Be Performed


1. Determine the value, true or false , of each of the following Boolean expressions,
assuming that the value of the variable count is 0 and the value of the variable limit is
10. Give your answer as one of the values true or false .

a. (count == 0) && (limit < 20)


b. count == 0 && limit < 20
c. (limit > 20) || (count < 5)
d. !(count == 12)
e. (count == 1) && (x < y)
f. (count < 10) || (x < y)
g. !( ((count < 10) || (x < y)) && (count >= 0) )
h. ((limit/count) > 7) || (limit < 20)
i. (limit < 20) || ((limit/count) > 7)
j. ((limit/count) > 7) && (limit < 0)
k. (limit < 0) && ((limit/count) > 7)
l. (5 && 7) + (!6)

2. Write a program that prompts the user for their quarterly water bill for the last four
quarters. The program should find and output their average monthly water bill. If the

22
average bill exceeds $75, the output should include a message indicating that too
much water is being used. If the average bill is at least $25 but no more than $75, the
output should indicate that a typical amount of water is being used. Finally, if the
average bill is less than $25, the output should contain a message praising the user for
conserving water. Use the sample run below as a model for your output.
Sample Run:
Please input your water bill for quarter 1: 300
Please input your water bill for quarter 2: 200
Please input your water bill for quarter 3: 225
Please input your water bill for quarter 4: 275
Your average monthly bill is $83.3.
You are using excessive amounts of water

3. The University of Guiness charges $3000 per semester for in-state tuition and $4500
per semester for out-of-state tuition. In addition, room and board is $2500 per
semester for in-state students and $3500 per semester for out-of-state students. Write
a program that prompts the user for their residential status (i.e., in-state or out-of-
state) and whether they require room and board (Y or N). The program should then
compute and output their bill for that semester.
Sample Run 1:
Please input "I" if you are in-state or "O" if you are out-of-state: I
Please input "Y" if you require room and board and "N" if you do not: N
Your total bill for this semester is $3000
Sample Run 2:
Please input "I" if you are in-state or "O" if you are out-of-state: O
Please input "Y" if you require room and board and "N" if you do not: Y
Your total bill for this semester is $8000

4. Suppose that a traffic police officer is newly appointed at a location where there is a
user controlled LCD instead of traffic lights. The message appearing on the LCD will
instruct the traffic to get ready, go or stop. Implement a program such that when the
police man presses 1 the message on the LCD appears as “get ready to go”, on
pressing 2 the message is “GO!” and on pressing 3 the message on the screen is
“STOP!”. Implement the code using switch statement inside an infinite loop.

Challenge Problem
5. The BJT has four operating modes depending on the forward and reverse biasing of
the emitter-base and collector-base junctions as shown in the table below:

23
Write a program that takes as input the biasing of both the junctions and then shows as output
that in which mode is the transistor working.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

24
Lab 3: Implementation of For, While and Do-While loops

Objectives
1. To introduce counter and event controlled loops
2. To work with the while loop
3. To introduce the do-while loop
4. To work with the for loop

Equipment
1. PC with Microsoft Visual C++ 2013

Theory

Increment and Decrement Operator


To execute many algorithms we need to be able to add or subtract 1 from a given integer
quantity.
For example:
count = count + 1; // what would happen if we used ==
// instead of = ?
count += 1;
Both of these statements increment the value of count by 1. If we replace “+” with “-” in the
above code, then both statements decrement the value of count by 1. C++ also provides an
increment operator ++ and a decrement operator -- to perform these tasks. There are two
modes that can be used:

count++; // increment operator in the postfix mode


count--; // decrement operator in the postfix mode
++count; // increment operator in the prefix mode
--count; // decrement operator in the prefix mode

The while Loop


The syntax is the following:

while (expression)
{
statement_1;
statement_2;
:
statement_n; }
25
If there is only one statement, then the curly braces can be omitted. When a while loop is
encountered during execution, the expression is tested to see if it is true or false. The block of
statements is repeated as long as the expression is true. Consider the following:
Prog 3.a
#include <iostream>
using namespace std;
int main()
{
char letter = 'a';
while (letter != 'x')
{
cout << "Please enter a letter" << endl;
cin >> letter;
cout << "The letter your entered is " << letter << endl;
}
return 0;
}

Note that this program requires input from the user during execution. Infinite loops can be
avoided, but it would help if the user knew that the 'x' character terminates the execution.

Counters
Suppose we want to find the average of five test scores. We must first input and add the five
scores. This can be done with a counter-controlled loop . Notice how the variable named
test works as a counter. Also notice the use of a constant for the number of tests. This is done
so that the number of tests can easily be changed if we want a different number of tests to be
averaged.
Prog 3.a
#include <iostream>
using namespace std;
const int NUMBEROFTESTS = 5;
int main()
{
int score ; // the individual score read in
float total = 0.0; // the total of the scores
float average; // the average of the scores
int test = 1; // counter that controls the loop
while (test <= NUMBEROFTESTS) // the expression is tested
{
cout << "Enter your score on test " << test << ": " << endl;
cin >> score;
total = total + score;
26
test++; }
average = total / NUMBEROFTESTS;
cout<< " test scores is " << average << endl;
return 0;
}

Sentinel Values
Control the execution of a loop by using a sentinel value which is a special value that marks
the end of a list of values. In a variation of the previous program example, if we do not know
exactly how many test scores there are, we can input scores which are added to total until the
sentinel value is input. Sample Program 3.b revises Sample Program 3.a to control the loop
with a sentinel value. The sentinel in this case is -1 since it is an invalid test score. It does not
make sense to use a sentinel between 0 and 100 since this is the range of valid test scores.
Notice that a counter is still used to keep track of the number of test scores entered, although
it does not control the loop. What happens if the first value the user enters is a -1?

Prog 3.b
include <iostream>
using namespace std;
int main()
{
int score ; // the individual score read in
float total = 0.0; // the total of the scores
float average; // the average of the scores
int test = 1; // counter that controls the loop
cout << "Enter your score on test " << test
cout << " (or -1 to exit): " << endl;
cin >> score; // Read the 1st score
while (score != -1) // While we have not entered the sentinel
// (ending) value, do the loop
{
total = total + score;
test++;
cout << "Enter your score on test " << test
cout << " (or -1 to exit): " << endl;
cin >> score; // Read the next score
}
if (test > 1) // If test = 1, no scores were entered
{
average = total / (test - 1);
}
27
cout << "Your average based on " << (test - 1);
cout << " test scores is " << average << endl;
return 0;
}
Notice that the program asks for input just before the while loop begins and again as the last
instruction in the while loop. This is done so that the while loop can test for sentinel data.
Often this is called priming the read and is frequently implemented when sentinel data is
used to end a loop.

The do-while Loop


A do-while loop is similar to a while loop except that the statements inside the loop body are
executed before the expression is tested. The format for a single statement in the loop body is
the following:
do
statement;
while (expression);
Note that the statement must be executed once even if the expression is false. To see the
difference between these two loops consider the code
int num1 = 5;
int num2 = 7;
while (num2 < num1)
{
num1 = num1 + 1;
num2 = num2 - 1;
}
Here the statements num1 = num1 + 1 and num2 = num2 - 1 are never executed since the test
expression num2 < num1 is initially false. However, we get a different result using a do-
while loop:
int num1 = 5;
int num2 = 7;
do
{
num1 = num1 + 1;
num2 = num2 - 1;
} while (num2 < num1);
In this code the statements num1 = num1 + 1 and num2 = num2 - 1 are executed exactly
once. At this point num1 = 6 and num2 = 6 so the expression num2 < num1 is false.
Consequently, the program exits the loop and moves to the next section of code.

The for Loop


The for loop is often used for applications that require a counter.

28
The syntax for the for loop is the following:
for (initialization; test; update)
{
statement_1;
statement_2;
:
statement_n;
}
There are three expressions inside the parentheses of the for statement, separated by
semicolons.
1. The initialization expression is typically used to initialize a counter that must have a
starting value. This is the first action performed by the loop and is done only once.
2. The test expression, as with the while and do-while loops, is used to control the execution
of the loop. As long as the test expression is true,the body of the for loop repeats. The for
loop is a pre-test loop which means that the test expression is evaluated before each iteration.
3. The update expression is executed at the end of each iteration. It typically increments or
decrements the counter.
Prog 3.c
#include <iostream>
using namespace std;
int main()
{
int value;
int total = 0;
int number;
float mean;
cout << "Please enter a positive integer" << endl;
cin >> value;
if (value > 0)
{
for (number = 1; number <= value; number++)
{
total = total + number;
} // curly braces are optional since
mean =(total) / value;
cout << " positive integers is " << mean << endl;
}
else
// there is only one statement
// note the use of the typecast
// operator
cout << "Invalid input - integer must be positive" << endl;
return 0;
}

29
Instructions To Be Followed
a. Student will choose an appropriate repetition structure by analyzing the problem
statement.
b. Student will achieve bonus marks if he will complete challenge problem in 3 hours.
c. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Tasks To Be Performed


1. Find out the solution for the given equation iteratively that at which integer value this
equation will get balance.
𝒙 = 𝒙𝟐 − 𝟐 ∗ 𝒙
2. The ASCII lowercase letters are separated from the uppercase letters by 32. Thus, to
convert a lowercase letter to uppercase, subtract 32 from it. Use this information to
write a program that reads characters from the keyboard. Have it convert all lowercase
letters to uppercase, and all uppercase letters to lowercase, displaying the result. Make
no changes to any other character. Have the program stop when the user enters a
period. At the end, have the program display the number of case changes that have
taken place.

3. Implement a program which takes integers from user and count the number of
positive and negative integers entered. Use a while loop which continues to take input
unless zero is entered by the user. Print the number of positive and negative integers
entered.

4. Implement a program which takes ‘n’ inputs from the user. The value of ‘n’ will be
specified by the user (use cin>>). The program will determine the smallest integer
entered by the user.

5. Implement an automatic decision system for the grading of students of a class. The
grading system categorizes students as ‘pass’, ‘fail’ and ‘average’. Develop a program
that prompts the user for the number of students in the class. The user will then enter
the marks of students one by one. The while loop will continue execution till the
scores of all the students are entered. For each score entered, your program will
determine if the student is pass, average or fail. Print appropriate message indicating
‘pass’, ‘average’ or ‘fail’ on the output screen. The criteria will be as follows:

Pass: marks >= 80


Average: 50 =< marks < 80
Fail < 50

30
6. Display all ASCII characters using while loop.

Challenge Problem
7. Implement a program that evaluates Gregory’s series given as follows:
𝐱𝟑 𝐱𝟓 𝐱𝟕
𝐆=𝐱− + − …
𝟑 𝟓 𝟕
Take the value of variable ‘x’ and the number of terms from the user. Display the
answer on the output screen.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

31
Lab 4: Implementation of Nested For, While and Do-While loops

Objectives
1. Student should be able to work with nested loops.

Equipment
2. PC with Microsoft Visual C++ 2013

Theory
In this section, we give examples that illustrate how to use nested loops to achieve useful
results and process data.
Suppose you want to create the following pattern:
*
**
***
****
*****
for (i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{ cout << "*";
}
cout<<endl;
}
Suppose you want to create the following multiplication table:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50

The multiplication table has five lines. Therefore, we use a for statement to output these lines
as follows:
for (i = 1; i <= 5; i++)
{ for(j = 1; j <= 10; j++)
{ cout<< i * j;
}
cout << endl;
}
32
Suppose you want to create the following output given below:

*****
*****
*****
*****
*****
for(int x=1;x<=5;x++)
{ for(int y=1;y<=5;y++)
{
cout<<“*”;
}
cout<<endl;
}

OBSERVATIONS
The following observation can be made from the above nested for loops examples:

a. The outer for loop controls the number of rows to be displayed


b. The inner for loop control the number or type of characters in each row to be
displayed on the output screen.
c. The character or number to be displayed on the output screen is to be written with a
cout statement inside the inner for loop.
d. The first iteration of outer for loop causes the inner for loop to run from initial value
to the limiting condition.
e. The second iteration of outer for loop starts after the inner for loop has executed to
completion and so on.
f. After the outer for loop begins a new iteration, the looping variables of the inner for
loop are re-initialized.

Display all prime numbers from 1 to 300

#include <iostream.h>
void main()
{ int i, j, c = 0;
for(i = 1; i<=300; i++)
{ for(j = 1; j<=i; j++)
{
if(i%j == 0)
{

33
c++;
}
}
if(c == 2)
{
cout<<i<<" , ";
}
c = 0;
}
cout<<endl;
}
For example, if a programmer wants to print 10 rows of numbers from 0 to 9 such that
each line has numbers from 0 to 9.
#include <iostream.h>
void main()
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i < 10; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}
}
The range of numbers on one line and the number of lines can be controlled by the user.
Consider the following code:
#include <iostream.h>
void main()
{
int numbers,rows;
cin>>numbers;
cin>>rows;
for(int j = 0; j <=rows; j++)
{ for(int i = 0; i <=numbers; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}

34
Instructions To Be Followed
a. Student will choose an appropriate nested repetition structure by analyzing the
problem statement.
b. Student will achieve bonus marks if he will complete challenge problem in 3 hours.
c. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Tasks To Be Performed

1. Display the following figures using nested for or while loops:

* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *

2. Display the following figures using nested for loops:

* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *

3. Display the following figure using nested while loops:

*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

4. Modify the problem in question 3 above such that a user defined character is
displayed instead of asterisks.

5. Implement a code that prints even numbers from 0 to 10 on first row, 0 to 9 on


second row, and 0 to 8 on the third row and so on.

35
6. Implement a program to display the factorial of all numbers from 1 to 10 on the
output screen.

7. Implement a program to display the following pattern on the output screen using
nested for loops.

97 5 3 1
7 5 3 1
5 3 1
3 1
1

Challenge Problem
8. Display the following figure using nested while loops:

Conclusion:

36
Teacher/Supervisor’s signature: _______________________

Date: _______________________

37
Lab 5: Implementation of Infinite loops, break, and goto, statements

Objectives
1. Student should be able to work with infinite loops.
2. Student should know how to handle infinite loops using goto, break commands.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
Infinite Loop:

An infinite loop is one which keeps on running for all values of the loop variable involved.
Essentially, the reason for an infinite loop is that the condition for the loop is always true. If
the condition is never false there will be nothing to stop the loop from running.

GoTo Statement:
The word written after goto is called a label. The label can be any word and is not to be declared
or initialized first like a variable. The label name should not have a space in it. Whenever a
goto statement is executed, the program execution starts from the line of code where the label
is directed. The difference between a break statement a goto statement is that, when the loop
ends using a break statement the program execution continues after the for loop. For a goto
statement, the program execution will start from the label to which the goto statement is
directed. Goto statements can also be used in places other than infinite loops.
1. A simple infinite loop implementation is given in prog1.cpp.
//prog1.cpp
#include <iostream.h>
void main ( )
{
for(;;)
{
cout<<"* ";
}
}

2. The above for loop will display infinite asterisks on the output screen. Other infinite
loops can be implemented such that the condition in the loop is never false. Consider
the following loops:
I.

38
for(int i = 0;;)
{
cout<<"* ";
}
II.
for(int i = 0; i<10;)
{
cout<<"* ";
}

3. In both of the above loops, there is no increment in the value of variable ‘i’ which can
make the condition false. So the value of variable is always 0 which is always true for
the condition in for loop. The following for loop is also infinite loop:

for(int i = 0;i>=0;i++)
{
cout<<"* ";
}

4. The value of variable ‘i’ is initially 0 which is true for the condition. The value of
variable ‘i’ is incremented afterwards which still satisfies the condition. So the
condition never becomes false and this makes an infinite loop.

5. There are several methods to implement an infinite loop that ends at some time. For
this purpose, break or goto statements are used. Prog2.cpp makes use of a break
statement:
//prog2.cpp
#include <iostream.h>

void main ( )
{
int d = 0;
for(;;)
{ cout<<"* ";
d++;
if(d == 10)
{
break;
}
}cout<<endl;
}

39
The above program will display 10 asterisks on the output screen, each time the counter ‘d’ is
incremented. When the value of variable ‘d’ is 10, the if condition becomes true and the loop
ends.

6. A goto statement can also be used to end a loop.

//prog3.cpp
#include <iostream.h>

void main ( )
{
int d = 0;
for(;;)
{
cout<<"* ";
d++;
if(d == 10)
{
goto m1;
}
}
m1:
cout<<endl;
}

7. The following program calculates the average of marks of 10 students in the range from
0 to 100 while making use of goto statement. Any marks beyond that range should be
re-entered.
//prog4.cpp
#include <iostream.h>

void main ( )
{
float marks, sum = 0, avg;
for(int i = 0; i<10; i++)
{
repeat:
cout<<"enter marks "<<i+1<<": ";
cin>>marks;
if(marks<0 || marks>100)
40
{
goto repeat;
}
sum = sum + marks;
}
avg = sum/10;
cout<<"average is: "<<avg<<endl;
}

Lab Tasks To Be Performed


1. Implement a program that keeps on adding all numbers entered by the user. The
program should terminate when the sum becomes more than 100. Display the sum
so far on the output screen.

2. Implement a program that takes a 5 digit number from the user and displays the
reversed number on the output screen. The program should keep on running. If the
user wants to exit the program, ‘n’ should be entered.

3. Implement a program that keeps on adding all numbers entered by the user. The
program should sum the numbers if they are even. If any odd number is entered by
the user, the program should not add it in the sum and terminate.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

41
Lab 6: Implementation of 1-D arrays

Objectives
1. Student should be able to work with one-dimensional arrays.
2. Student should know how to handle infinite loops using goto, break commands.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
An array is defined by its name, size and type of variables it stores. Missing any of these will
result in an error.

An array can be initialized along with declaration. For array initialization it is required to
place the elements separated by commas enclosed within braces.

Int A[5 ]= {11,12,13,14,15};

It is possible to leave the array size open. The compiler will count the array size.
Int B[ ]= {6,7,8,9,15,12};

There are many ways of declaring and initializing an array.

1D ARRAYS USING FOR LOOP :


As you have seen before, initializing 1D arrays with user defined values will be difficult if the
size of the array is large. Repetition loops like for loops are very helpful for this purpose
especially because an array is a consecutive memory block. Another important use of for loop
is with counters. Counters are variables with initial value zero and the value is then incremented
to count for certain things as asked in the question statement.

Consider the following program:


// prog1.cpp
#include <iostream.h>

void main ( )
{

int a[10]; // declaring array of size 10


int b[ ] = {0,1,2,3,4,5,6,7,8,9}; // array of size 10 with 10 values

42
int c[10] = {0,1,2,3,4,5,6,7,8,9}; // array of size 10 with 10 values
int d[10] = {0}; // array of size 10 with all values 0
int e[10] = {1}; // array of size 10 with a[0] = 1 and
// all other locations have a value of 0
}

The first statement of prog1.cpp just creates an array ‘a’ with size 10 to store integer type
variables. The rest of the statements also initialize the array with values.

Consider the following program which initializes the array with user defined values every
time the program is executed:
// prog2.cpp
#include <iostream.h>
void main ( )
{
int a[4]; // declaring array of size 4
cout<<”enter values for 4 locations of array ”<<endl;
cin>>a[0];
cin>>a[1];
cin>>a[2];
cin>>a[3];

cout<<”displaying the array: ”<<endl;


cout<<a[0]<<” ”<<a[1]<<” ”<<a[2]<<” ”<<a[3]<<endl;
}

The prog3.cpp shows how easily we can use a for loop to initialize and display an array of
size 10 with user defined values.

// prog3.cpp
#include <iostream.h>

void main ( )
{
int size = 10, a[10], i;

for(i = 0; i < size; i++)


{
cout<<”enter value for a[”<<i<<”] :”;
cin>>a[i];
43
}
for(i = 0; i < size; i++)
{
cout<<”the array location a[”<<i<<”] = ”<<a[i];
}
}
Consider the following programming code that stores 10 integers in an array, calculates the
sum of the array values and prints the sum.

// prog4.cpp
#include <iostream.h>

void main( )
{
int size = 10, sum = 0, a[10], i;

for(i = 0; i < size; i++)


{
cout<<”enter value for a[”<<i<<”] :”;
cin>>a[i];
}
for(i = 0; i < size; i++)
{
sum += a[i];
}
cout<<”sum of all values of array a is = ”<<sum<<endl;
}
The above program can be modified to calculate the sum with just one for loop.

The prog5.cpp counts the number of even integers entered by the user in an integer array.

// prog5.cpp
#include <iostream.h>

void main ( )
{
int a[10], i, even = 0, odd = 0;

cout<<"initializing array: "<<endl;

44
for(i = 0; i<10; i++)
{
cout<<"enter value for a["<<i<<"] : ";
cin>>a[i];

if(a[i]%2 == 0)
{
even++;
}
}
cout<<"number of even integers in the array: "<<even<<endl;
}
The above program can be modified to count the odd integers as well.

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Tasks To Be Performed


1. Implement a program that declares a 1D array of size 10 from the user. The
program should calculate the sum and then the average (mean) of all values of the
array.

2. Implement a program that declares a 1D array of size 10 from the user. The program
should determine and display the maximum and minimum value present in the array.

3. Implement a program that takes 10 integers from the user in the range 0 to 9 (there
can be repetition). The program should count how many times a specific integer is
entered by the user. Now implement a 1D array of size 10 with all locations initially
set to zero. Each location of the array will now act as a counter for the integers
entered by the user. For example the number of 5’s entered by the user should be
saved in array location a[5] and so on. Display the occurrence of each integer on the
output screen.

4. Complete the program by filling in the code. (Areas in bold)


Run the program with 3 grades per student using the sample data below.
Mary Brown 100 90 90
George Smith 90 30 50
45
Dale Barnes 80 78 82
Sally Dolittle 70 65 80
Conrad Bailer 60 58 71
You should get the following results:
Mary Brown has an average of 93.33 which gives the letter grade of A
George Smith has an average of 56.67 which gives the letter grade of F
Dale Barnes has an average of 80.00 which gives the letter grade of B
Sally Dolittle has an average of 71.67 which gives the letter grade of C
Conrad Bailer has an average of 63.00 which gives the letter grade of D

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

46
Lab 7: Implementation of 2-D arrays

Objectives
1. Student should be able to work with two-dimensional arrays.
2. Student should know how to use 2D arrays used for matrix operations.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
Up till now the 2D arrays were initialized without loops by writing several cin statements.
This approach is not very efficient in dealing with 2D arrays of larger dimensions. An array
of size 3×3 means that there will be 3 rows and 3 values in each row (or 3 columns). The
array a[3][3] will have the locations a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0],
a[2][1] and a[2][2]. 2-D arrays are normally used to model matrices. For this purpose there
must be 2 user defined arrays. The sum of 2 arrays is saved in another array.
The 2D arrays can be declared and/or initialized directly. Consider prog6.a as an example.
// prog6.a
#include <iostream.h>
void main ( )
{
int a[2][2]; // declaring 2×2 array
int b[2][3]; // declaring 2×3 array
int c[2][2] = {{1,2},{3,2}}; // declaring and initializing
int d[3][2] = {{1,2},{3,2}}; // declaring and initializing
int e[2][2] = {{0},{0}}; // declaring & initializing with all values 0
int f[2][2] = {0}; // declaring & initializing with all values 0
int g[2][3] = {{0},{0}}; // declaring & initializing with all values 0
}
In order to initialize this 2-D array with user-defined values, a nested for loop can be
implemented as follows:

// prog6.b
#include <iostream.h>

void main ( )
{
int i,j, a[3][3];

for(i = 0; i< 3; i++)


{

47
for(j = 0; j < 3; j++)
{
cout<<”enter value for a[”<<i<<”][”<<j<<”] :”;
cin>>a[i][j];
}
}
}

In order to initialize and display the 2-D array, consider the following code:

// prog6.c
#include <iostream.h>

void main ( )
{
int i,j, a[3][3];

for(i = 0; i< 3; i++)


{
for(j = 0; j < 3; j++)
{
cout<<”enter value for a[”<<i<<”][”<<j<<”] :”;
cin>>a[i][j];
}
}
cout<<”\nthe array is:”<<endl;
for(i = 0; i<3; i++)
{
for(j = 0; j <3; j++)
{
cout<<a[i][j]<<” ”;
}
cout<<endl;
}
}

Consider a program that implements the addition of two 3×3 matrices. Notice that the program
uses separate loops for initializing and displaying the matrices. This enables an understandable
output.

// prog6.d
#include <iostream.h>

void main ( )
{

48
int i,j,a[3][3],b[3][3],c[3][3];

cout<<”the 1st array is ”<<endl;


for(i = 0; i< 3; i++)
{
for(j = 0; j < 3; j++)
{
cout<<”enter value for a[”<<i<<”][”<<j<<”] :”;
cin>>a[i][j];
}
}

cout<<endl<<”the 2nd array is ”<<endl;


for(i = 0; i<3; i++)
{
for(j = 0; j <3; j++)
{
cout<<”enter value for b[”<<i<<”][”<<j<<”] :”;
cin>>b[i][j];
}
}

cout<<endl<<”the addition of 2 arrays is:”<<endl;


for(i = 0; i<3; i++)
{
for(j = 0; j <3; j++)
{
c[i][j] = a[i][j] + b[i][j];
cout<<c[i][j]<<” ”;
}
cout<<endl;
}
}

The above addition can be done with 2 arrays as well. That is, by adding the two arrays and
saving the result in one of the arrays ‘a’ or ‘b’. Also if the requirement is just to display the
result of addition of two matrices and not to display it, the statement c[i][j] = a[i][j] + b[i][j];
can be replaced by cout<< a[i][j] + b[i][j]<<” ”;.
2D arrays can be used for other purposes as well. The following program determines the sum
and average of a user defined 2D integer array and displays it.

// prog6.e
#include <iostream.h>

void main ( )
{

49
int i,j, a[3][3];
float sum = 0, avg;

for(i = 0; i< 3; i++)


{
for(j = 0; j < 3; j++)
{
cout<<”enter value for a[”<<i<<”][”<<j<<”] :”;
cin>>a[i][j];
sum = sum + a[i][j];
}
}
cout<<”sum = ”<<sum<<endl;
avg = sum/10;
cout<<”average = ”<<avg<<endl;
}

Now consider the programming example to copy the contents of one user-defined array in to
another and displaying the second one.

// prog6.f
#include <iostream.h>

void main ( )
{
int i,j, a[3][3], b[3][3];

for(i = 0; i< 3; i++)


{
for(j = 0; j < 3; j++)
{
cout<<”enter value for a[”<<i<<”][”<<j<<”] :”;
cin>>a[i][j];
}
}

cout<<endl<<”the copied array is:”<<endl;


for(i = 0; i< 3; i++)
{
for(j = 0; j < 3; j++)
{
b[i][j] = a[i][j];
cout<<b[i][j]<<” ”;
}
cout<<endl;
}
}
50
LAB ASSIGNMENTS: __

1. Use prog6.d to implement subtraction of 2 3×2 matrices. Display the matrix that
stores the result of subtraction.

2. Implement a program that multiplies 2 user defined 3×3 matrices, stores the result
of multiplication in a separate matrix and displays that matrix.

3. Implement a program that calculates the determinant of a user defined2×2 matrix.


Also determine the adjoint and inverse of the input matrix. The formula for
inverse of a 2×2 matrix is:
1
𝑖𝑛𝑣 𝐴 = × 𝐴𝑑𝑗𝐴
det(𝐴)
Display the original matrix, the adjoint and inverse of the matrix. Remember to
use float variables for division.
4. The transpose of a matrix is obtained by interchanging the rows and columns of a
matrix. Implement a program that takes a 3×3 matrix from the user. Display the
original matrix. Then take its transpose, store it in another matrix and display the
transpose.

5. Implement a program to initialize a user defined 3×3 matrix. Determine if the matrix
is a scalar matrix or not. Display an appropriate message in either case. For a matrix
to be scalar, the following properties are satisfied:

𝑥 (𝑎𝑛𝑦 𝑖𝑛𝑡𝑒𝑔𝑒𝑟 𝑣𝑎𝑙𝑢𝑒) 𝑓𝑜𝑟 𝑖 == 𝑗


𝑎𝑖𝑗 = {
0 𝑓𝑜𝑟 𝑖 ≠ 𝑗

6. Implement a program that determines the maximum and minimum value of a 4×4
user defined array. Display the maximum and minimum value of the array.

7. Implement a program that initializes 2 3x3 user defined arrays. The program should
swap the values of the two arrays. Display the arrays before and after swapping.

Conclusion:

51
Teacher/Supervisor’s signature: _______________________

Date: _______________________

52
Lab 8: Implementation of sorting and searching

Objectives
1. Student should be able to implement bubble and selection sorting.
2. Student should be able to implement binary and linear search.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory

SELECTION SORT:

Selection sort is a sorting algorithm that is used for in-place sorting. Selection sort is noted for its
simplicity, and also has performance advantages over more complicated algorithms in certain
situations.

Algorithm:

The algorithm for selection sort is as follows:


Input: An array A[1..n] of n elements.
Output: A[1..n] sorted in ascending order.

for i  0 to n - 1
ki
for j  i + 1 to n {Find the i th smallest element.}
if A[j] < A[k] then k  j
end for
if k  i then interchange A[i] and A[k]
end for

Array implementation of selection sort:

The method for array implementation of selection sort is as follows:


int i,j,min,temp;

for(i = 0;i < size-1;i++)


{
min = i;
for(j = i+1;j < size;j++)
{
if(array[min]>array[j])
{ min = j;}

53
}
if (min != i)
{
temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}

BUBBLE SORT:

Bubble sort is a simple in-place sorting algorithm. It works by repeatedly stepping through the
list to be sorted, comparing each pair of adjacent items and swapping them if they are in the
wrong order. The pass through the list is repeated until no swaps are needed, which indicates
that the list is sorted.

Algorithm:

The algorithm for bubble sort is as follows:


Input: An array A[1..n] of n elements.
Output: A[1..n] sorted in ascending order.

for i  0 to n - 1
for j  0 to n - 1
if A[j] < A[j+1] then swap
end for
end for

Array implementation of bubble sort:

The method for array implementation of bubble sort is as follows:


int j, i, temp;

for(i = 0; i < size – 1; i++)


{
for(j = 0; j < size – 1; j++)
{
if(array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}

54
BINARY SEARCH

A binary search is a divide and conquer search algorithm. The major requirement for using
binary search is that the array or the list on which it is applied should be sorted first. Binary
search is therefore best for searching in a sorted collection of data. For example: Searching for
a word in a sorted collection of words as in a dictionary, searching for a telephone number from
a telephone directory which is a sorted list of everyone’s phone numbers, etc.

Algorithm:

The algorithm for binary sort is as follows:


Input: An array A[1..n] of n elements, element x to be searched
Output: element found or not

i = 0 (left end point of the array)


j = size – 1(right end point of the array)
while i< j
begin
mid = (i + j) / 2
if am = x then element found
if x > am then i = m + 1
else j = m
end
end while

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Task To Be Performed

1. Use the selection sort algorithm to sort an array of 10 integers.

2. Use the bubble sort algorithm to sort an array of 10 integers.

3. You can reduce the number of comparisons (number of iterations in the inner loop) in
the bubble sort algorithm mentioned above. Use that algorithm to sort an array of 10
integers.

4. Implement binary search in arrays. Use this binary search function to search a sorted
array of 10 integers for any user-defined integer.

55
Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

56
Lab 9: Implementation of Strings

Objectives
1. Student should be able to work with string arrays.
2. Student should know how to handle different pre-defined string function.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
A string is a series of characters treated as a single unit. A string may include letters, digits,
special characters such as +, -, *, / and $. A string in C++ is an array of characters. In this lab,
the concept of strings is explained. Some functions from string library will also be discussed.
An array of characters can be declared, initialized and displayed in following different ways:
// prog1.cpp

#include <iostream.h>
void main()
{
char s[] = {‘w’, ’o’, ’r’, ’l’, ’d’}; // displays garbage value because
cout<<s<<endl; // string is not terminated with ‘\0’

char s1[6] = {‘w’, ’o’, ’r’, ’l’, ’d’};


cout<<s1<<endl;

char s2[] = {‘w’, ’o’, ’r’, ’l’, ’d’,'\0'};


cout<<s2<<endl;

inti = 0;
// character wise display
while(s2[i]!='\0')
{
cout<<s2[i];
i++;
}
cout<<endl;

char s3[] = “save the world”;


cout<<s3<<endl;
}

Execute the above program and observe the output. ‘\0’ is called the null character. In string
s, the null character is not placed in the end so garbage value is displayed. In s1, array size is
one greater than the number of letters in the array which accommodates the null character and
so garbage value is not displayed in the output of s1. In s2, the null character is separately
placed at the end of the character array. While printing the character array, the null character is
57
not printed. In s3, the C++ compiler places the null character itself in the end of the string.
Considering the null character, the length of the string is always the actual length of string plus
one. For example, the string s1 has 5 alphabets and 1 null character. Now consider the following
program:
// prog2.cpp

#include <iostream.h>
void main()
{
char s[15];
cin>>s;
cout<<s<<endl;
}
In the above program, if “save the world” is taken as input from the user then only the first word i.e. “save” will
be printed on the output screen. This is because there is a space between the words. The compiler considers the
space as a null character and terminates the sentence. To solve this issue, the function gets() is used. The
function gets() is from the standard library file stdio.h. Consider the following code segment:

// prog3.cpp

#include <iostream.h>
#include <stdio.h>

void main()
{
chars[15];
gets(s);
puts(s);
cout<<s;
}

Now if the sentence “save the world” is entered from the keyboard, the whole sentence is saved
in string s and is printed on the output screen as a result of cout<<s. Similarly, the function
puts() displays the string ‘s’ followed by a new line character. The function puts() is from
the standard library file stdio.h. The output of puts() and cout is the same here.

STRING LIBRARY FUNCTIONS


The string handling library <string.h> provides useful functions for manipulating string
data like copying and concatenating strings, comparing strings, searching strings for characters
and other strings, tokenizing strings and determining the length of strings. Some of the
functions of string handling library that are normally used are summarized below. Every
function below appends a null character to its result.

Function prototype Function description

strcpy(s1,s2); copies string s2 into s1. s1 is returned.

strcat(s1,s2); appends string s2 to s1. The first character of s2 overwrites the


terminating null
character of s1. s1 is returned.
58
strcmp(s1,s2); string compare function compares lengths of the strings s1 and s2. The
function returns 0 if the s1 and s2 are equal in length, -1 if s1 is less than
s2 and 1 if s1 greater than s2.

strlen(s); returns length of string s. The number of characters preceding the


terminating nullcharacter is returned.

strchr(s,c); locates the first occurrence of character c in string s. (string searching)

Consider the following program to understand the usage of the function strcpy(s1,s2).

// prog4.cpp
#include <iostream.h>
#include<string.h>
void main()
{
char s[] = "save the world";
char s1[15];
strcpy(s1,s);
cout<<"string s1 is: "<<s1<<endl;
cout<<"string s is: "<<s<<endl;
}

The string ‘s’ is copied into the character array ‘s1’. Change the order of parameters passed to
the function and observe the output.The following program explains the use of the function
strcat(s1,s2).

// prog5.cpp
#include <iostream.h>

void main()
{
char s[] = "world";
char s1[] = "save the ";
cout<<strcat(s1,s)<<endl;
}

This function can also be applied on user defined strings as in the following code segment:
// prog6.cpp
#include <iostream.h>
#include <stdio.h>
#include <string.h>

void main()
{ char s[20];
char s1[10];
gets(s);
gets(s1);
59
cout<<”concatenating s and s1: ”strcat(s,s1)<<endl;
}

Prog8.cppexplains the use of the function strcmp(s1,s2).

// prog8.cpp
#include <iostream.h>
#include <stdio.h>
#include <string.h>

void main()
{
char s[10];
char s1[10];
int answer;

gets(s);
gets(s1);

answer = strcmp(s,s1);

if(answer == 0)
{
cout<<”both strings are same."<<endl;
}

else if(answer > 0)


{
cout<<”string s alphabetically greater than s1.”<<endl;
}
else
{
cout<<”string s alphabetically smaller than s1.”<<endl;
}
}

The function strcmp() returns zero when both strings are same. The function returns 1 if the
first string is alphabetically/lexicographically greater in rank than the second string, for
example “world” is lexicographically greater than “home”. Consider the following program to
understand the use of the function strlen(s).

// prog9.cpp
#include <iostream.h>
#include <stdio.h>
#include <string.h>

void main()
{
char s[20];
gets(s);
cout<<”length of string s is ”<<strlen(s)<<endl;
}

The function will display the number of characters present in the string ‘s’. The characters will
include spaces as well.Prog10.cppexplains the working of the function strchr(s,c).

60
// prog10.cpp
#include <iostream.h>
#include <stdio.h>
#include <string.h>

void main()
{
char s[20];
char c;
gets(s);
cout<<”enter character to search in string s: ”;
cin>>c;
if(strchr(s,c) != '\0')
{
cout<<”character ‘”<<c<<”’ was found in string \””<<s<<”\””<<endl;
cout<<”remainder of the string beginning with character ‘”<<c;
cout<<”is \”<<strchr(s,c)<<”\””<<endl;
}
else
{
cout<<”character ‘”<<c<<”’ was not found in string \””<<s<<”\””<<endl;
}
}

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Task To Be Performed

1. Implement a program that can displays the date in the format: May 28, 2013
the name of the month is taken as a string, and the day and year as integers from the
user.

2. Write a program to calculate the length of a string. In this program, counts the number
of characters in the string ‘s’ and display the count.
Note: Don’t use Strlen ( s ) to calculate number of characters.

3. Implement a program in which you will reverses the string ‘s’ entered by the user. You
can use the strlen() function to determine the length of the string and then run the
loop for that length of string and display the string character in reverse order.
4. A palindrome is a string which it read same backwards as forwards. This program uses
the above code to reverse the string ‘s’ and then compares the original string and
reversed string to check if they are same. Display an appropriate message if the string
‘s’ is a palindrome.

61
5. The registration number of a student of engineering department looks like
LF12BSEE0011 or L1F12BSME0100. Implement a program which takes a registration
number and separates Session, department and roll no. from user. The program should
store these fields in separate strings and display them. Also display the three fields
separately.

6. Declare and initialize an array of strings that has the names of 5 courses that a student
has registered for a specific semester. Implement a Program to replace any course in
that list with another user-defined course.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

62
Lab 10: Implementation of Pointers

Objectives
1. Student should be able to understand the reference and dereference operators.
2. Student should be able to work with pointers and arrays.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
Pointers are variables whose values are memory addresses. Normally, a variable directly
contains a value. A pointer contains the address of a variable that contains a specific value. In
this sense, variable name directly references a value, and a pointer indirectly references a value.
Referencing a value through a pointer is called indirection. Pointers like variables should be
defined before they can be used. For example, the definition

int *p, q;

defines a pointer ‘p’ of type ‘int’ and is read as “pointer p points to int”. Also, the variable
‘q’ is defined to be an ‘int’, not a pointer to an ‘int’. The symbol * indicates that it is a
pointer and not a variable.
q q

5 p 5

q directly references a variable p indirectly references a variable

whose value is 5 whose value is 5

POINTER OPERATORS

The & operator returns the address of its operand. For example, assuming the definitions:

int y = 5;
int *yptr;

the statement:

yptr = &y;

63
assigns the address of the variable ‘y’ to pointer variable ‘yptr’. Variable ‘yptr’ is then said
to point to ‘y’. The schematic representation of memory after the above statement will be:
y
yptr 5

Graphical representation of a pointer pointing to an integer variable in memory

The * operator is commonly referred to as the indirection or dereferencing operator. Consider


that if the integer variable ‘y’ is stored in memory at location 6000, the variable ‘yptr’ is
stored at location 5000. The operand of the address operator must be a variable; the address
operator cannot be applied to constants or to expressions. Consider the following diagram:
yptr
5000 6000

y
6000 5

Representation of ‘y’ and ‘yptr’ in memory

USE OF POINTERS

Pointers are defined like variables in the start of the program. Same as variables, pointers also
have data types which define the type of value whose address the pointer points to. Consider
the following program.
// prog1.cpp
#include <iostream.h>
void main()
{
int a;
int *aPtr;

a = 7;
aPtr = &a;

cout<<"address of a is:" <<&a<<endl;


cout<<"value of aPtr is: "<<aPtr<< endl;

cout<<"value of a is:"<<a<<endl;
cout<<"value of aPtr is:"<<*aPtr<<endl;

cout<<"value of *&aPtr is:"<<*&aPtr<<endl;


cout<<"value of &*aPtr is:"<<&*aPtr<< endl;
}

In the above program, ‘a’ is a variable of integer type and ‘aPtr’ is a pointer that points to an
integer type variable. Here, this pointer is pointing to ‘a’ i.e. the pointer ‘aPtr’ stores the
address of the variable ‘a’. The first two printing statements will print the address of the
memory location where variable ‘a’ is stored.
64
The third and fourth statement displays the value stored in the variable ‘a’. *aPtr displays
the value of the variable whose address is stored in aPtr. Whereas, &aPtr will display the
address of the variable to which it points.
The fifth and sixth statement displays the same thing. The * and & operators complement each
other i.e. they cancel each other’s effect when written together therefore *&aPtr and
&*aPtr displays the address stored in the pointer aPtr.

INCREMENTING AND DECREMENTING WITH POINTER

A pointer pointing to a variable can also be incremented or decremented. Consider the


following code to observe what will happen if a pointer is incremented or decremented:
// prog2.cpp
#include<iostream.h>
void main()
{
int *xptr, x;
x = 100;
xptr = &x;

cout<<"printing xptr: "<<xptr<<endl<<endl;

(*xptr)++;
cout<<"printing p after *xptr++ : "<<xptr<<endl<<endl;
cout<<"printing x after *xptr++ : "<<x<<endl<<endl;

(*xptr)--;
cout<<"printing p after *xptr-- : "<<xptr<<endl<<endl;
cout<<"printing x after *xptr-- : "<<x<<endl<<endl;
}

The first, second and fourth printing statement displays the address of variable ‘x’ stored in
pointer ‘xptr’. Remember that executing (*xptr)++ or (*xptr)-- increments or decrements
the value of variable ‘x’ to which ‘xptr’ points. This is because the increment or decrement is
in *xptr and not xptr. The statements:

x = 100;
xptr = &x;
or
xptr = &x;
*xptr = 100;

Have the same effect. In the first case, the pointer ‘xptr’ points to the variable ‘x’ which stores
the value 100. In the second case, the pointer ‘xptr’ points to an uninitialized variable ‘x’. the
value of ‘x’ is indirectly assigned using the pointer ‘xptr’.

USING POINTERS WITH ARRAYS


Pointers can be used to do any operation involving array subscripting. Assume that integer
array b[5] and integer pointer bptr have been defined. The pointer bptr can be set to point
the array b[5]by the following statement:
bptr = b;
65
this statement is equivalent to taking the address of the first element of the array as follows:
bptr = &b[0];
array element b[3] can alternatively be referenced with the pointer expression:
*(bptr + 3);
The 3 in the above statement indicates the element at b[3] of the array b. The element 3
indicates the number of locations offset from the location number 0. This notation is referred
to pointer/offset notation. Now consider the following expression:
*bptr + 3;
In this case, this expression will add 3 to the value of *bptr i.e. 3 is would be added to b[0]
assuming bptr points to the beginning of the array. Just as the array element can be referenced
with a pointer expression, the address
&b[3]
can be written with the pointer expression
bptr + 3
the array itself can be treated as a pointer and used in pointer arithmetic. For example, the
expression
*(b + 3)
also refers to the array element b[3]. Pointers can be subscripted exactly as arrays can. For
example, if bptr has the value b, the expression
bptr[1]
refers to the array element b[1]. This is referred to as pointer/subscript notation. Now the
following program will illustrate the use of pointers to traverse the elements of an array.

// prog4.cpp
#include<iostream.h>
void main()
{
int a[] = {1, 2, 3, 4, 5};
int *aPtr = a;
int i;
cout<<endl<<endl;
cout<<"printing array using array subscript notation:"<<endl;
for(i = 0; i <5; i++)
{
cout<<"a["<<i<<"] : "<<a[i]<<endl;
}
cout<<endl<<endl;
cout<<"printing array using array name and pointer notation:"<<endl;
for(i = 0; i <5; i++)
{
cout<<"*(a + "<<i<< "): " <<*(a + i)<<endl;
}
cout<<endl<<endl;
cout<<"printing array using bptr and array subscript notation:"<<endl;
for(i = 0; i <5; i++)
{
cout<<"aPtr["<<i<<"] : "<<aPtr[i]<<endl;
66
}
cout<<endl<<endl;
cout<<"printing array using pointer and pointer notation:"<<endl;
for(i = 0; i <5; i++)
{
cout<<"*(aPtr + "<<i<< "): " <<*(aPtr + i)<<endl;
}
}

The above program gives the same output for both loops. The repetition is just to clarify the
usage of pointers and their effect on the predefined variables and arrays. The following program
saves the addresses of consecutive memory locations of an integer array in another array of
pointers:

// prog5.cpp
#include<iostream.h>
void main()
{
int *p[10],y;
int i[10] = {2, 5, 7, 8, 9, 0, 1, 2, 4, 5};
for(y = 0 ; y < 10 ; y++)

{
p[y]=&i[y];
}
for( y = 0 ; y < 10 ; y++)
{
cout<<*p[y]<<" "<<p[y]<<endl;
}
}

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Task To be Performed


1. Introduce integer variables x and int* pointer variables xptr. Set x to 10 and
xptr to the address of x. Then display the following information in the main
method:
a. The address of x and the value of x.
b. The value of xptr and the value of *xptr.
c. Increment x by 1 and display the address and value of x. Also display *xptr.
d. Increment *xptr by 1 and display the address and value of x. Also display *xptr.
e. Increment xptr by 1 and display the value of x and xptr.

2. Introduce a character variable ch. Initialize the character variable with ‘h’. then
display the following information:

67
a. Initialize an integer pointer ptr and point it to the character variable ch. Display
ptr. What is the error and why?
b. Now initialize a character pointer chptr and point it to the character variable
ch. Display chptr, *chptr, ch and &ch.
c. Increment ch by 1 and display the address and value of ch. Also display *chptr.
d. Increment *chptr by 1 and display the address and value of ch. Also display
*chptr.

3. Take two integer variables as input from the user and swap the content of the variable
through pointer only. Display the value of the variables before and after swapping.

4. Write a program, which will take ten values from the user. In addition, the program
should display the average of those ten values. Array input and sum operation
should be done using pointer only.

5. Input and Display the 3 x 3 matrix through 2D pointer. Find out the maximum and
minimum values in matrix.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

68
Lab 11: Implementation of 2-D Strings and Pointers

Objectives
1. Student should be able to understand the reference and dereference operators.
2. Student should be able to work with pointers and strings.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
2D ARRAY OF STRINGS

A 2-dimensional array of strings can be implemented by placing separate strings in the rows of
a 2D character array. An example program is given below:
#include <iostream.h>
#include <string.h>
#include <stdio.h>

void main()
{
char country[5][9] = {"Pakistan", "China", "Iran", "India", "Thailand"};
char code[5][4] = {"092", "086", "098", "091", "066"};
char s1[10];

cout<<"enter country name: ";


cin>>s1;
int i = 0;
while(i<5)
{
if(!strcmp(s1,country[i]))
{
cout<<"country code is "<<code[i]<<endl;
goto l1;
}
i++;
}
cout<<"country not found"<<endl;
l1:;
}

In the array ‘country’ there are 5 countries which are placed in 5 rows. The countries can have
a maximum of 8 letters, so extra space is reserved for the null character for each country name.
The ‘if’ condition in the function above will become true (or 1) when the two strings i.e. s1 and

69
country[i] matches exactly. In that case the function strcmp() returns 0 and is converted to
1 because of the not symbol(!). When the ‘if’ condition becomes true, the country code at the
same location in another array is displayed and the function ends.

Strings as pointers
Another way of accessing a contiguous chunk of memory, instead of with an array, is with
a pointer. Since we are talking about strings, which are made up of characters, we'll be
using pointers to characters, or rather, char *'s. However, pointers only hold an address, they
cannot hold all the characters in a character array. This means that when we use a char * to
keep track of a string, the character array containing the string must already exist (having
been either statically- or dynamically-allocated).
Below is how you might use a character pointer to keep track of a string.

char label[] = "Single";


char label2[10] = "Married";
char *labelPtr;
labelPtr = label;
We would have something like the following in memory (e.g., supposing that the
array label started at memory address 2000, etc.):
label @2000
------------------------------
| S | i | n | g | l | e | \0 |
------------------------------

label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------

labelPtr @4000
--------
| 2000 |
--------
It's important to remember that the only reason the pointer labelPtr allows us to access
the label array is because we made labelPtr point to it. Suppose, we do the following:

labelPtr = label2;

Now, no longer does the pointer labelPtr refer to label, but now to label2 as follows:
label2 @3000
------------------------------------------
| M | a | r | r | i | e | d | \0 | | |
------------------------------------------
70
labelPtr @4000
--------
| 3000 |
--------

So, now when we subscript using labelPtr, we are referring to characters in label2

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Task To be Performed


1. Declare and initialize an array of strings that has the names of 5 courses that a
student has registered for a specific semester. Implement a program to replace any
course in that list with another user-defined course:
The program should search the first string in the strings. Once that string is found,
replace it with the second string ‘course2’. If the course name that is being searched
is not found, display an appropriate message.
In the main method, initialize the names of two courses from the user. First name
should be the course to be replaced and the second name should be the course that
is to be added in the list. Display the list of courses after replacing the course.

2. Write a program that allows the user to enter the last names of five candidates in a
local election and the number of votes received by each candidate. The program
should then output each candidate’s name, the number of votes received, and the
percentage of the total votes received by the candidate. Your program should also
output the winner of the election. A sample output is:

Candidate Votes Received % of Total Votes

Johnson 5000 25.91


Miller 4000 20.73
Duffy 6000 31.09
Robinson 2500 12.95
Ashtony 1800 9.33
Total 19300 _

The Winner of the Election is Duffy.

71
3. A palindrome is a string which it read same backwards as forwards. This program
should be written using pointer to reverse the string ‘s’ and then compares the
original string and reversed string to check if they are same. Display an appropriate
message if the string ‘s’ is a palindrome.
Note: Use only pointer to input and output the string. The string should be store in
reverse order with the help of pointer only.

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

72
Lab 12: Implementation of Functions

Objectives
1. Student should be able to understand the local and global variable declarations.
2. Student should be able to make functions.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
Functions helps in making a programming code more organized and reduces the number of instructions. Use of
functions is associated with reusability since the instructions enclosed by the function body can be reused just by
calling the function wherever required instead of writing that set of instructions several times.

FUNCTIONS

The most commonly used function/method is void main(). This function is a necessary part of every program.
There are several other function with which you are familiar like sqrt(), exp(), abs(), etc. These
functions come from the header file math.h. The details of these functions have been implemented by the C++
developers. In this lab session, students will learn to implement their own functions and make function calls.
Consider the main function:

void main() // function header


{

// function body

The function header is made up of the following parts:

Return type: In the above function, the return type is void. A function with void return type does not return
any value to the place where the function is called. A function may have any other return type depending on the
type of variable returned from the function.

Name of the function: Every function does have a name. The name of the function defined above is main. The
names of functions should be descriptive about the purpose for which the function is implemented. For example,
the function sqrt() indicates that it takes the square root of the variable placed between the round brackets.

Parameter list: Any variable written between the round brackets in the function header makes up the parameter
list. The parameter list may have one or more variables. For example, the function sqrt() takes only one
parameter. The function pow( , ) takes two parameters.

prog1.cpp implements a function square()with no return type and no parameter list. The function square()is
called in main method.
73
// prog1.cpp
#include <iostream.h>

// the function implementation


void square() // function header
{
int s, num; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
s = num * num; // calculating square
cout<<”square of ”<<num<<” = ”<<s<<endl; // printing square
}

void main()
{

cout<<”displaying square of a number:”<<endl;

square(); // function call


}

In the above program, the function square() has return type ‘void’ which means that the function does not return
any value. The number is taken as input from the user inside the function and the square of that number is also
printed inside the function.

Since the function computes the square of a number, the function can have the return type ‘int’. In that case, the
function will return an integer value (square of the number) where the function call is initially made. Consider the
following program which is another version of the program in prog1.cpp. prog2.cpp implements a
function square()with return type ‘int’ and no parameter list. The function square ()is called in main method.

// prog2.cpp
#include <iostream.h>

// the function implementation


int square() // function header
{
int s, num; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
s = num*num; // calculating square
return s; // returning value
}

void main()
{

int s; // local variable

cout<<”displaying square of a number:”<<endl;


s = square(); // function call
cout<<”square of the number is: ”<<s<<endl;
}

In the above program, the input from the user is taken inside the function, the square of that number is calculated
and the answer is returned to the main method. Always make sure that the value returned from the function is
consistent with the return type of the function specified in the header. Also the value returned from the function

74
is stored in a variable with appropriate data type. As in the above program, the function returns an ‘int’ value and
the value is stored in an ‘int’ type variable in the main method. The above function can also be written as below
without using another variable ‘s’:

int square() // function header


{
int num; // local variables
cout<<”enter the number to take square:”<<endl;
cin>>num; // taking number
return num*num; // returning value
}

In the above implementation, the local variable ‘s’ is not used. This function gives the same result as before.
Consider another implementation of the same function but with a function parameter. Here, the number from the
user is not taken inside the function, but is passed from the main method. The number is taken from the user in
the main method and is passed to the function as a function parameter. The function calculates the square of that
number and returns the value in the main method, from where the function was called.

// prog3.cpp
#include <iostream.h>

// the function implementation


int square(int num) // function header
{
int s; // local variable
s = num*num; //calculating square
return s; // returning value
}

void main()
{

int s, n1; // local variables


cout<<”enter the number to take square:”<<endl;
cin>>n1; // taking number
s = square(n1); // function call
cout<<”square of the ”<<n1<<” is: ”<<s<<endl;
}

In the above implementation, the number taken from the user (in the main method) is in the variable ‘n1’. This
variable is passed to the function square()as a parameter. In the parameter part, the value of ‘n1’ is copied in
the variable ‘num’, which is then passed inside the function square(). Inside the function, the square of that
number is calculated, stored in a local variable ‘s’ and the value in ‘s’ is returned to the main method.
Consider the following program which takes the maximum of three numbers. The three numbers should be passed
to the function from the main method and maximum of these three numbers will be returned back to the main
method.

// prog4.cpp
#include <iostream.h>

// the function implementation


int maximum(int a, int b, int c) // function header
{
int n = a; // local variable

if(n < b)
75
n = b;
if(n < c)
n = c;

return n; // returning value


}

void main()
{
int n1, n2, n3, max;

cout<<”enter the numbers to find maximum:”<<endl;


cin>>n1>>n2>>n3;
max = maximum(n1,n2,n3);
cout<<”maximum of the three numbers is ”<<max<<endl;
}

LOCAL AND GLOBAL VARIABLES

Local variables: The local variables are accessible only within the function. Using or printing these variables
inside main method or outside the function will generate an error. These variables are declared inside the function
and are destroyed when the function ends. Using variables with same name in other functions will not generate
an error. Changing value of local variable will not change the value of that variable in main or in other functions.
The change in value of local variable can be observed only if that local variable is returned from the function.

Global variables: Global variables are declared outside all the functions including main. Global variables are
accessible everywhere in the same C++ file but are not accessible in other C++ files. Global variables cannot be
re- declared in main function or in other functions. Changing the value of a global variable in one function will
change its value everywhere in the same C++ file.
Consider the following programming code to understand the idea of local variables:

// prog5.cpp
#include <iostream.h>

void change(int n1) // function header


{
int s, n; // local variable
s = n1*n1*n1;
n = s;
cout<<"value of local variable is "<<n<<endl;
}

void main()
{
int s, n; // local variables
cout<<"enter the number:"<<endl;
cin>>n; // taking number
change(n); // function call
cout<<"value of variable in main is "<<n<<endl;
}

76
Consider the following programming code to understand the idea of global variables:

// prog6.cpp
#include <iostream.h>

int n; // global variable


void change(int n1) // function header
{
n = n1*n1*n1;
cout<<"value of local variable n is "<<n<<endl;
}

void main()
{
cout<<"enter the number:"<<endl;
cin>>n;
change(n); // function call
cout<<"value of variable in main is "<<n<<endl;
}

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

Lab Task To be Performed


1. Implement the following function:

a. float temp(float t, char ch) – this function takes temperature ‘t’ and unit of
temperature ‘ch’ as parameter. The variable ‘ch’ will be either f or c depending
on whether the temperature in variable ‘t’ is in Fahrenheit or Celsius. The
function returns the converted temperature to the main method.

Call the above function in the main method. Initialize temperature and unit of
temperature from the user and pass them as parameter to the above function. The
converted temperature should be displayed in the main method.

2. Implement the following function:


a. int factorial(int n) - which takes a number as parameter and returns its factorial.
Call the above function in the main method. Initialize an integer variable from the
user in the main method and pass it as parameter to the above function. Display the
factorial in the main method.

77
3. Modify the above program to call the factorial function in the main method 10 times
while passing a user defined integer each time and displaying the corresponding
factorial.

4. Implement the following function:


a. void factors(int n) – displays all factors of the number ‘n’ passed as parameter.

b. void display(int start, int end) – this function takes the start and end of a range
as parameter and calls the above function factors() to display the factors of all
numbers in that range
Call the function display() in the main method. Take the start and end of a range
from the user and pass it to the function to display the factors.

5. Implement the following function:


a. char calculate_grade(int marks) - which returns the letter grade of a student. The
function should take the marks of the student as parameter, decide the grade and
return the grade in the main method.Call the function in the main method.

In the main method, take number of students from the user. Use a loop to take the marks of
each student from the user and pass them as parameter to the function calculate_grade(int
marks).

Conclusion:

Teacher/Supervisor’s signature: _______________________

Date: _______________________

78
Lab 13: Implementation of Functions with Arrays

Objectives
1. Student should be able to understand the local and global variable declarations.
2. Student should be able to make functions.

Equipment
1. PC with Microsoft Visual C++ 2013

Theory
Functions can be used with 1D and 2D arrays. It should be kept in mind that a function cannot
return an array, as a function returns only one value.

FUNCTIONS WITH 1D ARRAYS


In order to initialize or display arrays several for loops are used. This can be done more
efficiently and in less lines of code by implementing separate functions to initialize and display
the arrays. The following program defines 3 functions and then calls them in the main method.

// prog1.cpp
#include <iostream.h>

inti, c[10];

void input(int a[10])


{
for(i = 0; i<10; i++)
{
cin>>a[i];
}
}
void output(int a[10])
{
for(i = 0; i<10; i++)
{
cout<<a[i]<<” ”;
}
}
void sum(int a[10], int b[10])
{
for(i = 0; i<10; i++)
{
c[i] = a[i] + b[i];
}
}
void main()
{
int a[10], b[10];
cout<<”initializing array a:”<<endl;
input(a);
cout<<”initializing array b:”<<endl;
79
input(b);
sum(a, b);
cout<<”displaying sum of two arrays:”<<endl;
output(c);
}

In the above program, the input() function is used to initialize values for the two arrays.
When the arrays are initialized, they are passed to the function sum() which saves the sum of
the two arrays in a global array c. the output() function is called to display the global array
c.
The input() function above can initialize arrays of size 10 only. In order to implement a
general function to initialize an array of any size consider the following program:
// prog2.cpp
#include <iostream.h>

inti;
void input(int a[100], int size)
{
for(i = 0; i<size; i++)
{
cin>>a[i];
}
}

void main()
{
int a[20], b[10];
cout<<”initializing array a:”<<endl;
input(a, 20);
cout<<”initializing array b:”<<endl;
input(b, 10);
}

The above program calls the input() function to initialize 2 arrays of different sizes.

FUNCTIONS WITH 2D ARRAYS

Function can use 2D arrays as parameters or as local arrays. The following program adds two
2x2 matrices and displays the resultant matrix.
// prog3.cpp
#include <iostream.h>

inti, j, c[2][2];
void input(int a[2][2])
{
for(i = 0; i<2; i++)
{
for(j = 0; j<2; j++)
{
cout<<"array ["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
}
80
}
}

void output(int a[2][2])


{
for(i = 0; i<2; i++)
{
for(j = 0; j<2; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}

void sum(int a[2][2], int b[2][2])


{
for(i = 0; i<2; i++)
{
for(j = 0; j<2; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
}
void main()
{
int x[2][2], y[2][2];

cout<<"initializing array 1"<<endl;


input(x);
cout<<"initializing array 2"<<endl;
input(y);
sum(x, y);
cout<<"displaying sum ..."<<endl;
output(c);
}

Implementing programs using functions makes the program more systematic, readable and
efficient. Functions help to implement programs using lesser lines of code. It is a good practice
to implement all functions in a header file and include that header file in the C++ source file.

HEADER FILES
Each standard library has a corresponding header containing the function prototypes for all
the functions in that library and definitions of various data types and constants needed by
those functions.
Some commonly used standard library headers are:

Standard library header Explanation

<iostream.h> contains function prototypes for the standard input/output library


functions, and Information used by them.
<math.h> contains function prototypes for math library functions.
<string.h> contains function prototypes for string processing functions.

81
<time.h> contains function prototypes and types for manipulating the
time and date.
<stdlib.h> contains function prototypes for conversions for numbers to text and
text to numbers, memory allocation, random numbers, and other
utility functions.

A programmer can create custom headers. Programmer-defined header names should also
end in .h. A programmer-defined header can be included by using the #include preprocessor
directive.
// maximum.h
#ifndef max
#define max

int maximum(int a, int b, int c)


{
int n = a;
if(n < b)
n = b;
if(n < c)
n = c;

return n;
}

#endif

// prog4.cpp
#include <iostream.h>
#include "maximum.h"

void main()
{
int n1, n2, n3, max;

cout<<"enter the numbers to find maximum:"<<endl;


cin>>n1>>n2>>n3;
max = maximum(n1,n2,n3);
cout<<"maximum of the three numbers is "<<max<<endl;
}

Functions of one C++ source file cannot be used by the other. It is customary to define the
most commonly used functions in header files and include the header files in whichever C++
source file.

Instructions To Be Followed
a. Student will choose appropriate programming tools by analyzing the problem
statement.
b. Students are requested to prepare the lab report and bring the printouts of the report in
next coming lab so they will be mark accordingly.

82
Lab Task To be Performed

1. Declare two 1D arrays in the main method. Implement the following functions:
a. void input(int a[100], int n)– initializes an array ‘a’ of size ‘n’
passed as parameter.
b. int max(int a[100], int n) – returns maximum value of array a
c. int min(in a[100], int n) – returns minimum value of array a
d. int mean(int a[100], int n) – returns mean value of array a
In the main method, call input() function to initialize arrays. Use functions b, c, d to
return max, min, mean values of the 2 arrays. Use these values to determine which array
has maximum deviation from mean. Display appropriate message.
2. Declare two float type 2×2 arrays ‘a’ and ‘b’ in the main method. Implement the
following functions in a header file. Include the header file in your source file. Pass
the array ‘a’ and ‘b’ as parameter to the functions wherever required:
a. void input(float c[2][2])to initialize all the locations of the array.
b. Void output(float c[2][2])to display the array.
c. void transpose(float c[2][2])to take the transpose of the array and store
it in another array. Display the transpose using the function in part (b).
d. void copy(float a[2][2], float b[2][2]) to copy array a to array b.
Display array b using function in part b.
e. void swap(float a[2][2], float b[2][2]) to swap arrays a and b. Display
array a and b using function in part b.
f. float determinant(float c[2][2])to return the value of determinant of the
array.
g. void adjoint(float c[2][2]) to determine the adjoint of array and save it
in another array. Display the adjoint using function in part (b).
h. void inverse(float c[2][2]) to find the inverse of the array by using the
functions implemented in part (f) and part (g). Store the inverse in another array
and display the inverse using the function in part (b).

Conclusion:

83
Teacher/Supervisor’s signature: _______________________

Date: _______________________

84

You might also like