Computer Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

LABORATORY

MANUAL
EXPERIMENTS IN

COMPUTER PROGRAMMING

FACULTY OF ENGINEERING

UNIVERSITY OF CENTRAL PUNJAB


LIST OF AUTHORS

Sr. # Name Date Modified Contributions


1 Yaqoob Javed /
October 2014 Manual Creation.
Haleema Asif
2 Ali Awais October 2017 Manual Formatting
3 Haleema Asif /
October 2018 Manual formatting
Jawad Khalid
4
5
6
7
8
9
10
LABORATORY MANUAL

EXPERIMENTS IN

COMPUTER PROGRAMMING
Manual Owner: Engr. Haleema Asif
Lab Instructor: Engr. Jawad Khalid
Designation: Lecturer

University of Central Punjab, Lahore


EXPERIMENTS IN

COMPUTER PROGRAMMING
Revised on October, 2018

Copyrights © Reserved with the author

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

Engr. Yaqoob Javaid has done his Doctorate from University of Science and Technology of
China, Hefei, China. He PhD is in Control Theory and Engineering. He is working as an
Assistant Professor. Earlier he completed his bachelors from University of Central Punjab in
2008 and M.Sc in Computer Science from UET Lahore.

Engr. Haleema Asif has completed her Bachelors and Master’s degree from University of
Central Punjab, Lahore. She is currently serving University of Central Punjab as a lecturer.

Engr. Ali Awais currently serving as a Lecturer in University of Central Punjab. He


completed his B.Sc. in Electrical Engineering from University of Central Punjab and MS in
Computer Engineering from University of Engineering & Technology, Lahore.

Engr. Jawad Khalid has done his Masters from University of Central Punjab, Lahore. His M.Sc
is in Control Systems. He is working as Lecturer in UCP since 2012. Earlier he completed his
bachelors from University of Central Punjab in 2008.

Special Thanks to Dr. Ali Faisal for his contribution in this manual work.
INTRODUCTION

Computer Programming manual, presents a series of experiments dealing with all the topics
covered in one semester course in Computer Programming theory.

This manual is specially designed to help the students to understand basic program
development cycle and generate their own logic for the accomplishment of the assigned tasks.
Every lab is provided with the syntax of the statements or commands, which will be used to
make the programs of exercises. In order to facilitate the students some program segments are
also provided explaining the use of commands. For a wide scope of usage of the commands
several examples are also given so that the students can understand how to use the
commands.

This course takes a practical approach to teaching computer programming. Learning a


programming language is similar, in some respects, to learning how to speak a new language.
The best way to learn computer programming is by writing programs. This course will
involve homework assignments and lab tasks, all of which require solving programming
problems on a computer.

Authors
COMPUTER PROGRAMMING

TABLE OF CONTENTS

Sr.
Description Page No.
No.
Familiarizing the students with their work station,; how to open, start, execute
1 and save their files; how to make their folders; do’s and dont’s of the 7
programming lab session; writing their first C++ code
2 Writing programming codes using basic C++ data types, using simple
13
arithmetic and trigonometric operations
3 Understanding and writing programs using control or conditional, if and if-
19
else statements, nested if-else statements
4 Understanding and writing programs using for loop 26
5 Understanding and writing programs using while and do-while loop, nested
30
while loop
6 Understanding and writing programs using nested for loop 36
7 Understanding and writing programs using 1-dimensional arrays 42
8 Understanding and writing programs using 2-dimensional arrays
45
Mid Term Exam
9 Writing programming codes using infinite loop and goto statement 50
10 Understanding case & switch, continue and break 50
11 Writing programming codes using functions, parameter passing and function
54
overloading
12 Understanding and writing programs using1D and 2D arrays with functions
58
and making header files
13 Understanding and writing programs using strings and standard string
75
function using C++ library
14 Understanding and implementing linear and binary search 85
15 Understanding and implementing sorting 90

6
Experiment - 1:
INTRODUCTION AND EXECUTION OF FIRST C++ PROGRAM

PURPOSE:
To Learn:

1. How to operate the computer machine


2. How to make your own folder to keep a record of your lab sessions
3. How do we define the programming language – C++
4. How to open the C++ editor, write, execute and save the C++ code
5. How to Re-open the C++ code and modify it
6. How to execute simple C++ codes

EQUIPMENT:

1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:

Operating the Computer:


Before actually using your computer for writing and executing C++ programming codes, you
should familiarize yourself with your work station. Most likely, you will communicate with
your operating system using mouse, keyboard and monitor screen. Any passwords and user
identification numbers required for getting into the machine will be provided to the students
by the lab instructors. Students are not allowed to fiddle with the system if anything goes
wrong. They should always ask the lab instructors.

Making your own Folder:


You should create your own folder in your computer where you will keep your C++ files.
You should create your folder in the D drive. The folder will be named with your registration
number. Inside this folder, there will be sub folders for each lab session. For example, for lab
session 1, the folder L2F13BSEE00xyz will contain a folder lab 1. C++ files made during one
lab session should be kept in the related folder. Every student should keep his/her C++ files
with himself/herself. For that purpose, you are allowed to bring your flash drives and copy
the files for safe keeping and later use.

7
Introduction to the Programming Language- C++:
The language that the operating system understands is different from any human language or
programming language. That is called “machine language”. Writing programming codes to
communicate with the machine using machine language is a tedious task and it requires a
large number of programming instructions. Over the years, programmers have developed
several high-level programming languages that are closely related to human languages. Writing
programs in high-level languages like C, C++, JAVA, FORTRAN, BASIC, PASCAL,
etc is simpler and easier. These high-level codes are translated to low level machine
language by the system itself. The system then processes, debugs and executes the
programming code displaying the output in human readable form.
This course is focused on the C++ programming language. C++ was developed upon the
existing C programming language with added object-oriented support while still retaining
compatibility with the C language. Therefore C++ is object-oriented programming language.
Every programming language follows a certain set of rules and instruction set. This is called
the “language syntax”. C++ has its own syntax which will become clear with the course of
time.

Writing, Executing and Saving a C++ Code:


Every student should be familiar with typing, execution and saving of a C++ code. The
software which the student will be using for developing C++ code is Microsoft Visual C++
version 6.0. This software has been installed on each operating system. Basic sequence of steps
for each C++ file is:

Visual C++ Editor:


Open Visual C++. Create a new project with the Win 32 application (select this one). Enter a
project name, say test1. Set the location of you project to D:\L2F13BSEE00xyz\lab 1. This is
the destination folder that you created in the D drive. Now create a new file, C++ source file
(select this one). Enter a file name, say file1. This creates the C++ file in which you will have
to enter your C++ code. Observe that this file will have the extension of .cpp, for example
file1.cpp.
Visual C++ Compiler:
The computer cannot execute a program in its source form. It must be translated into machine’s
low level language first. This translation process is performed by machine’s translator
(or compiler). In the software that you are using, C++ files are compiled by hitting the compile
button in the top pane. Your lab instructor will demonstrate file compilation and execution.
Most C++ compilers pin point the exact line in which the error has occurred and also display a
short error message. In that case, locate the error indicated by the line number in the compiler
output window. Often very small error may spawn several misleading messages pointing to
false errors.
Don’t forget to save your C++ source code file after every 5 minutes. This practice is
encouraged to avoid losing any useful lines of code in case of sudden power failure or abnormal
software behavior.

8
Reopening the C++ Code:
Most often you will have to go back to your saved files for the purpose of modification, etc.
You can open the saved C++ files directly from the software. You can also do so by clicking
on the saved file with extension of .cpp in your related folder. Sometimes there can be several
softwares supporting the C++ text file in your system. In that case, you will have to select the
Visual C++ editor for opening the file.

Indentation:
As in the above statement, every line of code should terminate in a semi colon; otherwise, the
compiler generates a syntax error. Although not mandatory, it is customary to place each
statement on a separate line and to use indentation to help the reader identify related portions
of the program. Similarly, the opening and closing parenthesis should be in one column.
Students will be guided about proper indentation and are strictly instructed to make sure that
the C++ code is properly indented.

Any text written the quotation marks is printed as such on the output window. There can be
text displayed on the output screen without quotation marks, for example cout<<5+8<<endl;

PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.

2. Following is a simple C++ code. Type this in the editor window. We will traverse each
line of code one by one to have a better picture.
/* first C++ program */

#include <iostream.h>

void main( )
{
cout<<”hello”<<\n;
}

3. Save the above C++ code in the related folder. After that compile and execute the above
code and see the output. Let us go through what is the meaning of each line of the above
code.

/* first C++ program */

In addition to C++ code instructions, there are instruc tions which are never
translated into machine language, like explanator y r emarks written after // or
between /* … */. These are called comm ents . The compiler does not compile anything
written between /* … */ or after // on the same line. The comments provide user friendly
explanation of the C++ code. The y can also be used to give information about the
creation of a program such as the date created and b y whom. Students are
encouraged to make use of comments to elaborate the code they are executing.

4. #include <iostream.h>

This line of code is a preprocessing directive. These directives cause the source program to
be modified before compiling process begins and are signified by beginning with the # symbol.
Here the preprocessing directive causes a copy of standard header file iostream.h to be inserted
at the beginning of the source code when the compilation occurs. Students will have to include
this header file in almost every C++ code. This header file contains the necessary information
that the C++ compiler will need to create the required link between our C++ code and the system
library, like the prototypes for standard input/output library functions and the information used
by them. The include statement is used to include files in your C++ file. The same syntax as
above is used for every new file included in a C++ code. For example #include <math.h>

For standard library header files, the names of the files are always enclosed in angel brackets
< and >, as above. Besides, non-standard files (such as the one you create yourself) can also
be included in your C++ code. For that the names are enclosed in quotation marks, as in
#include “myfile.h”

5. void main ( )

This statement indicates the declaration of a main method or main function header. This
method/function represents the beginning of the C++ file, even though this declaration may
appear later in the code. Every executable C++ code has a main method. The C++ code
cannot compile or execute without it. The parenthesis { … } that follows after this method
header contains the method body. Anything written within this parenthesis is a part of the
main method. The void in the beginning of the method header indicates that the main method
does not return anything. The purpose of return type will become clear in later lab sessions.

6. cout<<”hello”<<endl;

The cout statement prints hello on the output window. cout statement is used whenever some
text is to be displayed on the output window. Anything written after << is transferred to the
output window. The pre defined object cout and the operator << are from the standard C++
library that you have included in the beginning of your C++ file. The new line character endl
ensures that any print statement after the current cout statement will print the text in the next
line.

7. The output of
cout<<”hello”<<endl;
cout<<”world”<<endl;

will be:

hello
world
8. Students should also observe the output of the above lines of code without writing the
new line character. There is also another special new line character. The statement
cout<<”hello\n”; will also cause the subsequent line of code to be printed on a separate line.

What would cout<<”hello\n”<<endl; print on the output screen?

LAB ASSIGNMENTS:
Display your name, registration number and session on the output screen. Display everything
on new line.
1. Display the addition, subtraction, multiplication and division of two digits on the
screen. Also display the name of respective mathematical operation.

For example, output should look like: addition of 2 and 4 is 6

2. Display the following text on the output screen:

The Hounds of Baskervilles by Sir Arthur Conan Doyle

a. All on one line


b. On two lines
c. On nine lines
d. Inside a rectangle dra wn with asterisks

3. Calculate the following b y writing separate cout statements on separate


lines :

a. (4 + 6) * (8 + 9)
b. 5 * (13 + 89) – (34 - 12)
c. ((34 + 32 + 7) – (23 * 78)) / 5
d. (90 + 56) / 4 + (34 + 91) / 7
e. (12 + 7) / 9 – (45 + 11) / 6
Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.

Teacher / Supervisor’s Signature:


Experiment - 2:
C++ DATA TYPES AND ARITHMETIC OPERATIONS
PURPOSE:
To Learn
1. How to use different C++ data types to implement a C++ code
2. How to implement arithmetic operations
3. How to take input from the user

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:

C++ Data Types:


The most common data types that will be used in C++ programming are: int, double, float, char,
bool, etc. Data types define the nature of a declared variable or a function.

double or float data types are used for variables having decimal values. char data type is used
for declaring character variables (like a, b, c, etc). An important feature of C++ is that character
variables can also be stored in integer data types because both int and char are one- byte long.
We can treat a character as an integer or as a character depending on its use.

Taking Input from the User:


Sometimes, the value of the variable is not pre-assigned. In case, the user wants to change the
value of variables involved every time the program is executed, the values will be taken from
the user through keyboard input. The keyword used for taking input from the user is cin. The
operator that follows after cin is also different.

Declaring Multiple Variables:


Variables of one data type can also be declared on one line. For example, the variables in the
above code can be declared as:
int length, width;

Similarly, variable initialization from the keyboard can be done in one line for all the variables,
as in
cin>>length>>width;

Arithmetic Operations:
Different arithmetic operations can be performed by including certain header file. For this
purpose, you will have to include the C++ header file from C++standard library math.h, the
syntax for this is #include <math.h>.
Comments:
Comments are added in a program to provide information about the program to the general
reader. The comments are not compiled or seen by the compiler. The syntax rules of the
language need not to be followed while writing comments. The comments may be added in
the beginning of a program to describe who made the program and on what date. Comments
may be added after or before lines of code to explain what a particular instruction is doing.
For one line comment the following syntax is followed:

// … (write comments here)


/* … (write comments here) … */

PROCEDURE:
1. After making the project in visual basic 6.0, write the following program in the source
file.
2. Consider the following programming code that demonstrates addition of two integers
a and b:

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

void main( )
{
int a = 2;
int b = 4;

cout<<”a + b =”<<a+b<<endl;
}

3. Implement following programming code that demonstrates the use of data type
“double” where the values are pre assigned to the integers.

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

void main( )
{
double a = 2.4;
double b = 4.2;
cout<<”a + b =”<<a+b<<endl;
}

4. The following programming code demonstrates the use of “char” data type.

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

void main( )
{
char a = ‘a’;

cout<<”English alphabet begins with”<<a<<endl;


}

5. Notice that in prog3.cpp, the character ‘a’ is enclosed in single quotes. If we want to
use character ‘a’ as an integer, consider the following code:

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

void main( )
{
int a = ‘a’;

cout<<”The value of ”<<’a’<< “ is ”<<a<<endl;


}

Explain why this happens? (Recall the ASCII character set)

6. Consider the following program where the user wants to add two integers a and b by
taking the user defined variables, the code will go like:

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

void main ( )
{
int a;
int b;

cin>>a; // notice the operator >> is different from that ofcout


cin>>b;

cout<<”a + b =”<<a+b<<endl;
}

7. Consider finding out the area of a rectangle with user defined lengths:

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

void main()
{
intlength; // variable declaration
int width;

cin>>length; // variable initialization


cin>>width;

cout<<”Area of rectangle is ”<<length*width<<endl;


}

8. The above program can be made easier to understand if it modified as:

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

void main ( )
{
int length;
int width;

cout<<”Enter length of rectangle: ”


cin>>length;

cout<<”Enter width of rectangle: ”


cin>>width;
cout<<”Area of rectangle is ”<< length*width <<endl;
}

9. Consider division of two integers when the result of division is stored in another
variable. Observe the output of the following code:

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

void main( )
{
int a, b, c;
a = 7;
b = 2;
c = 7/2;

cout<<”a/b =”<<c<<endl;
}

The result of the above division is 3.5 but the value stored in c and displayed on the output
screen is 3. This is because the actual answer (3.5) is a decimal point number and cannot be
saved in an integer type variable. For that reason an int type storing variable will only store
the lower value (3 in this case) and will neglect the decimal part. The machine does not round
off to the nearest decimal by itself. To get the actual result, the data type of the variables should
be changed to float or double.

10. Consider the following code for calculating absolute, square root, exponential and power of
different variables.

// prog9.cpp
#include <iostream.h>
#include <math.h>
void main ( )
{
cout<<”Square root of 5 is ”<<sqrt(5) <<endl;
cout<<”Absolute value of -5 is ”<< abs(-5) <<endl;
cout<<”Exponential of 5 (e^5)is”<<exp(5) <<endl;
cout<<”5 raised to the power 2(5^2) is ”<<pow(5,2) <<endl;
}

11. Open the header file math.h. Check different mathematical operations declared in this
file. Implement them in your C++ code and show the results.
LAB ASSIGNMENTS:
Take two integers from the user and implement addition, subtraction, multiplication and
division.
1. Take two lengths in decimal point from the user and find the area of a triangle.
2. Determine the diameter, circumference and area of a circle. Take the radius (as a
float value) of the circle from the user.
3. Determine the value of y = a3+ b3+ c3+ 3abc (a + b + c). Take variables a, b and c
from the user. Display the value of the variable y.
4. Implement a code to convert x kg into y pounds. Implement a general equation
that takes the variable x in kg from the user, convert it into pounds and save in
another variable y. (1 kg = 2.204 pounds)
5. Implement a code to calculate the roots of quadratic equation. Take the values of
the variables a, b, c from the user for solving the quadratic equation.
6. Initialize a decimal point number from the user. Separate the number before and
after decimal. Display the number before and after separately on the output screen.
For example: if the number from the user is 45.67, you should display as:
Number before decimal: 45
Number after decimal: 0.67

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.

Teacher / Supervisor’s Signature:


Experiment - 3:

CONTROL AND CONDITIONAL STATEMENTS: IF, IF-ELSE AND


NESTED IF-ELSE

PURPOSE:
To Learn:
1. How to use the control and conditional statements like if, if-else and nested if-else
2. How to execute conditions

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:

IF Statement:
The most common conditional statement is an IF statement. The IF statement allows a
program to make a decision based on the truth or falsity of a statement of fact called the
condition. If the condition is met, (i.e. if the condition is true) the statement in the body of the
IF condition is executed. If the condition is not true, the statement in the body is not executed.

IF-ELSE Statement:

The if-else selection statement allows the programmer to specify that different actions are to
be performed if the condition is true than when the condition is false.

There can be multiple else if statements depending on the number of conditions suggested in
the problem statement. There can be only one else statement in one if-else if-else block. You
will be using multiple else if statements in lab assignments 4 and 6 at the end of this manual.

Nested IF-ELSE:

Nested if-else refers to implementing an if-else block within another if or else block.
PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.

2. Consider the following code segment that checks if a is greater than b, when both a
and b are entered by the user.

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

void main( )
{
int a, b;

cout<<”enter a: ”<<endl;
cin>>a;
cout<<”enter b: ”<<endl;
cin>>b;

if(a > b)
{
cout<<”a is greater than b”<<endl;
}
}

3. Characters can also be used in if-else statements. Consider the following code:

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

void main ( )
{
char ch;
cout<<”enter a character: ”<<endl;
cin>>ch;

if(ch == ‘a’)
{
cout<<”this is the letter a”<<endl;}}}

4. To decide which integer entered by the user is greater, an if-else statement will decide
as follows:

// prog3.cpp
#include <iostream.h>
void main()
{
int a, b;
cout<<”enter a: ”<<endl;
cin>>a;
cout<<”enter b: ”<<endl;
cin>>b;
if(a > b)
{
cout<<”a is greater than b”<<endl;
}
else
{
cout<<”a is not greater than b”<<endl;
}
}

5. In the above code, the IF statement is executed only if a greater than b. Cases in
which a is less than b or equal to b, the program execution will not go in to the if
block; only else block will be executed. To incorporate other conditions in the above
code consider the following:

// prog4.cpp
#include <iostream.h>
void main()
{
int a, b;
cout<<”enter a: ”<<endl;
cin>>a;
cout<<”enter b: ”<<endl;
cin>>b;
if(a > b)
{
cout<<”a is greater than b”<<endl;
}
else if(a < b)
{
cout<<”a is less than b”<<endl;
}
else
{
cout<<”a and b are equal”<<endl;
}
}
6. Consider the following code using nested if-else which decides if one number is equal
to or not equal to the other number, if the two numbers are not equal it also decides
which one of them is greater and which one is smaller:

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

void main( )
{
int a, b;
cout<<”enter a: ”<<endl;
cin>>a;
cout<<”enter b: ”<<endl;
cin>>b;
if(a == b)
{
cout<<”a and b are equal”<<endl;
}
else
{
cout<<”a and b are not equal”<<endl;
if(a > b)
{
cout<<”a is greater than b”<<endl;
}
else
{
cout<<”a is less than b”<<endl;
}
}
}

In the above programming code, there is an if-else block inside the else block. Remember
that there can be several different ways to design one particular programming problem. The
above program can have another implementation yielding the same results.
LAB ASSIGNMENTS:
Implement a program which decides if a number entered from user is even or odd. Display
the number and also display if the number is even or odd.
1. Implement a program which decides if a number entered by the user is divisible
by 7 or not. Display the result accordingly.

2. Implement a program which determines the roots of a quadratic equation. The


program also determines if the roots of the equation are real or imaginary. Display
the roots if they are real. Print a message on the output screen about the nature of
the roots (real or imaginary).

3. Consider the following age groups:


Infant – age <= 3 years
Child – 3 years < age <= 12 years
Teenager – 12 years < age <= 19 years
Young – 19 years < age <= 30 years
Mid age – 30 years < age <= 50 years
Old – 50 years < age

Implement a code which takes the age of a person and decides which age group does
the person falls in. Display the age and age group to which the person belongs.

4. A palindrome is a string of characters that reads the same forward as backwards.


For example, 15251, 37173, etc are palindromes. Implement a program which
takes a five digit number as input from the user and decides whether it is a
palindrome or not (Hint: use / and % operators to separate the digits of a number)

5. A character is entered from the keyboard. Determine if the character entered is a


capital letter, small letter, number or a special character. The ASCII character set
is summarized as follows:

Capital letters: A to Z – 65 to 90
Small letters: a to z – 97 to 122
Numbers: 0 to 9 – 48 to 57
Special characters (like @, &, *, ”, etc) : 0 to 47, 58 to 64, 91 to 96, 123 to 127

6. Initialize a 2D integer matrix of size 2x2 with user defined values. Calculate the
determinant of the matrix and display it on the output screen. Also determine if
the matrix is singular or not.

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.

Teacher / Supervisor’s Signature:


Experiment - 4:
FOR LOOP
PURPOSE:
To Learn:
1. How to use repetition loops like for loop.
2. How to execute conditions.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:
The for repetition statement handles all the details of counter-controlled repetition. The for loop
consists of three parts, initialization, condition and update. The syntax of a general for loop is
as follows:

for(initialization; condition; update)


{
statement(s);
}
In the above loop, the initialization part is omitted. Other parts of the for loop can be omitted
as well, but omitting the condition part results in an infinite loop.

PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.
2. Consider a simple for loop which prints the loop updated value of a variable 10 times.
// prog1.cpp
#include <iostream.h>

void main()
{
for (int i = 0; i< 10; i++)
{
cout<<”the value of i is”<<i<<endl;
}
}

3. There can be variations in the above for loop. For example, the variable can be
initialized outside the for loop as in the following:
// prog2.cpp
#include <iostream.h>
void main()
{
int i = 0;
for(; i< 10; i++)
{
cout<<”the value of i is”<<i<<endl;
}
}

4. Implement a for loop with the condition part omitted and check the output. Similarly
if the control variables are not initialized or are not updated, the program does execute
without error but shows no output. Observe the output of a for loop without
initializing variables and updating the variables.
5. The increment or decrement in the update part can be several steps as well. For
example:

for(int i = 0; i <= 20; i += 2) // this varies the control variable from 0 to 20 in steps of 2.

for(int i = 99; i >= 0; i -= 11) // this varies the control variable from 99 to 0 in steps of 11.

Use the above for loops and observe what values for the control variable “i” are printed on
the output screen.
6. Other operators like multiplication (*), division (/) and remainder (%) can also be
used in the update part. The code below uses multiplication in the update part.
Observe how many times the loop executes and what values of “i” are printed on the
output screen.
// prog3.cpp
#include <iostream.h>

void main()
{
for(int i = 1; i < 10; i *= 2)
{
cout<<”the value of i is”<<i<<endl;
}
}

What will happen if the initial value of i is made 0?

7. Consider the following for loop which prints the running sum of numbers up to a
certain value (entered by the user).
// prog4.cpp
#include <iostream.h>

void main ( )
{
int limit;
int sum = 0;
cin>>limit; // enter limit from user

for(int i = 0; i <= limit; i++)


{
sum =sum+i;
}

cout<<”sum of numbers from 0 to ”<<limit<<” is:”<<sum<<endl;


}

Can you modify the above program to calculate the sum of even numbers between 0 and 50?

8. Remember that you can always use other conditional statements like if-else, etc with
the for loop. Consider a program that will print a number only if it is even.
// prog5.cpp
#include <iostream.h>

void main()
{
int limit;
cin>>limit; // enter limit from user

cout<<”Print even numbers between 0 and ”<<limit<<endl;

for(int i = 0; i <= limit; i++)


{
if( i % 2 == 0)
{
cout<<i<<endl;
}
}
}

There is another way to print even numbers without using if-else. Implement that as well.
LAB ASSIGNMENTS:
Implement a program that calculates the sum of all integers from 0 to 10. Display the sum
and average on the output screen.

1. Implement a program that displays the multiples of 7 on the output screen. The
start and end of range for displaying multiples of 7 should be given by the user.

2. Implement a code that prompts the user to enter 10 integers (there can be
repetition). The program will count the number of times the user enters the integer
‘2’. The count will be displayed on the output screen.

3. Implement a code that calculates the factorial of a number entered by the user.
Factorial of negative number does not exist. So whenever user enters a negative
number, convert that into a positive value and then calculate factorial.

4. Implement a code that estimates the value of mathematical constant ‘e’ according
to the following formula:

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’.

5. Implement a program using for loop that prints multiples of 5 from 0 to 100 such
that only 5 numbers are printed on one row. Use if statement to control the numbers
printed on each row.

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the experiment.
Also submit solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 5:
WHILE AND DO-WHILE LOOP
PURPOSE:
To Learn:

1. How to use another repetition loop – the while and do-while loop.
2. How to execute it as a variation of For loop.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:
WHILE LOOP:
The while repetition statement allows the user to execute a particular set of instructions
repeatedly while some condition remains true. The while loop is very similar to for loop and
requires initialization, limiting condition and updating of the control variable involved. The
syntax of a general while loop is as follows:

initialization;
while(condition)
{
Statement(s);
update;
}

A while loop in which the control variable is not initialized, the program execution will not
enter the while loop because the variable whose condition is specified in the while loop does
not have an initial value to start with.
Similarly, if a while loop is not provided with a terminating condition for the control variable
or the terminating condition provided in the while loop never becomes false, both of these
conditions result in an infinite loop. You will have to stop the program execution by force.

As explained above, a while loop executes as long as the condition for the control variable is
true. Keeping this in mind, the condition in the while loop can be replaced by ‘1’ or the keyword
‘true’. In both cases, the while loop will execute forever unless terminated by force.
DO WHILE LOOP:

Every while loop can be converted into a do-while loop but not vice versa. The reason is that
the do-while loop always executes at least once. The basic syntax for a do-while loop is:

initialization;

do
{
Statement(s);
update;
} while(condition);

The do part in above is executed without checking the condition. So even if the condition is
false, the do part will execute at least once, after which the condition in while is checked. If
the condition is true, the do part executes again, otherwise the loop exits.

PROCEDURE:

PART – 1 WHILE LOOP

1. After making the project in visual basic 6.0, write the following program in the
source file.

2. Consider a simple for loop which prints the updated value of a variable 10 times.

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

void main()
{

int i = 0;
while(i < 10)
{
cout<<”the value of i is”<<i<<endl;
i++;
}
}

3. The output screen displays the value of ‘i’ from 0 to 9. The condition i<10 is the
terminating condition for the while loop. The program execution will enter the body
of the while loop as long as the condition is true. The value of the control variable
‘i’ will be different if the update in the value of ‘i’ is made before the
output statement.

4. Consider the following while loop:


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

void main ( )
{

int i = 0;
while(i < 10)
{
i++;
cout<<”the value of i is”<<i<<endl;
}
}

This will display the value of ‘i’ from 1 to 10.

5. In prog2.cpp, if the terminating condition is set to i >= 0, the condition never


becomes false, since the control variable is continuously being incremented and
remains greater than 0. Such a loop will continue indefinitely unless terminated by
force.
6. Consider the following program which prints the first 10 integers in decreasing
order:

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

void main ( )
{
int i = 10;
while(i > 0)
{
i--;
cout<<”the value of i is”<<i<<endl;
}
}

7. Consider the use of ASCII character set. The following program presents a code
that will print continue to print smiley faces on the output screen unless
terminated. Remember that the ASCII value of 1 corresponds to a smiley face.

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

void main ( )
{
char i = 1;
while(1)
{
cout<<i<<” ”;
}
}

8. Prog4.cpp can also be modified such that the ‘1’ or ‘true’ in the condition for the
while loop can be changed from within the loop. Consider a program in which we
want the while loop to terminate if 20 smiley faces have been printed. One way of
doing this is as follows:

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

void main ( )
{
char i = 1;
int a = 1;
int b = 0;

while(a == 1)
{

cout<<i<<” ”;

b++;
if(b == 20)
{
a = 0;
}
}
}

In the above program, two variables control the execution of the loop.
PART – 2 DO WHILE LOOP

1. Consider the following code segment:

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

void main ( )
{
int a = 0;

do
{
a++;
cout<<i<<” ”;

} while(a > 0);


}

2. The do-while loop in prog6.cpp will execute forever even if the initial value of ‘a’ is 0
which does not satisfy the condition in while loop. The output will print numbers
from 0 onwards. If same initialization, increment and condition is used in a while loop
to get the same output as above, the while loop will not execute at all.

3. Consider the following implementation of prog5.cpp using do-while loop:

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

void main ( )
{
char i = 1;
int a = 1;
int b = 0;

do
{
cout<<i<<” ”;

b++;
if (b == 20)
{
a = 0;
}
} while(a == 1);
}
LAB ASSIGNMENTS:
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.

1. 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.

2. Implement a program which takes ‘n’ inputs from the user. The value of ‘n’ will
be specified by the user. The program will determine the number of even integers
entered by the user.

3. 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

4. Implement all of the above using do-while loop.

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 6:
NESTED FOR LOOPS
PURPOSE:
To Learn:

1. How to use repetition loops nested for loop.


2. How to execute conditions.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:
One for loop can be nested inside another for loop. This happens when there is a need to control
the rows and columns of the output. 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, the outer loop run for 10
times. The inner loop will run for the number of values to be displayed in each row i.e.
10 times. Since the numbers displayed are from 0 to 9, the inner loop variable will vary from
0 to 9.

PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.
2. Consider the following code to understand the inner and outer loop executions:

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

void main ( )
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i< 10; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}
}

Observe the output of the above code.


3. The range of numbers on one line and the number of lines can be controlled by the
user. Consider the following code:

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

void main ( )
{
int numbers; int
rows;
cin>>numbers;
cin>>rows;

for(int j = 0; j <=rows; j++)


{
for(inti = 0; i<=numbers; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}
}

4. The user can also define the value from which any particular row begins. For that
purpose the initialized value of the control variable will be changed or defined by the
user as in above program.

5. Now consider a for loop in which the outer loop variable controls the inner loop
variable. Consider the following:

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

void main ( )
{
for(int j = 0; j < 10; j++)
{
for(inti = j; i< 10; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}
}

6. Similarly, the effect of the outer loop variable may appear in the condition part of the
inner loop variable. Consider the following:

// prog4.cpp
#include <iostream.h>
void main ( )
{
for(int j = 0; j < 10; j++)
{
for(inti = 0; i<= j; i++)
{
cout<<i<<” ”;
}
cout<<endl;
}
}

If it is required to display some symbol other than the variable ‘i’ on the output screen, the
cout statement should be changed.

7. Consider prog5.cpp where asterisks will appear on the output screen instead of
numbers.

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

void main ( )
{
for(int j = 0; j < 10; j++)
{
for(int i = 0; i<= j; i++)
{
cout<<”* ”;
}
cout<<endl;
}
}

8. A user defined character can also be displayed on the output screen as shown in the
prog6.cpp below:

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

void main ( )
{
char ch;
cout<<”enter a character to display:”;
cin>>ch;

for(int j = 0; j < 10; j++)


{
for(inti = 0; i<= j; i++)
{
cout<<ch<<” ”;
}
cout<<endl;
}
}

LAB ASSIGNMENTS:
1. Display the following figures using nested for loops:

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

2. Display the following figures using nested for loops:

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

3. Display the following figure using nested for 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.

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

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 7:
1-DIMENSIONAL ARRAYS
PURPOSE:
To Learn:

1. How to initialize and declare arrays.


2. How to use the concept of arrays to solve various problems.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:
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.

PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.

2. 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

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
}

3. 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.

4. 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;
}

5. 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];
}

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


{
cout<<”the array location a[”<<i<<”] = ”<<a[i];
}
}

6. 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.

7. 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;

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.

LAB ASSIGNMENTS:
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.

Task: After going through given questions and answers related to the experiment, submit a separate
report which should include the analysis of results of the experiment. Also submit solved lab
assignment.
Teacher / Supervisor’s Signature:
Experiment - 8:
2-DIMENSIONAL ARRAYS
PURPOSE:
To Learn:

1. How to use 2D arrays used for matrix operations.


2. How to use 2D arrays for other programming practices.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:
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.

PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.
2. The 2D arrays can be declared and/or initialized directly. Consider prog1.cpp as an
example.
// prog1.cpp
#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
}

3. In order to initialize this 2-D array with user-defined values, a nested for loop can be
implemented as follows:

// prog2.cpp
#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];
}
}
}

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

// prog3.cpp
#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;
}
}

5. 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.

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

void main ( )
{
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;
}
}

6. 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]<<” ”;.

7. 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.

// prog5.cpp
#include <iostream.h>
void main ( )
{
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;
}

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

// prog6.cpp
#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;
}
}
LAB ASSIGNMENTS:

1. Use prog4.cpp 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:

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:

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.

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 9:
INFINITE LOOP AND GOT STATEMENT
PURPOSE:
To Learn:

1. How to how to handle infinite loops using goto commands.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:

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.
PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.

2. A simple infinite loop implementation is given in prog1.cpp.

//prog1.cpp
#include <iostream.h>
void main ( )
{
for(;;)
{
cout<<"* ";
}
}

3. 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.
for(int i = 0;;)
{
cout<<"* ";
}
II.

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

4. 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<<"* ";
}

5. 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.
6. 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;
}

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.

7. 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;
}
8. 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)
{
goto repeat;
}
sum = sum + marks;
}
avg = sum/10;
cout<<"average is: "<<avg<<endl;
}

LAB ASSIGNMENTS:
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.

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 10:
SWITCH STATEMENT
PURPOSE:
To Learn:

1. How to implement cases through switch statement.


2. How to terminate loop through break statement.
3. How to use default case.

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:
Switch statement is similar to an if-else structure studied earlier. In switch statement, the option
selected by the user is compared against all the available cases and the appropriate case is
executed. Unlike if-else statement, the user cannot specify a range as the condition for the
switch statement to execute. The switch statement compares the value of a variable with a
constant and cannot do this for a range. The basic syntax followed by a switch statement is:

initialization;
switch(variable)
{
case c1:
statement(s);
break;
case c2:
statement(s);
break;
.
.
.
default:
statement(s);
break;
}

If ‘n’ is the variable used and its value is n = 0, only the case where c1 = 0 will be executed.
If there is no case value for the value of ‘n’ then default case is executed. It is not necessary
to always write a default case but it is a good practice to use one. A default case is similar to
the else block in if-else.
PROCEDURE:

1. After making the project in visual basic 6.0, write the following program in the source
file.
2. Consider the following program that displays the range of marks against the grade
entered by the user.

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

void main ( )
{
char grade;
int a = 0;
switch(grade)
{
case ‘A’:
cout<<”80 < marks <= 100”<<endl;
break;
case ‘B’:
cout<<”67 < marks <= 80”<<endl;
break;
case ‘C’:
cout<<”56 < marks <= 67”<<endl;
break;
case ‘D’:
cout<<”49 < marks <= 56”<<endl;
break;
case ‘W’:
cout<<”Withdrawn”<<endl;
break;
case ‘F’:
cout<<”Fail”<<endl;
break;
default:
cout<<”invalid grade”<<endl;
break;
}
}

3. Prog2.cpp makes use of a switch statement to implement a simple calculator. The


program first displays the menu options and when the user selects an appropriate option,
the program does the corresponding arithmetic operation.

// prog2.cpp
#include <iostream.h>
void main ( )
{
float a, b;
int op;
for(;;)
{
cout<<"enter a: ";
cin>>a;

cout<<"enter b: ";
cin>>b;

cout<<"press 1 for addition"<<endl;


cout<<"press 2 for subtraction"<<endl;
cout<<"press 3 for multiplication"<<endl;
cout<<"press 4 for division"<<endl;
cout<<"press 9 to exit the calculator"<<endl;
cin>>op;

switch(op)
{
case 1:
cout<<a<<" + "<<b<<" = "<<a+b<<endl;
break;
case 2:
cout<<a<<" - "<<b<<" = "<<a-b<<endl;
break;
case 3:
cout<<a<<" * "<<b<<" = "<<a*b<<endl;
break;
case 4:
cout<<a<<" / "<<b<<" = "<<a/b<<endl;
break;
case 9:
goto end;
default:
cout<<"invalid option"<<endl;
break;
}
}
end:
cout<<endl;
}
4. The above program is implemented inside an infinite loop which means the program
will keep on performing arithmetic operations until the user selects 9, after which the
program ends.

LAB ASSIGNMENTS:

1. Implement a 2x2 matrix calculator that determines the addition, subtraction,


multiplication, transpose, adjoint, determinant and inverse of any matrices of size 2x2.
Use switch block as in prog5.cpp to implement the calculator.

2. Suppose that a traffic police man 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.

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 11:
FUNCTIONS & VARIABLE TYPES
PURPOSE:
1. What are the different types of variables on the basis of definition and use
2. What are the functions and why we use them
3. How we define a function, its input and output parameters
4. How these functions are called and used to give specified output
5. What do we mean by function overloading

EQUIPMENT
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:

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.
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.
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.

Function Overloading: Several functions of the same name are defined but with different
signatures. This is known as function overloading. A signature is a combination of a function’s
name and its parameter types (in order).
PROCEDURE

PART – 1 WITH NO INPUT PARAMETER AND VOID RETURN TYPE

1. After making the project in visual basic 6.0 write the following program in the source
file.
2. Compile and build the program and check how it is working.
3. Relate the expected working of the code with its actual output.

// prog1.cpp
#include <iostream.h>
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; // displaying square
}

void main()
{

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


square(); // function call
}

4. Note that 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 displayed inside the
function.
5. Try to return the value from the function without changing its return type. Mention
the output/error in that case:
PART – 2 WITH NO INPUT PARAMETER AND ‘INT’ RETURN TYPE

1. 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.
2. If a function wants to return an integer, it 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.

// prog2.cpp
#include <iostream.h>
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;
}
3. 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.
4. 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 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
}

5. In the above implementation, the local variable‘s’ is not used. This function gives the
same result as before.
6. Try not returning the value from the function without changing its return type.
Mention the output/error in that case:
PART – 3 WITH INPUT PARAMETER(s) AND ‘INT’ RETURN TYPE

1. Consider another implementation of the same function but with a function parameter
as input.
2. Here, the number from the user is not taken inside the function, but is passed from the
main method.
3. The number is taken from the user in the main method and is passed to the function as
a function parameter.
4. 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;
}
5. 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.
6. 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>

int maximum(int a, int b, int c) // function header


{
int n = a; // local variable

if(n < b)
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;
}
7. Try to combine the last two statements in the main method above and write it as one
statement:

Note: Always remember that whenever a function header is written with parameter list, the
values of those parameters are passed from where that function is called. Do not initialize the
parameters inside the function itself.
PART - 4: USE OF LOCAL AND GLOBAL VARIABLES

1. Consider the following two programs prog5.cpp and prog6.cpp.


// 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;
}

// 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;
}
2. List the changes in both the codes.

3. Which variable is acting as a global variable in prog5.cpp and which one in


prog6.cpp.
PART - 5: FUNCTION OVERLOADING

1. Consider the following program.


//prog7.cpp
#include<iostream.h>
int square(int x) //function 1
{
cout<<”square of integer”<<x<<”is”;
return x * x;
}
double square(double y) //function 2
{
cout<<”square of double”<<y<<”is”;
return y *y;
}
int main()
{ cout<<square(7);
cout<<endl;
cout<<square(7.5);
cout<<endl;
}
2. Write the output/error of the above program (prog7.cpp).

3. Two functions having the same name “square” are used. How the program will
distinguish that which function is called.

4. Change the return type of function 2 to ‘int’ and rerun the code. Record the change
occurred this time. Also give reason for that.
LAB ASSIGNMENTS:

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.
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). The grades returned from this function are displayed
in the main method.

Grading criteria is:


Grade A: 90 <= marks <= 100
Grade B: 80 <= marks < 90
Grade C: 70 <= marks < 80
Grade D: 60 <= marks < 70
Grade F: 50 <= marks < 60

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 12:
FUNCTIONS WITH ARRAYS & CREATING HEADER FILES

PURPOSE:
To Learn:
1. How we can use functions with arrays 1D and 2D
2. What would be there input parameters and return types
3. How we can make a header file

EQUIPMENT:
1. Personal Computer
2. Visual Basic 6.0 software

INTRODUCTION:
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 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.

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.

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
Explanation
Header
Contains function prototypes for the standard input/output library
<iostream.h>
functions, and Information used by them
<math.h> Contains function prototypes for math library functions.
<string.h> Contains function prototypes for string processing functions.
Contains function prototypes and types for manipulating the time and
<time.h>
date.
Contains function prototypes for conversions for numbers to text and
<stdlib.h> 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.

PROCEDURE:

PART – 1 FUNCTIONS WITH 1D ARRAY

1. After making the project in visual basic 6.0 write the following program in the source
file.

// prog1.cpp
#include <iostream.h>
int i, 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;
input(b);
sum(a, b);
cout<<”displaying sum of two arrays:”<<endl;
output(c);
}

2. Compile and build the program and check how it is working.


3. Relate the expected working of the code with its actual output.
4. Note: 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 above program defines 3 functions and then calls
them in the main method.
5. 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.
6. The input() function above can initialize arrays of size 10 only. Give its reason

7. In order to implement a general function to initialize an array of any size consider the
following program:

// prog2.cpp
#include <iostream.h>
int i;
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);
}
8. The above program calls the input() function to initialize 2 arrays of different sizes.
How?
PART – 2 FUNCTIONS WITH 2D ARRAY

1. Consider the following program


// prog3.cpp
#include <iostream.h>
int i, 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];
}
}
}
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);
}
2. The above program adds two 2x2 matrices and displays the resultant matrix.
3. Can we do that by making the 2D array ‘c’ a local array?

4. What changes will be required if we make all arrays global.


PART – 3 MAKING HEADER FILES

1. Consider the following code.

// 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

2. The above code defines a header file ‘maximum.h’.


3. Now consider the following program

// 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;
}
4. In the above implementation, we don’t need to define function maximum.
5. Using the custom header file, maximum function is used.
Note: Always remember that 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.
LAB ASSIGNMENTS:

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).

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 13:
STRINGS
PURPOSE:
To Learn:
1. What do we mean by strings
2. How to implement them
3. Different function using strings
4. Use of string in 2D arrays
Equipment:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:

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.

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.

strcmp(s1,s2); String compare function compares the strings s1 and s2. The function
returns 0 if the s1 and s2 are same, -1 if s1 is less (in length) than s2
and 1 if s1greater (in length) than s2.
strlen(s); Returns length of string s. The number of characters preceding the
terminating null character is returned.

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


PROCEDURE

PART – 1 DEFINING AND INITIALISING STRINGS

1. After making the project in visual basic 6.0 write the following program in the source file.
2. Compile and build the program and check how it is working.
3. Relate the expected working of the code with its actual output.
// 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;

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

char s3[] = “save the world”;


cout<<s3<<endl; // function
call
}

4. Write the output of the above program.


5. Note: ‘\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 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.

PART – 2 INITIALISING THE ARRAY USING USER INPUT

1. Consider the following program

// prog2.cpp
#include <iostream.h>
void main()
{
char s[15];
cin>>s;
cout<<s<<endl;
}
2. In the above program, give input ‘save the world’.
3. Note the output by the third statement.
4. 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.
5. Consider the following code segment:
6. 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 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’:

// prog3.cpp
#include <iostream.h>
#include <stdio.h>
void main()
{
chars[15];
gets(s);
puts(s);
cout<<s;
}
7. In the above program, give input ‘save the world’.
8. Note the output by the ‘puts()’ statement.
9. Note the output by the ‘cout’ statement.

PART – 3 STRING LIBRARY FUNCTIONS

1. 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;
}
1. Write the output of the above program

2. Changes the order of parameters passed to the function and observes the output.

3. Consider the following program to understand the usage 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; }
4. Write the output of the above program

5. Changes the order of parameters passed to the function and observes the output.

6. Take the values of both the strings from the user and apply the function.
7. Consider the following program to understand the usage of the function strcmp(s1,s2).

// prog6.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;
}
}
8. Write the output of the above program

9. Changes the order of parameters passed to the function and observes the output.

10. Consider the following program to understand the usage of the function strlen(s)
// prog7.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;


}
11. Write the output of the above program

12. Consider the following program to understand the usage of the function strchr(s,c).
// prog8.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<<”’ is
\””<<strchr(s,c)<<”\””<<endl;
}
else
{
cout<<”character ‘”<<c<<”’ was not found in string \””<<s<<”\””<<endl;
}
}

13. Write the output of the above program

14. Changes the order of parameters passed to the function and observes the output.
PART – 4 2D ARRAY OF STRINGS

1. Consider the following program

//prog9.cpp
#include <iostream.h>
#include <string.h>
#include <stdio.h>
//global arrays
char country[5][9] = {"Pakistan", "China", "Iran", "India", "Thailand"};
char code[5][4] = {"092", "086", "098", "091", "066"};

void search(char s1[10])


{
inti = 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:;
}

void main()
{
char s1[10];

cout<<"enter country name: ";


cin>>s1;
search(s1);
}
2. Write the output of the above program by giving input ‘Iran’

3. Note: In the global 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 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.
4. Try giving inputs outputs which are in the array. Also try a country other than those
defined above. Write your observations below

LAB ASSIGNMENTS:

1. Implement a program that can displays the date.


void display(char m[], int day, int year)–the name of the month is taken as a
string, and the day and year as integers from the main method and passed to the
display function. This function displays the date in the format: May 28, 2013

a. Implement the main method. Initialize the month, date and year from the user
and pass it to the function call.

2. Implement your own function to calculate the length of a string:


int stringlength(char s[])– this function counts the number of characters in the
string ‘s’ and returns the count.
In the main method, call the above function and pass a user-defined string to this
function. Display the length of string as returned from this function.
3. Implement the following functions:
void reverse(char s[]) – this function reverses the string ‘s’ passed to the function.
You can use the strlen() function to determine the length of the string and then run
the loop for that length of string.
void palindrome(char s[]) – a palindrome is a string which it read same backwards
as forwards. This function uses the function above to reverse the string ‘s’ passed
as parameter. This function 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.
In the main method, initialize a user-defined string. Call the function palindrome()
to check if the string is a palindrome or not.

4. The registration number of a student of engineering department looks like


L1F12BSEE0011 or L1F12BSME0100. Implement a function which takes a registration
number as parameter and separates the Session, department and roll no. from it. The
function should store these fields in separate strings and display them. In the main
method, initialize a registration number from the user and pass it to the function which
will display the three fields separately.

5. Declare and initialize a global array of strings that has the names of 5 courses that a
student has registered for a specific semester. Implement a function to replace any course
in that list with another user-defined course:
void replace(char course1[], char course2[]) – this function takes 2 strings as
parameter. The function should search the first string in the global array of 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. Call the above function to replace the desired course.
Display the list of courses after replacing the course.

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 14:
LINEAR SEARCH AND BINARY SEARCH
PURPOSE:
To Learn:
1. Need of searching in an array
2. Concept and Implementation of Linear Search
3. Concept and Implementation of Binary Search
Equipment:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:
Linear Search: More often there are applications in which it is required to search the whole
data for one particular value. Here we will consider the data being placed in an array and the
value can be any integer, character, double or float, etc. The linear search algorithm for this
purpose is very simple. Linear search algorithm works best for small and unsorted arrays. The
algorithm begins its search from the start of the array and checks every element, index wise,
to see if that element is required.

Binary Search: Binary search is a more efficient algorithm to search an array. The algorithm
always operates on sorted arrays. The algorithm’s efficiency relies on the fact that, to find a
particular element, we don’t need to traverse the whole array. Binary search algorithm
eliminates from consideration one half of the elements in a sorted array after each
comparison. It first determines the beginning, end and middle of the array, and then it decides
in which half of the array the desired element will be located.
PROCEDURE:

PART – 1 LINEAR SEARCH

1. After making the project in visual basic 6.0 write the following program in
the source file.

// prog1.cpp
void linearsearch (int a[ ],int key, int s)
{
for(int i = 0; i<s; i++)
{
if(a[i] == key)
{
cout<<"element found";
goto end;
}
}
cout<<"element not found";
end:;
}

2. Write the ‘main’ for the above program and call the searching function in
it.
3. Compile and build the program and check how it is working.
4. Relate the expected working of the code with its actual output.
5. The linear search function above accepts the array in which the element is
to be searched, the element to be searched and the size of the array. The
above function can also be implemented as follows:

// prog2.cpp
int linearsearch(int a[], int key, int size)
{
for(int i = 0; i<size; i++)
{
if(a[i] == key)
{
cout<<"element found";
return 0;
}

}
cout<<"element not found";
return 0;
}
1. Observe the difference between the two functions.
2. Modify the above function in such a way that it returns the index location
of the array where the element is found.

PART – 2 BINARY SEARCH

1. After making the project in visual basic 6.0 write the following program in the source
file.

// prog3.cpp
void binarysearch(int a[], int key, int size)
{
int low = 0;
int high = size – 1;
int mid;

while(low <= high)


{
mid = (low + high)/2;
if(key == a[mid])
{
cout<<"element found";
goto end;
}
else if(key < a[mid])
{
high = mid - 1;
}
else if(key > a[mid])
{
low = mid + 1;
}
}
cout<<"element not found";
end:;
}
2. Write the ‘main’ for the above program and call the searching function in it.
3. Compile and build the program and check how it is working.
4. Relate the expected working of the code with its actual output.
5. What happens if we call do binary search on an unsorted array? Why?

6. Modify the return type of the above function to ‘int’ and try to return the index of the
array location where the element is found.
LAB ASSIGNMENTS:

1. Take a 2D array of size 3 by 3 in the main method. Implement the


following functions:
a. void input(int a[3][3]) – to take user defined input for the array.
b. void output(int a[3][3]) – to display array of integers.
c. int linearsearch(int a[3][3], int key) – this function is the modified version of
prog4.cpp. This function will also check how many times the ‘key’ value entered
by the user occurs in the array. Return the count. Return ‘0’ if the
‘key’ value is not present in the array.

2. Modify question 3 to use binary search in an array that is sorted in


descending order.

Task: After going through given questions and answers related to the experiment, submit a
separate report which should include the analysis of results of the experiment. Also submit
solved lab assignment.
Teacher / Supervisor’s Signature:
Experiment - 15:
SELECTION SORT AND BUBBLE SORT
PURPOSE:
To Learn:
1. Need of sorting in an array
2. Concept and Implementation of Selection Sort
3. Concept and Implementation of Bubble Sort
Equipment:
1. Personal Computer
2. Visual Basic 6.0 software
INTRODUCTION:
Sorting refers to arranging or placing data into particular order (ascending or descending). It
is a very important computing application. A bank sorts all checks by account number so that
it can prepare individual bank statements at the end of each month. Telephone companies sort
their list of accounts by last name and, within that, by first name to make it easy to find phone
numbers. There are many sorting algorithms that vary in their time and space complexity.
The one that is suited to apply in a particular situation is used. We will study how different
sorting algorithms are developed into C++ coding from a simple algorithmic logic.
Selection Sorting:

The selection sort algorithm follows the following steps:

1. Compare all the values in the array with the first value.
2. Swap the smaller value with the value in the first place.
3. Repeat above steps for the other locations until the array is completely sorted.

swap

5 8 7 9 3 2 0 1 4 6

Bubble Sorting:

The selection sort algorithm follows the following steps:

1. Compare every value in the array with adjacent value.


2. Swap the adjacent values if they are not in ascending order.
3. Repeat above steps until the array is completely sorted.

7 8 5 6 9 4 0 1 2 3
PROCEDURE:

PART – 1 SELECTION SORT

1. After making the project in visual basic 6.0 write the following program in
the source file.

// prog1.cpp
void selection(int a[], int size)
{
int i, j, temp;
for (i = 0 ; i < size – 1 ; i++)
{
for( j = i+1 ; j < size ; j++)

{
if (a[j] < a[i])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
//point1
}
}

2. Write the ‘main’ for the above program and call the searching function in it.
3. Compile and build the program and check how it is working.
4. Relate the expected working of the code with its actual output.
5. Modify the above code to display your array at ‘point1’.
6. Observe the output and write your observations.
PART – 2 BUBBLE SORT

1. After making the project in visual basic 6.0 write the following program in
the source file.

// prog2.cpp
void bubble(int array[], int size)
{
int i, j, temp;
for (i = 0;I < size -1 ; i++)
{
for(j = 0 ; j < size - i; j++)
{
if (a[j] > a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
//Point1
}
}

2. Write the ‘main’ for the above program and call the searching function in
it.
3. Compile and build the program and check how it is working.
4. Relate the expected working of the code with its actual output.
5. Modify the above code to display your array at ‘point1’.
6. Observe the output and write your observations.
LAB ASSIGNMENTS:

1. Take an array of size 10 in the main method. Implement the following


functions:
a. void input(int a[], int size) – to take user defined input for the array.
b. void output(int a[], int size) – to display array of integers.
c. void selection(int a[], int size) – from prog1.cpp to sort the array using
selection sort.
d. int median(int a[], int size) - it takes an array of size 20 as a parameter. Inside
this function the bubble sort function is called and the array is passed to the
sorting function. After the array is sorted, determine the median of the array and
return the value of median calculated.
(Note: median is the middle value of a sorted array)
In the main method, use the above function to take random input and display the
unsorted array. Then call the median function.

2. Take an array of size 20 in the main method. Implement the following


functions:
a. void input(int a[], int size) – to take user defined input for the array.
b. void output(int a[], int size) – to display array of integers.
e. void bubble(int a[], int size) – from prog2.cpp to sort the array using bubble
sort.
c. int binarysearch(int a[], int key, int size) – before using this function sort
your array using any sorting technique. After sorting pass the sorted array to the
function given in program prog5.cpp.Use this function to search for a user
defined value in ‘key’ passed from the main method.

Task: After going through given questions and answers related to the experiment,
submit a separate report which should include the analysis of results of the
experiment. Also submit solved lab assignment.
Teacher / Supervisor’s Signature:

91
APPENDIX A: Lab Evaluation Criteria

 Experiment and Reports 50%

o Experiment 60%
o Report 40%

 Quizzes 15%

 Final Evaluation 35%

o Code Implementation 60%


o Quiz 40%

Notice:
Copying and plagiarism of lab reports is a serious academic misconduct. First instance of copying may entail ZERO
in that experiment. Second instance of copying may be reported to Dean’s Office. This may result in awarding FAIL
in the lab course.

92
APPENDIX B: LAB Performance and Manual Rubrics

Excellent Acceptable Amateur Unsatisfactory Marks


5 4 3 2 Obtained
Specifications The program The program The program The program is
works and meet works, produces displaying
all specifications produce correct result incorrect
correct results but are not results
and displayed displayed
correctly. Also correctly
meet most of
other
specifications
Readability The code is The code is The code is The code is
exceptionally fairly easy to readable only by poorly
well organized read someone who organized and
and very easy to knows what it is very difficult to
follow supposed to be read
doing
All assignments All All assignments All assignments
are well assignments are not are not
Lab Report organized. are complete. complete. Most complete.
Programs are Most of of Programs and Outputs are
complete. Programs and outputs are missing.
Outputs are outputs are displayed. Conclusion is
displayed. displayed. Conclusion is not written
Conclusion is Conclusion is written
well written written

Total Marks

93
APPENDIX C: Safety around Electricity
In all the Electrical Engineering (EE) labs, with an aim to prevent any unforeseen accidents during conduct of lab
experiments, following preventive measures and safe practices shall be adopted:
 Remember that the voltage of the electricity and the available electrical current in EE labs has enough power to
cause death/injury by electrocution. It is around 50V/10 mA that the “cannot let go” level is reached. “The key
to survival is to decrease our exposure to energized circuits.”
 If a person touches an energized bare wire or faulty equipment while grounded, electricity will instantly pass
through the body to the ground, causing a harmful, potentially fatal, shock.
 Each circuit must be protected by a fuse or circuit breaker that will blow or “trip” when its safe carrying capacity
is surpassed. If a fuse blows or circuit breaker trips repeatedly while in normal use (not overloaded), check for
shorts and other faults in the line or devices. Do not resume use until the trouble is fixed.
 It is hazardous to overload electrical circuits by using extension cords and multi-plug outlets. Use extension
cords only when necessary and make sure they are heavy enough for the job. Avoid creating an “octopus” by
inserting several plugs into a multi-plug outlet connected to a single wall outlet. Extension cords should ONLY
be used on a temporary basis in situations where fixed wiring is not feasible.
 Dimmed lights, reduced output from heaters and poor monitor pictures are all symptoms of an overloaded circuit.
Keep the total load at any one time safely below maximum capacity.
 If wires are exposed, they may cause a shock to a person who comes into contact with them. Cords should not
be hung on nails, run over or wrapped around objects, knotted or twisted. This may break the wire or insulation.
Short circuits are usually caused by bare wires touching due to breakdown of insulation. Electrical tape or any
other kind of tape is not adequate for insulation!
 Electrical cords should be examined visually before use for external defects such as: Fraying (worn out) and
exposed wiring, loose parts, deformed or missing parts, damage to outer jacket or insulation, evidence of internal
damage such as pinched or crushed outer jacket. If any defects are found the electric cords should be removed
from service immediately.
 Pull the plug not the cord. Pulling the cord could break a wire, causing a short circuit.
 Plug your heavy current consuming or any other large appliances into an outlet that is not shared with other
appliances. Do not tamper with fuses as this is a potential fire hazard. Do not overload circuits as this may cause
the wires to heat and ignite insulation or other combustibles.
 Keep lab equipment properly cleaned and maintained.
 Ensure lamps are free from contact with flammable material. Always use lights bulbs with the recommended
wattage for your lamp and equipment.
 Be aware of the odor of burning plastic or wire.
 ALWAYS follow the manufacturer recommendations when using or installing new lab equipment. Wiring
installations should always be made by a licensed electrician or other qualified person. All electrical lab
equipment should have the label of a testing laboratory.
 Be aware of missing ground prong and outlet cover, pinched wires, damaged casings on electrical outlets.
 Inform Lab engineer / Lab assistant of any failure of safety preventive measures and safe practices as soon you
notice it. Be alert and proceed with caution at all times in the laboratory.
 Conduct yourself in a responsible manner at all times in the EE Labs.
 Follow all written and verbal instructions carefully. If you do not understand a direction or part of a procedure,
ASK YOUR LAB ENGINEER / LAB ASSISTANT BEFORE PROCEEDING WITH THE ACTIVITY.
 Never work alone in the laboratory. No student may work in EE Labs without the presence of the Lab engineer
/ Lab assistant.
 Perform only those experiments authorized by your teacher. Carefully follow all instructions, both written and
oral. Unauthorized experiments are not allowed.
 Be prepared for your work in the EE Labs. Read all procedures thoroughly before entering the laboratory. Never
fool around in the laboratory. Horseplay, practical jokes, and pranks are dangerous and prohibited.
 Always work in a well-ventilated area.
 Observe good housekeeping practices. Work areas should be kept clean and tidy at all times.
 Experiments must be personally monitored at all times. Do not wander around the room, distract other students,
startle other students or interfere with the laboratory experiments of others.
 Dress properly during a laboratory activity. Long hair, dangling jewelry, and loose or baggy clothing are a hazard
in the laboratory. Long hair must be tied back, and dangling jewelry and baggy clothing must be secured. Shoes
must completely cover the foot.
Know the locations and operating procedures of all safety equipment including fire extinguisher. Know what to do
if there is a fire during a lab period; “Turn off equipment, if possible and exit EE lab immediately.”

94
APPENDIX D: Guidelines on Preparing Lab Reports
Each student will maintain a lab notebook for each lab course. He will write a report for each experiment he performs
in his notebook. A format has been developed for writing these lab reports.
C.I: Hardware Lab Report Format
For hardware based labs, the format of the report will include:
1. Introduction: Introduce area explored in the experiment.
2. Objective: What are the learning goals of the experiment?
3. Measurements: In your own words write how the experiment is performed (Do not copy/paste the
procedure).
a. Issues: Which technical issues were faced during the performance of the experiment and how they
were resolved?
b. Graphs, if any
4. Conclusions: What conclusions can be drawn from the measurements?
5. Applications: Suggest a real world application where this experiment may apply.
6. Answers to post lab questions (if any).

Sample Lab Report: Hardware Experiments


Introduction
An RC circuit is a first order circuit that utilizes a capacitor as an energy storage element whereas a resistor as an
energy wastage element. RC circuits are building blocks of electronic devices and their thorough understanding is
important in comprehending advance engineering systems such as transistors and transmission lines.
An RC circuit can be operated with both DC and AC sources. In this lab we study transient response of RC circuits
with a square wave as a DC source. During the DC operation of an RC circuit the voltage across the capacitor or the
resistor show energy storing (capacitor charging) and dissipating (capacitor discharging via resistor) mechanisms of
the circuit. The capacitor charging or discharging curves then lead to determine time constant of the circuit where
the time constant signifies time required by the RC circuit to store or waste energy.
Objective:
To study transient response of a series RC circuit.
Measurements:
The circuit used for the experiment is shown in Fig. 1. Both input (a square wave) and output (voltage across
capacitor) waveforms are monitored on an oscilloscope. The capacitor charging is observed during "on" part of the
square waveform whereas the capacitor discharging is observed during "off" part of the square waveform (Fig. 2).
We measure the time constant from the capacitor charging or discharging curve. While keeping the capacitor value
constant, we also measure time constants with various resistor values (Table 1).

Fig.1. The circuit used in the experiment


Issues:
Mention any issue(s) you encountered during the experiment and how they were resolved.
Conclusions:
From the measurements following conclusions can be drawn:
a) The capacitor charging and discharging curves are exponential.
b) The time constant is directly proportional to the resistor value.
Both of the above conclusions are also easily verifiable by solving differential equation for the RC circuit.
Applications:
An RC circuit can be employed for a camera flash. The capacitor discharges through the flash light during a picture
taking event.

95
INPUT VOLTAGE VOLTAGE ACROSS A CAPACITOR

Fig. 2. Input and Output waveforms

TABLE I. Time constant as a function of the resistor values


Resistance
270 Ω 330 Ω 470 Ω 1 kΩ 2.2 kΩ 3.3 kΩ
(Nominal)
Resistance
(Measured)
Time constant
(Calculated)
Time constant
(Measured)
Capacitance
(Measured)

C.2: Programming Stream Lab Report Format

For programming streams, the format of the report will be as given below:
1. Introduction: Introduce the new constructs/ commands being used, and their significance.
2. Objective: What are the learning goals of the experiment?
3. Design: If applicable, draw the flow chart for the program. How do the new constructs facilitate
achievement of the objectives; if possible, a comparison in terms of efficacy and computational tractability
with the alternate constructs?
4. Issues: The bugs encountered and the way they were removed.
5. Conclusions: What conclusions can be drawn from experiment?
6. Application: Suggest a real world application where this exercise may apply.
7. Answers to post lab questions (if any).

Sample Lab Report for Programming Labs


Introduction
The ability to control the flow of the program, letting it make decisions on what code to execute, is important to the
programmer. The if-else statement allows the programmer to control if a program enters a section of code or not
based on whether a given condition is true or false. If-else statements control conditional branching.

if ( expression )
statement1
else
statement2
If the value of expression is nonzero, statement1 is executed. If the optional else is present, statement2 is executed if
the value of expression is zero. In this lab, we use this construct to select an action based upon the user's input, or a
predefined parameter.

96
Fig. 1. (Caption)
Objective:
To use if-else statements for facilitation of programming objectives: A palindrome is a number or a text phrase that
reads the same backward as forward. For example, each of the following five-digit integers is a palindrome: 12321,
55555, 45554 and 11611. We have written a C++ program that reads in a five-digit integer and determines whether
it is a palindrome.
Design:
The objective was achieved with the following code:
#include<iostream>
usingnamespace std;
int main()
{
int i,temp,d,revrs=0;
cout<<"enter the number to check :";
cin>>i;
temp=i;
while(temp>0)
{
d=temp%10;
temp/=10;
revrs=revrs*10+d;
}
if(revrs==i)
cout<<i<<" is palindorme";
else
cout<<i<<" is not palindrome";
}
}

The conditional statement made this implementation possible; without conditional branching, it is not possible to
achieve this objective.
Issues:
Encountered bugs and issues; how were they identified and resolved.
Conclusions:
The output indicates correct execution of the code.
Applications:
If-else statements are a basic construct for programming to handle decisions.

97

You might also like