Eee 2110
Eee 2110
Laboratory Manual
for
Electrical and Electronic Engineering Sessional Course
Student Name :
Student ID :
Welcome to the Programming Language Laboratory (EEE 2110). This is the first laboratory on program-
ming language and is required for all electrical and electronic engineering students. This course introduces
the fundamental concepts of structured programming.
This laboratory manual is designed to be used in conjunction with the course Programming Language
(EEE 2109). The experiments in this laboratory are based on theory and concepts learned in EEE 2109. The
laboratory activities typically illustrate concepts from class lectures by using examples, implementations,
and problems that are designed to challenge the student. This laboratory is designed in such a way that the
environment provides a student with the opportunity to try various options or approaches and to receive
immediate feedback.
This laboratory manual will help the students to learn fundamental knowledge of the basic terminologies
used in computer programming. The students will also be able to proficiently transform designs of prob-
lem solutions into a standard programming language, use an integrated development environment (IDE) to
write, compile, and execute programs involving a small number of source files. In addition to that, they will
proficiently use fundamental programming elements including variable declaration, data types and simple
data structures (arrays, strings, and structures), decision structures, loop structures, functions/methods, in-
put and output for console and text files. In addition, students will apply debugging and testing techniques
to locate and resolve errors and to determine the effectiveness of a program.
In each week, the lectures are followed by a three-hour laboratory. Each laboratory activity in this
manual is designed to illustrate and explore concepts from that week’s lectures. Thus, the pace of the course
is very much driven by the laboratory activities. This laboratory has close to thirty students, with two
supervising instructors and a laboratory assistant. In the laboratory, every student has a computer, but
sometimes students work together in small groups of two so that students help each other and share the
responsibility of teaching and learning. We encourage the students to seek assistance from supervising
instructors at any point during the laboratory if they need help.
This manual is designed in such a way that students can easily grasp the fundamental of C++. Students
will start with the introduction to the computers for setting up the IDE for C++. Then they will gradually
explore variables and constants, operators, expressions, control statements, functions, array, pointer, string,
and finally the object-oriented programming using C++. In the end, this laboratory reviews the skills devel-
oped in the manual by requiring the student to develop several small programs. In this way, students can be
prepared for the final project. Such several programs are presented at the end of each laboratory in the post
laboratory problems. Each program focuses on a programming skill that students should now be able to
perform on their own. The featured skills are prompting for and extracting input, translating mathematical
formulas to C++ code, checking the validity of input according to some stated criteria, writing a function
that accepts optional parameters, opening a data file, and processing the data.
The instructor has some flexibility in deciding how to use the laboratories. Much of Laboratory 1 should
be review material for many students. If desired, Laboratories 1 and 2 can be combined into a single labo-
ratory. In this way, the instructor can decide whether two Laboratories can be combined into one or one
Laboratory can be split into two depending on the students’ understanding.
Finally, we thank the users of this laboratory manual. We welcome your comments, suggestions, and
ideas for improving this material.
ii
Course Outline
Course Assessment
1. Online and offline task: A combination of online and offline assignments may be provided for asessing
the performance.
2. Mode of evaluation: Individual code implementation and evaluation will be conducted in the form of
presentation, quiz and/or viva. Late submissions are to be highly discouraged and will be penalized.
3. Semester project: An individual project will be assigned to the student before the end of the semster.
Students will be provided a time period for completing and submitting the project. Students will be
asked to attend a viva on their respective projects.
a) Basic Requirements: Clear understanding of all the lab experiments of C++ programming.
b) Presentation Requirement: Yes.
c) Demonstration Requirement: Depending on the semester project, demonstration will be con-
ducted by respective lab teachers.
d) Reporting Requirement: A brief report along with the codes must be submitted.
4. Final quiz: There will be a final quiz based on all the lab experiments done in this lab. Quiz must
not include specific project oriented questions. The quiz may consist of MCQ, True/False, Small code
snippet (i.e., possible outputs, any existing bug, etc.).
5. Percentages of assessment methods:
Laboratory 5. Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.2. Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.3. C++ library functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.4. C++ user-defined function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.4.1. C++ function declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.4.2. Calling a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5.4.3. Function prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.5. The void function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
5.6. Boolean functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.7. Passing arguments by value and by reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.8. Function overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.9. Default arguments (parameters) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Laboratory 6. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2.1. Array declaration in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2.2. Access elements in array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
6.2.3. Array initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.3. Passing array to function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
6.3.1. Linear search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
6.3.2. Bubble sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
6.4. Multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.4.1. Declaration of multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.4.2. Size of multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.4.3. Initialization of multidimensional arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Laboratory 7. Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2. Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2.1. Address-of operator (&) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.2.2. Dereference operator (∗) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.2.3. Pointer declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.3. Pointers and arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.3.1. Dynamic arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.4. Pointers to functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Laboratory 8. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.2. C-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.2.1. Initialization of C-strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.2.2. Standard C-string Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
8.3. Standard C++ Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Laboratory 9. Structures and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
9.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
9.2. Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
9.2.1. Declaring and defining a structure in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
9.2.2. Accessing members of a structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
9.2.3. Structure to function (Passing by value) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Contents vii
1.1. Objective
This introductory laboratory teaches students the basic skills that they will need to complete future
laboratories. These skills include gaining access to the machine, having first contact with the IDE, writing
your first C++ program, compiling C++ programs, executing C++ programs.
You may be working with a wide variety of computer equipment. No matter what computer you used
earlier, your first contact with the computer will be through its operating system. Operating system itself
is a program that coordinates the activities of the machine and performs tasks as directed by the machine’s
user (or users). You will communicate with the operating system through a keyboard, mouse, and monitor
screen. Your instructor will explain how to establish contact with the operating system and will supply you
with any customized information (such as user identification numbers or passwords) that you may need.
Through the machine’s operating system you will be able to activate numerous auxiliary programs, some
of which are designed to assist in program development. These are the programs you will learn to use in
this laboratory session. In some cases these programs may be bundled as an integrated package; in other
cases they may appear as individual programs whose services you must explicitly request. Your instructor
will describe how your particular system operates.
The steps required to develop programs using the C++ language will depend on the computer installation
being used. However, some features of the process are common to all systems.
As a first step, the programmer uses a program called an editor to type a C++ language version of the
program being developed. This editor may be a stand-alone utility program or a part of an integrated soft-
ware development package, which is also known as integrated development environment (IDE). Once the
program has been typed, it is usually saved as a file in mass storage. This version of the program is known
as the source program because it is the initial, or source, version of the program. It is this version to which
you will return when alterations to the program are required.
A program in its source form cannot be executed by the computer; it must first be translated into the
machine’s own low-level language. This translation process is performed by a program known as a translator
or compiler. Your instructor will explain the details of how to type, save, translate, and finally execute
programs using your particular computer system. In the next section we will discuss how we use the IDE
for developing C++ programs for this laboratory.
2 Laboratory 1. Introduction to the C++
For Windows
1. Make sure your computer is connected to the internet.
2. To download the software from the official source go to the URL http://www.codeblocks.org/downloads.
3. Then click Download the binary release in that web page.
4. Then select your operating platform (e.g., Windows XP / Vista / 7 / 8.x / 10). Download the installer
with GCC Compiler, e.g., mingw-setup.exe. This installer includes the MinGW’s GNU GCC compiler
and GNU GDB debugger.
5. Now install Code::Blocks by running the downloaded installer. Accept the default options by clicking
a series of Next buttons.
int main ()
{
cout << "Hello world!" << endl;
return 0;
}
7. At this point, you will have your main.cpp file, which you can modify if you like. For now, it just says
Hello World!, so we can run it as is. Hit F9, which will first compile it and then run it.
8. If it compiles successfully, the Build log at the bottom of the Code::Blocks window will display the
following message.
Process terminated with status 0 (0 minute (s), 0 second (s))
0 error(s), 0 warning (s) (0 minute (s), 0 second (s))
Example 01
Below is a simple “Hello world!” program. You can consider it as the basic C++ template.
1 // my first program in C++
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "Hello world!" << endl;
7 cout << "I’m a C++ program ." << endl;
8 return 0;
9 }
4 Laboratory 1. Introduction to the C++
In C++, the #include is called a preprocessor directive. Preprocessor directives begin with a # sign. They
are processed before compilation. The directive #include <iostream> tells the preprocessor to include the
iostream header file to support input/output operations.
The using namespace std; statement declares std as the default namespace used in this program. The
names cout and endl, which is used in this program, belong to the std namespace. These two lines shall be
present in all our programs.
The main() function is the entry point of program execution. main() is required to return an int (integer).
The output to the display console is done via cout and the stream insertion (or put-to) operator <<. A
special symbol called endl (END-of-Line) can be used to produce a newline. Whenever an endl is printed,
there is no visible output, but the cursor advances to the beginning (left-margin) of the next line. A string,
which is enclosed by a pair of double quotes, will be printed as it is, including the white spaces and punctu-
ation marks within the double quotes.
The last line of the program is return 0; which terminates the main() function and returns a value of 0
to the operating system. Typically, return value of 0 signals normal termination; whereas value of non-zero
(usually 1) signals abnormal termination. This line is optional. C++ compiler will implicitly insert a return
0; to the end of the main() function.
The console output of the above program will be as follows.
Hello world!
I’m a C++ program .
Example 02
This is another version of the “Hello world!” program. As you can see in this example, you can print as
many items as you wish to cout, by chaining the items with the << operator.
1 // prints "Hello world !":
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "Hel" << "lo wo" << "rld!" << endl;
7 cout << "I’m" << " a C+" << "+ program ." << endl;
8 return 0;
9 }
Example 03
The following program will help you to understand insertion of numeric literals into the standard output
stream of a C++ program. Integers (such as 1, 2, 3) and floating-point numbers (such as 1.1, 2.2) can be printed
with the help of cout too.
1 // prints "Hello world !":
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "Hello world!" << endl;
1.5. Introduction to the C++ programs 5
Example 04
The following program will help you to understand insertion of escape characters (\n and \t) in a C++
program. Beside the endl, you can also use \n, which denotes a newline character, to advance the cursor to
the next line. Similarly, you could use \t, which denote a tab character, to advance the cursor to the next tab
position. \n and \t are known as escape sequences.
1 // usage of \n and \t in a C++ program
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "This is an example of using ’\\n ’." << endl;
7 cout << "\n*\n**\n***\n****\n *****\ n" << endl;
8 cout << "This is an example of using ’\\t ’." << endl;
9 cout << "\t*\t**\t***\t****\t *****\ t" << endl;
10 cout << "This is an example of using both ’\\n’ and ’\\t ’." << endl;
11 cout << "\n\t*\n\t**\n\t***\n\t****\n\t *****\ n\t" << endl;
12 return 0;
13 }
It is strongly recommend that you use endl to print a newline, instead of \n. This is because line delim-
iter is system dependent: Windows use \r\n; UNIX/Linux/Mac use \n. The endl produces system-specific
newline. Furthermore, endl guarantees that the output is flushed; while \n does not.
Example 05
Write and run the folowing program to print W as a block letter.
1 // prints "W" as a block letter
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "# #" << endl;
7 cout << " # #" << endl;
8 cout << " # #" << endl;
9 cout << " # # #" << endl;
10 cout << " # # # #" << endl;
11 cout << " # # # #" << endl;
12 cout << " # #" << endl;
13 }
6 Laboratory 1. Introduction to the C++
Example 06
Write and run the following program to print your name, student ID, year, semester, section and depart-
ment name.
1 // prints personal information
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 cout << "Name: your_name " << endl;
7 cout << "ID: your_student_ID " << endl;
8 cout << "Year: your_current_year " << endl;
9 cout << " Semester : your_current_semester " << endl;
10 cout << " Section : your_section " << endl;
11 cout << " Department : your_department " << endl;
12 return 0;
13 }
Post-laboratory Problems
1. What is/are the error(s) in the following C++ program? Write down the exact output of the following
program after correcting the error.
1 # include <iostream >
2 int main ()
3 // this program prints
4 "Hello , World!":
5 cout << "Hello , World !\n"
6 return 0;
7 }
2. What is/are the error(s) in the following C++ program? Write down the exact output of the following
program after correcting the error.
1 include <iostream .h>
2 int main ()
3 {
4 cout << "Patri";
5 cout << "ot " << "G";
6 cout << "a" << "m" << "e" << "\n";
7 cout << "\t Written " << " ";
8 cout << "B" << "y" << "\n";
9 cout << "\t\t Tom" << " " << "C" ;
10 cout << "lancy\n\n\n";
11 return 0;
12 }
3. Write a C++ program that displays six of your favourite colours name in -
a) 1 row (use comma and space to separate them)
b) 6 rows (use \n to separate them in multiple rows and use \t to separate them in each row )
c) 3 rows (use \n to separate them in multiple rows and use \t to separate them in each row )
Post-laboratory Problems 7
4. Write and run a C++ program that prints a box, an oval, an arrow and a diamond as below.
********* *** * *
* * * * *** * *
* * * * ***** * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
********* *** * *
5. Write and run a C++ program that prints the above patterns using only one cout statement.
6. Write and run a C++ program that prints the first letter of your last name as a block letter in a 7 × 7
grids of asterisks (the star symbol in your keyboard).
7. Write and run a C++ program that prints the flag of Bangladesh as below.
========================================
========================================
===============::::::===================
============::::::::::::================
===========::::::::::::::===============
==========::::::::::::::::==============
==========::::::::::::::::==============
===========::::::::::::::===============
============::::::::::::================
===============::::::===================
========================================
========================================
Laboratory 2
2.1. Objective
In this laboratory students are guided through the process of decomposing a problem into steps and
then translating those steps into working C++ code. The laboratory also exercises basic C++ programming
skills that have been introduced in the lectures. Students practice input and output operations using the
iostream objects cin and cout and also translating mathematical formulas into C++ assignment statements.
In addition, this laboratory introduce students to the variables that are used in C++ with several simple
arithmetic operations as well as mathematic functions.
Example 01
The following example of a C++ program is simply going to set a variable and print it out.
1 // prints "n = 44":
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int n;
7 n = 44;
8 cout << "n = " << n << endl;
9 }
In line 6 of the above code, you see a new statement that looks like int n;. This declares a variable named
n of type int. In C++, int means integer. As we discussed before, an integer is a data type which can only
contain non-floating point values. In other words, only whole numbers.
Then in the line 7 you see n = 44;. This is commonly known as initialization of variable. This line simply
assigns the value of 44 to n. The mailbox of the variable now has a letter that says 44. The = operator is
10 Laboratory 2. Variables, operators and type conversions
Enumeration
enum
Types
char
Character Types unsigned char
Integral Types
wchar_t
short
int
Fundamental
Types long
Integer Types
unsigned short
float
unsigned int
Floating-point
double
Types unsigned long
long double
called the assignment operator. It assigns the value of whatever is on the right to whatever is on the left.
However, this newly assigned data can later be used in our program for output in the next line.
The next line indicates - cout << "n = " << n << endl;. This line tells the computer to output the value
stored in n (which is 44 by the way) with a text n =, and then an endl (end-of-line character). It is done the
same way with most variables, simply append an extra << operator for each value you wish to attach. The
final output of this program will be as below.
n = 44
Example 02
The following example of a C++ program takes different data types as input from the user and print
those in the output.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int m, n;
2.4. Arithmetic operators 11
Example 03
1 /* Integer Arithmetic
2 Testing the operators +, -, *, /, and % */
3 # include <iostream >
4 using namespace std;
5 int main ()
6 {
7 int m=54, n=20;
8 cout << "m = " << m << " and n = " << n << endl;
9 cout << "m+n = " << m+n << endl;
10 cout << "m-n = " << m-n << endl;
11 cout << "m*n = " << m*n << endl;
12 cout << "m/n = " << m/n << endl;
13 cout << "m%n = " << m%n << endl;
14 }
Example 04
Example 05
Example 06
25 cout << "Value of ln (10) is " << log (10) << endl;
26 cout << "Value of log (10) is " << log10 (10) << endl;
27 }
Example 08
Write a program in C++ to enter length in centimeter and convert it into meter and kilometer.
Example 09
Simple interest is a quick and easy method of calculating the interest charge on a loan. It is determined
by multiplying interest rate by the principal by the number of years that elapse between payments. Write a
program in C++ to enter principle, time, rate of interest and calculate simple interest.
1 #include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int p, r, t, i;
6 cout << "Input the Principle : ";
7 cin >> p;
8 cout << "Input the Rate of Interest : ";
9 cin >> r;
10 cout << "Input the Time: ";
11 cin >> t;
12 i=(p*r*t )/100;
13 cout << "The Simple interest for the amount " << p << " for ";
14 cout << t << " years @ " << r << " % is: " << i << endl;
15 }
Example 10
At its closest point to Earth, Mars is approximately 34,000,000 miles away. Assuming there is someone
on Mars that you want to talk with, what is the delay between the time a radio signal leaves Earth and the
time it arrives on Mars? Radio signals travel at the speed of light, approximately 186,000 miles per second.
Thus, to compute the delay, you will need to divide the distance by the speed of light. Now, write and run a
C++ program to display the delay in terms of seconds and also in minutes.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 double distance , lightspeed , delay , delay_in_min ;
6 distance = 34000000.0; // 34 ,000 ,000 miles
7 lightspeed = 186000.0; // 186 ,000 per second
8 delay = distance / lightspeed ;
9 cout << "Time delay when talking to Mars: " << delay << " seconds .\n";
10 delay_in_min = delay / 60.0;
11 cout << "This is " << delay_in_min << " minutes .";
12 }
2.7. Increment and decrement 15
The values of integral objects can be incremented and decremented with the ++ and −− operators,
respectively. Each of these operators has two versions: a pre version and a post version. The pre version
performs the operation (either adding 1 or subtracting 1) on the object before the resulting value is used
in its surrounding context. On the other hand, the post version performs the operation after the object’s
current value has been used. Both the increment and decrement operators can either precede (prefix) or
follow (postfix or suffix) the operand. For example, x = x + 1; can be written either as + + x; //prefix
form or as x + +; //postfix form
In the above lines, there is no difference whether the increment is applied as a prefix or a postfix. How-
ever, when an increment or decrement is used as part of a larger expression, there is an important difference.
When an increment or decrement operator precedes its operand, C++ will perform the operation prior to
obtaining the operand value for using by the rest of the expression. If the operator follows its operand, then
C++ will obtain the operand value before incrementing or decrementing it. Consider the following lines of
code,
x = 10; y = + + x;
In this case, y will be set to 11. However, if the code is written as below,
x = 10; y = x + +;
then y will be set to 10. In both cases, x is still set to 11. The difference is – when it happens. There are
significant advantages in being able to control when the increment or decrement operation takes place.
Example 11
Example 12
Example 13
In the program, we have assigned an int data to a double variable. Here, the int value is automatically
converted to double by the compiler before it is assigned to the num_double variable. This is an example of
implicit type conversion.
Example 14
In the program, we have assigned a double data to an int variable. Here, the double value is automatically
converted to int by the compiler before it is assigned to the num_int variable. Since int cannot have a decimal
part, the digits after the decimal point are truncated in the above example.
18 Laboratory 2. Variables, operators and type conversions
As we have seen from the above example, conversion from one data type to another is prone to data loss.
This happens when data of a larger type is converted to data of a smaller type. This scenario is shown in
Figure 2.2.
data loss occurs (from higher data type to lower data type)
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGA
long
double float long int short char
double
DGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
no data loss occurs (from lower data type to higher data type)
Example 15
1 // type casting
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 double num_double = 3.56;
7 cout << " num_double = " << num_double << endl;
8 int num_int1 = (int) num_double ;
9 cout << " num_int1 = " << num_int1 << endl;
10 int num_int2 = int( num_double );
11 cout << " num_int2 = " << num_int2 << endl;
12 return 0;
13 }
Example 16
This example promotes a char to a short to an int to a float to a double:
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 char c = ’A’;
6 cout << "char c = " << c << endl;
2.10. Numeric overflow 19
7 short k = c;
8 cout << "short k = " << k << endl;
9 int m = k;
10 cout << "int m = " << m << endl;
11 long n = m;
12 cout << "long n = " << n << endl;
13 float x = n;
14 cout << "float x = " << x << endl;
15 double y = x;
16 cout << " double y = " << y << endl;
17 }
Example 17
1 // numeric overflow
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int n = 1000;
7 cout << "n = " << n << endl;
8 n *= 1000; // multiplies n by 1000
9 cout << "n = " << n << endl;
10 n *= 1000; // multiplies n by 1000
11 cout << "n = " << n << endl;
12 n *= 1000; // multiplies n by 1000
13 cout << "n = " << n << endl;
14 }
This shows that the computer that ran this program cannot multiply 1,000,000,000 by 1000 correctly.
Integer overflow wraps around to negative integers. Floating-point overflow sinks into the abstract notion
of infinity.
Post-laboratory Problems
1. Write and run a C++ program for a calculator that takes two decimal numbers from a user. It performs
the addition, subtraction, division and multiplication. It shows the results on the output screen.
20 Laboratory 2. Variables, operators and type conversions
2. Write and run a C++ program that asks the user to type the width and the length of a rectangle to calculate
the area and the perimeter of that rectangle. Then it shows the result results on the output screen.
3. Write and run a C++ program that converts centimeters to inches.
Hints: 1.0 cm = 0.393 inch.
4. Write and run a C++ program that converts any temperature from Celsius scale to Fahrenheit scale.
5
Hints: relation between Celsius and Fahrenheit is C = × (F − 32); where F is Fahrenheit and C is
9
Celsius.
5. Write and run a C++ program to calculate the hypotenuse a right triangle from the given length of two
legs.
6. Write and run a C++ program to calculate the distance between two co-ordinates (x1 , y1 ) and (x2 , y2 )
of a two dimensional graph. p
Hints: The distance between two points (x1 , y1 ) and (x2 , y2 ) is (x2 − x1 )2 + (y2 − y1 )2
7. Write and run a C++ program to find the roots of a quadratic equation. The standard form of a quadratic
equation is ax2 + bx + c = 0, where a, b, and c are real numbers and a ̸= 0 .
Hints: cout << "The equation is: "<< a << "*x*x+"<< b << "*x+"<< c << "=0"<< endl;
Laboratory 3
Selection statements
3.1. Objective
The objective of this laboratory is to ensure that students have a good understanding of the operation and
use of the selection statements, such as if, if-else, switch, conditional operators and compound conditions.
The programs in the previous two laboratories have sequential execution, i.e., each statement in the program
executes once, and they are executed in the same order that they are listed. This laboratory shows the
students how to use selection statements for more flexible programs.
The code inside the curly brackets {} is the body of the if statement.The if statement evaluates the
condition inside the parentheses (). If the condition evaluates to true, the code inside the body of if is
executed. If the condition evaluates to false, the code inside the body of if is skipped.
Example 01
The following example of a C++ program prints positive number entered by the user. If the user enters
a negative number, it is skipped.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int number ;
6 cout << "Enter an integer : ";
7 cin >> number ;
8 if ( number > 0) // checks if the number is positive
22 Laboratory 3. Selection statements
9 {
10 cout << "You entered a positive integer : " << number << endl;
11 }
12 cout << "This statement is always executed .";
13 }
When the user enters 5, the condition number > 0 is evaluated to true and the statement inside the
body of if is executed. Now if the user enters −5, the console output will be as follows.
Enter a number : -5
This statement is always executed .
When the user enters -5, the condition number > 0 is evaluated to false and the statement inside the
body of if is executed.
Example 02
The following example of a C++ program finds the minimum of three integers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int n1 , n2 , n3;
6 cout << "Enter three integers : ";
7 cin >> n1 >> n2 >> n3;
8 int min = n1; // now min <= n1
9 if (n2 < min)
10 {
11 min = n2; // now min <= n1 and min <= n2
12 }
13 if (n3 < min)
14 {
15 min = n3; // now min <= n1 , min <= n2 , and min <= n3
16 }
17 cout << "Their minimum is " << min << endl;
18 }
Example 03
The following example of a C++ program determines whether the user’s guessed number matches the
magic number.
1 # include <iostream >
2 # include <cstdlib >
3.3. The if...else statement 23
This program uses the if statement to determine whether the user’s guess matches the magic number.
If it does, the message is printed on the screen.
The if...else statement evaluates the condition inside the parenthesis. If the condition evaluates true,
— the code inside the body of if is executed
— the code inside the body of else is skipped from execution
If the condition evaluates false,
— the code inside the body of else is executed
— the code inside the body of if is skipped from execution
Example 04
The following example of a C++ program checks whether an integer is positive or negative. This pro-
gram considers 0 as a positive number.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int number ;
6 cout << "Enter an integer : ";
7 cin >> number ;
8 if ( number >= 0)
9 {
10 cout << "You entered a positive integer : " << number << endl;
11 }
24 Laboratory 3. Selection statements
12 else
13 {
14 cout << "You entered a negative integer : " << number << endl;
15 }
16 cout << "This statement is always executed .";
17 return 0;
18 }
In the above program, we have the condition number >= 0. If we enter the number greater or equal
to 0, then the condition evaluates true. Here, we enter 4. So, the condition is true. Hence, the statement
inside the body of if is executed. Now, if the user enters −4, the console output will be as follows.
Enter an integer : -4
You entered a negative integer : -4.
This statement is always executed .
Here, we enter −4. So, the condition is false. Hence, the statement inside the body of else is executed.
Example 05
The following example of a C++ program takes the magic number program further. This version uses
the else to print a message when the wrong number is picked.
1 # include <iostream >
2 # include <cstdlib >
3 using namespace std;
4 int main ()
5 {
6 int magic , guess;
7 magic = rand ();
8 cout << "Enter your guess: ";
9 cin >> guess;
10 if (guess == magic)
11 {
12 cout << "!Right Guess!" << endl;
13 }
14 else
15 {
16 cout << "Sorry! You guessed wrong." << endl;
17 }
18 }
Example 06
Example 07
Example 08
The following example of a C++ program finds the minimum of three integers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int n1 , n2 , n3;
6 cout << "Enter three integers : ";
7 cin >> n1 >> n2 >> n3;
8 if (n1 < n2)
9 {
10 if (n1 < n3)
11 {
12 cout << "The minimum is " << n1 << endl;
13 }
14 else
15 {
16 cout << "The minimum is " << n3 << endl;
17 }
18 }
19 else
20 {
21 if (n2 < n3)
22 {
23 cout << "The minimum is " << n2 << endl;
24 }
25 else
26 {
27 cout << "The minimum is " << n3 << endl;
28 }
3.5. if...else if...else statement 27
29 }
30 return 0;
31 }
Here,
— If condition1 evaluates to true, the code block 1 is executed.
— If condition1 evaluates to false, then condition2 is evaluated.
— If condition2 is true, the code block 2 is executed.
— If condition2 is false, the code block 3 is executed.
There can be more than one else if statement but only one if and else statements.
Example 09
The following example of a C++ program checks whether an integer is positive, negative or zero.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int number ;
6 cout << "Enter an integer : ";
7 cin >> number ;
8 if ( number > 0)
9 {
10 cout << "You entered a positive integer : " << number << endl;
11 }
12 else if ( number < 0)
13 {
14 cout << "You entered a negative integer : " << number << endl;
15 }
16 else
17 {
18 cout << "You entered 0." << endl;
28 Laboratory 3. Selection statements
19 }
20 cout << "This statement is always executed .";
21 return 0;
22 }
In this program, we take a number from the user. We then use the if...else if...else ladder to check whether
the number is positive, negative, or zero. If the number is greater than 0, the code inside the if block is
executed. If the number is less than 0, the code inside the else if block is executed. Otherwise, the code
inside the else block is executed.
Here, the expression is evaluated once and compared with the values of each case label.
3.6. The switch statement 29
— If there is a match, the corresponding code after the matching label is executed. For example, if the value
of the variable is equal to constant2, the code after case constant2: is executed until the break statement
is encountered.
— If there is no match, the code after default: is executed.
You can do the same thing with the if...else if..else ladder. However, the syntax of the switch statement is
cleaner and much easier to read and write.
Example 10
The following example of a C++ program checks whether a number is even or odd using switch state-
ment.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int num;
6 cout << "Enter any number to check even or odd: ";
7 cin >> num;
8 switch (num %2)
9 {
10 case 0:
11 cout << " Number is Even";
12 break;
13 case 1:
14 cout << " Number is Odd";
15 break;
16 }
17 return 0;
18 }
Example 11
The following example of a C++ program creates a basic calculator using the switch statement.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 cout << " Basic Calculator " << endl;
6 cout << " ----------------" << endl;
7 cout << " [1] Addition " << endl;
8 cout << " [2] Subtraction " << endl;
9 cout << " [3] Multiplication " << endl;
10 cout << " [4] Division " << endl;
11 float num1 , num2 , result ;
12 int choice ;
13 cout << "Enter two numbers : ";
14 cin >> num1 >> num2;
15 cout << "Enter your choice [1/2/3/4]: ";
16 cin >> choice ;
17 switch ( choice )
18 {
19 case 1:
30 Laboratory 3. Selection statements
20 result = num1+num2;
21 cout << " Summation = "<< result ;
22 break;
23 case 2:
24 result = num1 -num2;
25 cout << " Subtraction = " << result ;
26 break;
27 case 3:
28 result = num1*num2;
29 cout << " Multiplication = " << result ;
30 break;
31 case 4:
32 result = num1/num2;
33 cout << " Division = " << result ;
34 break;
35 default :
36 cout << " Invalid choice !" << endl;
37 }
38 }
In C++, the ternary operator (also known as the conditional operator) can be used to replace if...else in
certain scenarios. A ternary operator evaluates the test condition and executes a block of code based on the
result of the condition. Its syntax is as follows.
Example 12
The following example of a C++ program finds the minimum of two integers using ternary operator.
Example 13
The following example of a C++ program finds the minimum of three integers using ternary operator.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int x, y, z, result ;
6 cout << "Enter three integers : ";
7 cin >> x >> y >> z;
8 result = ((x<y) ? (x<z ? x : z) : (y<z ? y : z));
9 cout << result << " is the minimum ." << endl;
10 }
p q p&&q p q p||q
T T T T T T p !p
T F F T F T T F
F T F F T T F T
F F F F F F
Figure 3.1. Truth tables for three logical operators
Figure 3.1 shows, for example, that if p is true and q is false, then the expression p&&q will be false
and the expression p||q will be true.
Example 13
The following example of a C++ program finds the minimum of three integers using compound conditions.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int x, y, z;
6 cout << "Enter three integers : ";
7 cin >> x >> y >> z;
8 if (x <= y && x <= z)
9 {
10 cout << "Their minimum is " << x <<endl;
11 }
32 Laboratory 3. Selection statements
Post-laboratory Problems
1. Write and run a C++ program that reads the users’ age and then prints the following
a) You are a child. if the age is less than 18 years,
b) You are an adult. if the age is in between 18 years and 65 years, and
c) You are a senior citizen. if the age is more than 65 years.
2. Write and run a C++ program that reads the students’ mark and then prints the appropriate grade. Your
program must follow the grading system of AUST.
3. Write and run a C++ program to check whether a year is a leap-year or not. Leap-year is a special year
containing one extra day, i.e., total 366 days in a year. A year is said to be leap-year, if the year is exactly
divisible by 4 and not divisible by 100. Year is also a leap-year if it is exactly divisible by 400.
4. Write and run a C++ program that takes input of five integers from the keyboard and then determines
and prints the largest and the smallest integers among them. using only the ternary operator.
5. Write and run a C++ program to check whether an alphabet is vowel or consonant, using the switch
statement.
6. Write and run a C++ program to print the number of days in a month, using only the switch statement.
January, March, May, July, August, October, and December have 31 days. April, June, September, and
November have 30 days. February has 28/29 days (due to the leap-year).
7. An AC power supply of V volts is applied to a circuit load with impedance of Z(O) / with currentI. Write
a C++ program to display the real power P , the reactive power R, the apparent power S and the power
factor P F of the load. Test the program with a voltage of 120 volts and an impedance of 8 ohms at 30
degrees.
8. Write and run a C++ program to find the roots of a quadratic equation including complex solution. The
standard form of a quadratic equation is ax2 +bx+c = 0, where a, b, and c are real numbers and a ̸= 0.
A quadratic equation can have either one or two distinct real or complex roots depending upon nature
of discriminant of the equation. Where discriminant of the quadratic equation is given by ∆ = b2 −4ac.
Laboratory 4
Iteration
4.1. Objective
In this laboratory the students explore three C++ iteration constructs — while, do...while, and for state-
ments. Iteration is the repetition of a statement or block of statements in a program. Iteration statements
are also called loops because of their cyclic nature. The objective of this laboratory is to teach students how
to use and write looping constructs. In addition to that, the students will learn about the nested loops as
well as common looping problems, such as infinite loops, off-by-one loops, improper initialization of a loop
counter, and incorrect termination conditions, etc.
Here,
— A while loop evaluates the condition
— If the condition evaluates to true, the code inside the while loop is executed.
— The condition is evaluated again.
— This process continues until the condition is false.
— When the condition evaluates to false, the loop terminates.
Example 01
The following example of a C++ program prints numbers from 1 to 5.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int i = 1;
6 while (i <= 5)
7 {
8 cout << i << " ";
9 ++i;
10 }
11 return 0;
12 }
34 Laboratory 4. Iteration
Example 02
The following example of a C++ program prints sum of positive numbers only. The negative number
works as the termination key and is not added to the sum.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int number ;
6 int sum = 0;
7 cout << "Enter a number : ";
8 cin >> number ;
9 while ( number >= 0)
10 {
11 sum += number ;
12 cout << "Enter a number : ";
13 cin >> number ;
14 }
15 cout << endl << "The sum is " << sum << endl;
16 return 0;
17 }
The sum is 25
In this program, the user is prompted to enter a number, which is stored in the variable number. In
order to store the sum of the numbers, we declare a variable sum and initialize it to the value of 0. The while
loop continues until the user enters a negative number. During each iteration, the number entered by the
user is added to the sum variable. When the user enters a negative number, the loop terminates. Finally, the
total sum is displayed.
Example 03
1 1 1 1
This program computes the sum of reciprocals, i.e., sum = 1 + + + + ··· + .
2 3 4 n
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int bound , i=0;
6 cout << "Enter a positive integer : ";
7 cin >> bound;
8 double sum =0.0;
4.3. The do...while loop 35
Example 04
The following C++ program generates and prints the Fibonacci sequence up to a certain number. In math-
ematics, the Fibonacci numbers, commonly denoted Fn , form a sequence, called the Fibonacci sequence, such
that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F0 = 0, F1 = 1, and
Fn = Fn−1 + Fn−2 for n > 1. Thus the beginning of the sequence is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, . . ..
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int t1 = 0, t2 = 1, nextTerm = 0, n;
6 cout << "Enter a positive number : ";
7 cin >> n;
8 cout << " Fibonacci Series : " << t1 << ", " << t2 << ", ";
9 nextTerm = t1 + t2;
10 while ( nextTerm <= n)
11 {
12 cout << nextTerm << ", ";
13 t1 = t2;
14 t2 = nextTerm ;
15 nextTerm = t1 + t2;
16 }
17 return 0;
18 }
Here,
— The body of the loop is executed at first. Then the condition is evaluated.
36 Laboratory 4. Iteration
— If the condition evaluates to true, the body of the loop inside the do statement is executed again.
— The condition is evaluated once again.
— If the condition evaluates to true, the body of the loop inside the do statement is executed again.
— This process continues until the condition evaluates to false. Then the loop stops.
Example 05
The following example of a C++ program prints numbers from 1 to 5, same as the Example 01. However,
this example uses the do...while loop.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int i = 1;
6 do
7 {
8 cout << i << " ";
9 ++i;
10 }
11 while (i <= 5);
12 return 0;
13 }
Example 06
The following example of a C++ program takes a number from the user and then prints it in reverse
orders.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int num , digit;
6 cout << "Enter your number : ";
7 cin >> num;
8 cout << "The number in reverse order is: ";
9 do
10 {
11 digit = num %10;
12 cout << digit;
13 num /= 10;
14 }
15 while (num !=0);
16 }
Example 07
The following example of a C++ program takes a number from the user and then calculates the sum of
all of its’ digits.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int num , digit , actual_num , sum =0;
6 cout << "Enter your number : ";
7 cin >> num;
8 actual_num = num;
9 do
10 {
11 digit = num %10;
12 num /= 10;
13 sum += digit;
14 }
15 while (num !=0);
16 cout << "Sum of the all digits "
17 }
Here,
— initialization - initializes variables and is executed only once.
— condition - if true, the body of for loop is executed. Andif false, the for loop is terminated.
— update - updates the value of initialized variables and again checks the condition.
Example 08
The following example of a C++ program prints numbers from 1 to 5, same as the Example 01 and
Example 05. However, this example uses the for loop.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 for (int i = 1; i <= 5; ++i)
6 {
7 cout << i << " ";
38 Laboratory 4. Iteration
8 }
9 return 0;
10 }
Example 09
The following example of a C++ program finds the sum of first n natural numbers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int num , sum = 0;
6 cout << "Enter a positive integer : ";
7 cin >> num;
8 for (int count = 1; count <= num; ++ count)
9 {
10 sum += count;
11 }
12 cout << "Sum = " << sum << endl;
13 return 0;
14 }
Example 10
The following example of a C++ program finds the factorial of a number.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int num , factorial =1;
6 cout << "Input a number to find the factorial : ";
7 cin >> num;
8 for (int a=1; a <= num; a++)
9 {
10 factorial = factorial *a;
11 }
12 cout << "The factorial of " << num << " is " << factorial << endl;
13 }
Example 11
The following example of a C++ program calculates the sum of the series x + x2 + x3 + x4 + · · · + xn .
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int i, n, x, t, sum =0;
6 cout << "Enter the value of x: ";
7 cin >> x;
8 cout << "Enter the number of terms: ";
9 cin >> n;
10 t = x;
11 for (i=1; i<=n; i++)
12 {
13 sum +=t;
14 t*=x;
15 }
16 for (i=1; i<n; i++)
17 {
18 cout << x << "^" << i<< " + ";
19 }
20 cout << x << "^" << n << " = " << sum;
21 return 0;
22 }
Example 12
The following example of a C++ program calculates the sum of the series 1 − 23 + 33 − 43 + · · · .
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int n, j, temp , sign =1, sum =0;
6 cout << "Enter the number of terms: ";
7 cin >> n;
8 for (int i=1; i<=n; i++)
9 {
10 j = i*i*i;
11 temp = sign*j;
12 sum += temp;
13 sign = ( -1)* sign;
14 }
15 cout << "Sum = " << sum;
16 return 0;
17 }
40 Laboratory 4. Iteration
Example 13
The following example of a C++ program displays 7 days of 3 weeks
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int weeks = 3, days_in_week = 7;
6 for (int i = 1; i <= weeks; ++i)
7 {
8 cout << "Week: " << i << endl;
9 for (int j = 1; j <= days_in_week ; ++j)
10 {
11 cout << "\t Day:" << j << endl;
12 }
13 }
14 return 0;
15 }
Day :4
Day :5
Day :6
Day :7
Example 14
The following example of a C++ program displays a pattern with 5 rows and 3 columns.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int rows = 5, columns = 3;
6 for (int i = 1; i <= rows; ++i)
7 {
8 for (int j = 1; j <= columns ; ++j)
9 {
10 cout << "* \t";
11 }
12 cout << endl;
13 }
14 return 0;
15 }
Example 15
The following example of a C++ program displays a pattern of half pyramid with numerics.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int i=0, j=0;
6 for (i=5; i >=1; i--)
7 {
8 for (j=1; j<=i; j++)
9 {
10 cout << j << "\t" ;
11 }
12 cout << endl;
13 }
14 return 0;
15 }
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Example 16
The following example of a C++ program displays a pattern of inverted full pyramid.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int rows;
6 cout << "Enter number of rows: ";
7 cin >> rows;
8 for (int i = rows; i >= 1; --i)
9 {
10 for (int space = 0; space < rows -i; ++ space)
11 {
12 cout << " ";
13 }
14 for(int j = i; j <= 2*i -1; ++j) j=1
15 {
16 cout << "* ";
17 }
18 for (int j = 0; j < i -1; ++j)
19 {
20 cout << "* ";
21 }
22 cout << endl;
23 }
24 }
In the above programs, the condition is always true which will then run the code for infinite times. That
means, a loop becomes infinite loop if a condition never becomes false.
Example 17
The following example of a C++ program shows the example of infinite loop.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 for( ; ; )
6 {
7 cout <<"This loop will run forever ." << endl;
8 }
9 return 0;
10 }
In the above program, since none of the three expressions that form the for loop are required, you can
make an infinite loop by leaving the conditional expression empty. When the conditional expression is
absent, it is assumed to be true. You can terminate an infinite loop by pressing Ctrl + C keys.
Post-laboratory Problems
1. Write and run a C++ program to test a number if it is prime number or not. Use the while loop.
2. Write and run a C++ program to find the sum = 1 + 32 + 52 + ... + n2 . Use the while loop.
3. Write and run a C++ program to find the Fibonacci sequence using the do...while loop.
4. Write and run a C++ program to find the factorial of a given number using the do...while loop.
5. Write and run a C++ program to find the sum of the even numbers using the do..while loop.
6. Write and run a C++ program to calculate sum of numbers until a negative number is entered. Use the
for loop.
7. Write and run a C++ program to find the sum and average of all the digits of a given number using the
for loop.
8. Write and run a C++ program to find the sum = 1 − 32 + 52 − .... using the for loop.
9. Write and run a C++ program to find the sum = 1 + 22 + 44 + .... using the for loop.
Laboratory 5
Function
5.1. Objective
In this laboratory, students begin an in-depth exploration of function invocation. The focus of this
laboratory is the parameter passing mechanisms. With the help of the function, students explore value and
reference parameter-passing mechanisms. The objective of the laboratory is to introduce the students to the
function, both in-built and user defined. In addition to that, students will have a strong understanding of
parameter passing mechanisms.
5.2. Function
Most computer programs that solve real-world problems are much larger than the programs presented
in the first laboratory. Experience has shown that the best way to develop and maintain a large program is
to construct it from smaller modules, each of which is more manageable than the original program. Besides
dividing a complex problem into smaller modules makes any program easy to understand and reusable.
Each of these modules is a small block of code that performs a specific task. These modules in C++ are
called functions.
There are two types of function:
1. Standard library functions: these functions are redefined in C++
2. User-defined function: these functions are created by users
Example 01
The following example of a C++ program finds the square root of a number.
1 # include <iostream >
2 # include <cmath >
3 using namespace std;
4 int main ()
5 {
6 double number , squareRoot ;
7 number = 25.0;
8 squareRoot = sqrt( number );
46 Laboratory 5. Function
9 cout << " Square root of " << number << " = " << squareRoot ;
10 return 0;
11 }
In this program, the sqrt() library function is used to calculate the square root of a number. The function
declaration of sqrt() is defined in the cmath header file. That’s why we need to use the code #include <cmath>
to use the sqrt() function.
Example 01
The following example of a C++ program shows function prototyping.
1 # include <iostream >
2 using namespace std;
3
4 int max (int x, int y);
5
6 int main ()
7 {
8 int m, n;
9 cout << "Enter two integers : ";
10 cin >> m >> n;
11 cout << max(m,n) << " is the maximum ." << endl;
12 }
13
14 int max (int x, int y)
15 {
16 if (x < y)
17 return y;
18 else
19 return x;
20 }
In the above code, the function prototype is in the line 3, i.e., int max (int x, int y);
This provides the compiler with information about the function name and its parameters. That’s why
we can use the code to call a function before the function has been defined.
Example 02
The following example of C++ program prints all the factorial values for the numbers 1 to 6.
1 # include <iostream >
2 using namespace std;
3
4 long fact (int );
5
6 int main ()
7 {
48 Laboratory 5. Function
Example 03
The following example of C++ program takes the numeric values for day, month, and year, and then
prints in a formal fashion.
1 # include <iostream >
2 using namespace std;
3
4 void print_date (int , int , int );
5
6 int main ()
7 {
8 int month , day , year;
9 do
10 {
11 cout << "Enter the date: ";
12 cin >> day;
13 cout << "Enter the month: ";
14 cin >> month;
15 cout << "Enter the year: ";
16 cin >> year;
17 print_date (month , day , year );
18 }
19 while (month > 0);
20 }
5.6. Boolean functions 49
21
22 void print_date (int m, int d, int y)
23 {
24 if (m < 1 || m > 12 || d < 1 || d > 31 || y < 0)
25 {
26 cout << "Error: parameter out of range." << endl;
27 return ;
28 }
29 cout << "The date is: ";
30 switch (m)
31 {
32 case 1: cout << " January "; break;
33 case 2: cout << " February "; break;
34 case 3: cout << "March "; break;
35 case 4: cout << "April "; break;
36 case 5: cout << "May "; break ;
37 case 6: cout << "June "; break ;
38 case 7: cout << "July "; break ;
39 case 8: cout << " August "; break;
40 case 9: cout << " September "; break;
41 case 10: cout << " October "; break;
42 case 11: cout << " November "; break;
43 case 12: cout << " December "; break;
44 }
45 cout << d << ", " << y << endl;
46 }
Example 04
The following example of C++ program prints all the prime numbers up to 80.
1 # include <iostream >
2 # include <cmath >
3 using namespace std;
4
5 bool is_prime (int );
6
7 int main ()
8 {
50 Laboratory 5. Function
Example 05
The following example of C++ program checks whether the given year is a leap-year.
1 # include <iostream >
2 using namespace std;
3
4 bool is_leap_year (int );
5
6 int main ()
7 {
8 int year;
9 do
10 {
11 cout << "Enter a year: ";
12 cin >> year;
13 if ( is_leap_year (year ))
14 cout << year << " is a leap year." << endl;
15 else
16 cout << year << " is not a leap year." << endl;
17 } while (year > 1);
18 }
19
20 bool is_leap_year (int y)
21 {
22 return (y%4==0 && y %100!=0 || y %400==0);
5.7. Passing arguments by value and by reference 51
23 }
Example 06
This example shows the difference between passing-by-value and passing-by-reference.
1 # include <iostream >
2 using namespace std;
3
4 void dummy (int , int &);
5
6 int main ()
7 {
8 int a = 22, b = 44;
9 cout << "a = " << a << ", b = " << b << endl;
10 dummy (a, b);
11 cout << "a = " << a << ", b = " << b << endl;
12 dummy (2*a-3, b);
13 cout << "a = " << a << ", b = " << b << endl;
14 }
15
16 void dummy (int x, int& y)
17 {
18 x = 88;
19 y = 99;
20 }
The call dummy(a, b) passes a by value to x and it passes b by reference to y. Therefore, x is a local
variable that is assigned a’s value of 22, while y is an alias for the variable b whose value is 33. The function
assigns 88 to x, but that has no effect on a. But when it assigns 99 to y, it is really assigning 99 to b, because
y is an alias for b. Therefore, when the function terminates, a still has its original value 22, while b has the
new value 99. The argument a is read-only, while the argument b is read-write.
Example 07
This example shows the function overloading in C++.
1 # include <iostream >
2 using namespace std;
3
4 int max (int , int );
5 int max (int , int , int );
6 float max (float , float );
7 float max (float , float , float );
8
9 int main ()
10 { int p, q, r;
11 float x, y, z;
12 cout << " Enter three integers : ";
13 cin >> p >> q >> r;
14 cout << " Enter three floating point numbers : ";
15 cin >> x >> y >> z;
16 cout << " Maximum of the first two integers is: " << max(p, q) << endl;
17 cout << " Maximum of the three integers is: " << max(p, q, r) << endl;
18 cout << " Maximum of the first two floating numbers is: " << max(x, y) << endl;
19 cout << " Maximum of the three floating numbers is: " << max(x, y, z) << endl;
20 }
21
22 int max (int x, int y)
23 {
24 return (x > y ? x : y);
25 }
26
27 int max (int x, int y, int z)
28 {
29 int m = (x > y ? x : y);
30 return (z > m ? z : m);
31 }
32
33 float max ( float x, float y)
34 {
35 return (x > y ? x : y);
36 }
37
38 float max ( float x, float y, float z)
39 {
40 float m = (x > y ? x : y);
5.9. Default arguments (parameters) 53
Example 08
The following dummy() function evaluates the third degree polynomial a0 + a1 x + a2 x2 + a3 x3 . The
actual evaluation is done using Horner’s Algorithm, grouping the calculations as a0 + (a1 + (a2 + a3 x)x)x
for greater efficiency.
1 # include <iostream >
2 using namespace std;
3
4 double dummy (double , double , double =0, double =0, double =0);
5
6 int main ()
7 {
8 double x, a0 , a1 , a2 , a3;
9 cout << "Enter the value of x: " ;
10 cin >> x;
11 cout << "Enter the value of a0 , a1 , a2 , and a3: ";
12 cin >> a0 >> a1 >> a2 >> a3;
13 cout << " Considering x and a0 , the result is: ";
14 cout << dummy (x, a0) << endl;
15 cout << " Considering x, a0 , and a1 , the result is: ";
16 cout << dummy (x, a0 , a1) << endl;
17 cout << " Considering x, a0 , a1 , and a2 , the result is: ";
18 cout << dummy (x, a0 , a1 , a2) << endl;
19 cout << " Considering x, a0 , a1 , a2 , and a3 , the result is: "
20 cout << dummy (x, a0 , a1 , a2 , a3) << endl;
21 }
22
23 double dummy ( double x, double a0 , double a1 , double a2 , double a3)
24 {
25 return (a0+(a1 +(a2+a3*x)*x)*x);
26 }
Post-laboratory Problems
1. Write and run a C++ program to test the following average() function that returns the average of four
numbers.
float average (float x1 , float x2 , float x3 , float x4);
2. Write and run a C++ program to test the following min() function that returns the smallest of four given
integers.
int min (int , int , int , int );
3. Write and run a C++ program to test the following is_square() function that determines whether the
given integer is a square number.
int is_square (int n);
Hints: The first ten square numbers are 0, 1, 4, 9, 16, 25, 36, 49, 64, and 81.
4. Write and run a C++ program to test the following compute_sphere() function that returns the volume
v and the surface area s of a sphere with given radius r.
void compute_sphere (float& v, float& s, float r);
5. Write and run a C++ program to find the solution for a polynomial of a given maximum degree of 5, i.e.,
c5 x5 + c4 x4 + c3 x3 + c2 x2 + c1 x + c0 for arbitrary values of the coefficients c5 , c4 , c3 , c2 , c1 , and c0 .
The formula for evaluating the polynomial at a given value of x is result = ((((c5 ∗ x + c4 ) ∗ x + c3 ) ∗
x + c2 ) ∗ x + c1 ) ∗ x + c0 . The program must invoke at least two functions to
a) prompt for and read the values of the coefficients.
b) calculate the result of the polynomial
6. Write and run a C++ program to test the following power() function that returns x raised to the power
n, where n can be any integer.
double power ( double x, int p);
Hints: Use the algorithm that would compute x20 by multiplying 1 by x for 20 times.
7. Write and run a C++ program to find the sum of the following series invoking function.
x x2 x3
a) sum = 1 + + + + ···
1! 2! 3!
2 4 6
x x x
b) sum = 1 + + + + ···
2! 4! 6!
Laboratory 6
Arrays
6.1. Objective
This laboratory develops the ability to use and manipulate arrays. This laboratory also introduces the
activity of searching a list for a key value by examining, modifying, and running programs that use sort as
well as search techniques. The student performs an experiment that measures the efficiency of these search
techniques.
6.2. Arrays
In C++, an array is a variable that can store multiple values of the same type. For example, suppose a
class has 27 students, and we need to store the grades of all of them. Instead of creating 27 separate variables,
we can simply create an array that can hold a maximum of 27 elements of same type data.
Arrays occupy space in memory. You specify the type of each element and the number of elements
each array requires so that the computer may reserve the appropriate amount of memory. The following
definition reserves 10 elements for integer array x.
int x [10];
Here,
— int - type of element to be stored
— x - name of the array
— 10 - size of the array
In C++, the size and type of arrays cannot be changed after its declaration.
First index
0 1 2 3 4 5 6 7 8 9 Array indices
x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] x[8] x[9] Array elements
For example, consider the array x we have seen above. Figure 6.1 shows the integer array called x,
containing 10 elements. Any one of these elements may be referred to by giving the array’s name followed
by the position number (or index) of the particular element in square brackets. The position number (or
index) within square brackets is called a subscript. A subscript must be an integer or an integer expression.
The first element of every array is in the zeroth index. An array name, like other variable names, can contain
only letters, digits and underscores and cannot begin with a digit. Here, the array’s name is x. Its’ 10 elements
are referred to as x[0], x[1], x[2], ..., x[8] and x[9]. The value stored in x[0] is −45, the value of x[1] is 36,
x[2] is 6, x[7] is 1 and x[9] is 25 .
Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the
size.
Example 01
The following example of a C++ program displays array elements.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int numbers [5] = {7, 5, 6, 12, 35};
6 cout << "The numbers are: ";
7 for (int i = 0; i < 5; ++i)
8 {
9 cout << numbers [i] << " ";
10 }
11 return 0;
12 }
Here, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we have printed
numbers[i].
Example 02
The following example of a C++ program takes inputs from user and store them in an array. Then it
prints the stored values.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int numbers [5];
6 cout << "Enter 5 numbers : ";
7 for (int i = 0; i < 5; ++i)
8 {
9 cin >> numbers [i];
10 }
11 cout << "The numbers are: ";
12 for (int n = 0; n < 5; ++n)
13 {
14 cout << numbers [n] << " ";
15 }
16 return 0;
17 }
Example 03
The following example of a C++ program displays largest element of an array.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int i, n;
6 float arr [100];
7 cout << "Enter total number of elements (1 to 100): ";
8 cin >> n;
9 cout << endl;
10 for (i = 0; i < n; ++i)
11 {
12 cout << "Enter Number " << i + 1 << " : ";
13 cin >> arr[i];
14 }
15 for (i = 1;i < n; ++i)
16 {
17 if (arr [0] < arr[i]) arr [0] = arr[i];
18 }
58 Laboratory 6. Arrays
Enter Number 1 : 17
Enter Number 2 : 29
Enter Number 3 : 42
Enter Number 4 : 36
Enter Number 5 : 66
Largest element = 66
For an example, if we pass an int type array named marks to the function total(), and the size of the
array is 5, then we can express it as follows.
int total (int marks [5])
{
// function body
}
Example 04
The following example of a C++ program display marks of 5 students.
1 # include <iostream >
2 using namespace std;
3
4 void display (int m[5]);
5
6 int main ()
7 {
8 int marks [5] = {88, 76, 90, 61, 69};
9 display (marks );
10 return 0;
11 }
12
13 void display (int m[5])
14 {
15 cout << " Displaying marks: " << endl;
6.3. Passing array to function 59
Example 05
The following example of a C++ program searches any element or number in an array.
1 # include <iostream >
2 using namespace std;
3
4 int input [100];
5
6 void read (int count );
7 void search (int num , int count );
8
9 int main ()
10 {
11 int count , num;
12 cout << "Enter the number of elements in array: ";
13 cin >> count;
14 cout << "Enter " << count << " numbers : ";
15 read ( count );
16 cout << "Enter a number to search in the array: ";
17 cin >> num;
18 search (num , count );
19 return 0;
20 }
21
22 void read (int count)
23 {
24 for (int i = 0; i < count; i++)
25 {
26 cin >> input[i];
27 }
28 }
29
30 void search (int num , int count)
60 Laboratory 6. Arrays
31 {
32 int i;
33 for (i = 0; i < count; i++)
34 {
35 if (input[i] == num)
36 {
37 cout << " Element is found at index " << i << "." << endl;
38 break;
39 }
40 }
41 if (i == count)
42 {
43 cout << " Element is not present in the array." << endl;
44 }
45 }
Example 06
The following example of a C++ program utilizes the bubble sort algorithm.
1 # include <iostream >
6.4. Multidimensional arrays 61
0 34 89 -46 2 39 87 71 31 28 91
2 -12 98 0 10 -56 87 54 15 86 28
Figure 6.2 illustrates a 2-dimensional array, x. The array contains three rows and 10 columns, so it is
said to be a 3-by-10 array. In general, an array with m rows and n columns is called an m-by-n array. Every
element in array x is identified in Figure 6.2 by an element name of the form x[i][j]; where, x is the name
of the array, and i and j are the subscripts (rows and columns respectively in this case) that uniquely identify
each element in x.
Here,
— data_type: Type of data to be stored in the array.
— array_name: Name of the array
— size1, size2, ... , sizeN: Sizes of the dimensions
According to the above syntax, we can declare the two dimensional array of Figure 6.2 as follows.
int x [3][10];
The above array has 2 rows and 3 columns, which is why we have 2 rows of elements with 3 elements
each. Same way we can initialize a three-dimensional array.
int test [2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
Notice the dimensions of the above three-dimensional array. The first dimension has the value 2. So,
the two elements comprising the first dimension are,
Element -1 is {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}} and
Element -2 is {{13 , 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9}}
The second dimension has the value 3. Notice that each of the elements of the first dimension has three
elements each,
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element -1.
{13 , 4, 56, 3}, {5, 9, 3, 5} and {5, 1, 4, 9} for Element -2.
Finally, the third dimension has the value 4. And there are four int numbers inside each of the elements
of the second dimension,
{3, 4, 2, 3}
{0, -3, 9, 11}
... ... ... ...
... ... ... ...
Example 07
The following example of a C++ program shows how a two-dimensional array can be processed
1 # include <iostream >
2 using namespace std;
3
4 void read (int a [][5]);
5 void print (int a [][5]);
6
7 int main ()
8 {
9 int a [3][5];
10 read(a);
11 print (a);
12 }
13
14 void read (int a [][5])
15 {
16 cout << "Enter 15 integers (5 per row ): " << endl;
17 for (int i=0; i <3; i++)
18 {
19 cout << "Row " << i << ": ";
20 for (int j=0; j <5; j++)
21 {
22 cin >> a[i][j];
23 }
64 Laboratory 6. Arrays
24 }
25 }
26
27 void print (int a [][5])
28 {
29 cout << "You have entered the following integers : " << endl;
30 for (int i=0; i <3; i++)
31 {
32 for (int j=0; j <5; j++)
33 {
34 cout << " " << a[i][j];
35 }
36 cout << endl;
37 }
38 }
Example 08
The following example of a C++ program finds transpose of a matrix.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int a[10][10] , transpose [10][10] , row , column , i, j;
6 cout << "Enter rows and columns of matrix : ";
7 cin >> row >> column ;
8 cout << "Enter elements of matrix : " << endl;
9 for (int i = 0; i < row; ++i)
10 {
11 for (int j = 0; j < column ; ++j)
12 {
13 cout << "Enter element a" << i + 1 << j + 1 << ": ";
14 cin >> a[i][j];
15 }
16 }
17 cout << endl << " Entered Matrix : " << endl;
18 for (int i = 0; i < row; ++i)
19 {
20 for (int j = 0; j < column ; ++j)
21 {
22 cout << " " << a[i][j];
23 if (j == column - 1)
6.4. Multidimensional arrays 65
Entered Matrix :
1 3 4 2
5 7 9 6
8 0 3 1
Transpose of Matrix :
1 5 8
3 7 0
4 9 3
2 6 1
Example 09
The following example of a C++ program finds the number of zeros in a three-dimensional array.
66 Laboratory 6. Arrays
Post-laboratory Problems
1. Write and run a C++ program to test the following function that returns the minimum value among the
first n elements.
float min (float a[], int n);
2. Write and run a C++ program to find the largest three elements in an array.
3. Write and run a C++ program to find the most occurring element in an array of integers.
4. Write and run a C++ program to separate even and odd numbers of an array of integers. Put all the even
numbers first, and then all the odd numbers.
5. Write and run a C++ program to find the first repeating element in an array of integers.
6. Write and run a C++ program to sort the elements of an array from the maximum to the minimum value.
7. Write and run a C++ program that will multiply two matrices of any columns and row, if it passes the
test for the conditions of matrix multiplication.
8. Write and run a C++ program to test the following function
Post-laboratory Problems 67
Hints: The function returns the standard deviation of a data set of N numbers, i.e., x0 , x1 , . . . , xN −1 defined
by the following formula
v
u N −1
u P 2
(x − x)
t i=0 i
u
σ=
N −1
Laboratory 7
Pointers
7.1. Objective
This laboratory focuses on the memory concept of variables, pointers and how to use variable identifiers
and pointers to refer to the variable. Students will learn the pointer variable declarations and initialization,
direct and indirect referencing a variable using the pointer operators using the de-reference (∗) and ad-
dress (&) operators. In addition, students will develop knowledge on passing and returning pointer from
functions as well as use of pointers with functions.
7.2. Pointers
In C++, pointers are variables that store the memory addresses of other variables. In other words, a
pointer is an object that contains a memory address. Very often this address is the location of another object
(e.g., a variable). For example, if x contains the address of y, then x is said to point to y.
This would assign the address of variable dhaka to khulna. Here, by preceding the name of the variable
dhaka with the address-of operator (&), the address of dhaka is assigned to khulna, instead of the content.
The actual address of a variable in memory cannot be known before runtime, but let’s assume, in order
to help clarify some concepts, that dhaka is placed during runtime in the memory address 20022. In this
case, consider the following code fragment,
dhaka = 19;
khulna = & dhaka;
sylhet = dhaka;
The values contained in each variable after the execution of the above code fragment are shown in the
Figure 7.1.
— In the first statement, we have assigned the value 19 to dhaka (a variable whose address in memory we
assumed to be 20022).
— The second statement assigns khulna the address of dhaka, which we have assumed to be 20022.
— Finally, the third statement, assigns the value contained in dhaka to sylhet. This is a standard assignment
operation, as already done many times in earlier laboratories.
The main difference between the second and third statements is the address-of operator (&).
Thus we can say that, variable that stores the address of another variable (e.g., khulna in the above case)
is called a pointer in C++.
70 Laboratory 7. Pointers
19 20022
sylhet khulna
An interesting property of pointers is that they can be used to access the variable they point to directly.
This is done by preceding the pointer name with the dereference operator (∗). The operator itself can be read
as value pointed to by.
To elaborate the idea of the deference operator, we extend the previous example with the following
statement,
bbaria = * khulna ;
The above statement assigns the value 19 to bbaria, since khulna is 20022, and the value pointed to by
20022 (following the example of the address-of operator) is 19. The whole process is shown in the Figure
7.2. It is important to understand that khulna refers to the value 20022, while *khulna (with an asterisk *
preceding the identifer) refers to the value stored at address 20022, which in this case is 19.
khulna
20022
20021 20022 20023 (memory)
... ... ... 19 ... ... ...
19
bbaria
data_type * pointer_name ;
Here, data_type is the type of data pointed to by the pointer. This type is not the type of the pointer
itself, but the type of the data the pointer points to. And pointer_name is the name of the pointer variable.
7.2. Pointers 71
Example 01
The following example of a C++ program demonstrates the C++ pointers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int var = 5, * point_var ;
6 point_var = &var;
7 cout << "var = " << var << endl;
8 cout << "&var = " << &var << endl;
9 cout << " pointVar = " << point_var << endl;
10 cout << "* pointVar = " << * point_var << endl;
11 return 0;
12 }
Example 02
The following example of a C++ program demonstrates to change the value pointed by pointers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int var = 5, * point_var ;
6 point_var = &var;
7 cout << "var = " << var << endl;
8 cout << "* point_var = " << * point_var << endl << endl;
9 cout << " Changing value of var to 7:" << endl;
10 var = 7;
11 cout << "var = " << var << endl;
12 cout << "* point_var = " << * point_var << endl << endl;
13 cout << " Changing value of * point_var to 16:" << endl;
14 * point_var = 16;
15 cout << "var = " << var << endl;
16 cout << "* point_var = " << * point_var << endl;
17 return 0;
18 }
Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the
first element of the array in variable ptr. Notice that we have used arr instead of &arr[0]. This is because
both are the same. So, the code below is the same as the code above.
int *ptr;
int arr [5];
ptr = &arr [0];
The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3], and &arr[4].
Example 03
The following example of a C++ program demonstrates the relation between arrays and pointers.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 int numbers [5];
6 int *p;
7 p = numbers ;
8 *p = 10;
9 p++;
10 *p = 20;
11 p = & numbers [2];
12 *p = 30;
13 p = numbers +3;
14 *p = 40;
15 p = numbers ;
16 *(p+4) = 50;
17 cout << "The numbers are: ";
18 for (int n=0; n <5; n++)
19 {
20 cout << numbers [n] << " ";
21 }
22 return 0;
23 }
7.3. Pointers and arrays 73
Example 04
The following example of a C++ program shows an array used as pointer.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 float arr [5];
6 cout << "Enter 5 numbers : ";
7 for (int i = 0; i < 5; ++i)
8 {
9 cin >> *( arr + i) ;
10 }
11 cout << " Displaying data: " << endl;
12 for (int i = 0; i < 5; ++i)
13 {
14 cout << *( arr + i) << endl ;
15 }
16 return 0;
17 }
Here, pointer_variable is the name of the pointer variable, new is a keyword to create a dynamic array,
and data_type must be a valid C++ data type. The keyword then returns a pointer to the first item. After
creating the dynamic array, we can delete it using the delete keyword.
Example 05
The following example of a C++ program demonstrates the creation as well as deletion of a dynamic
array.
74 Laboratory 7. Pointers
Example 06
The following example of a C++ program demonstrates pointers to functions.
1 # include <iostream >
2 using namespace std;
3
4 int addition (int a, int b);
5 int subtraction (int a, int b);
6 int operation (int x, int y, int (* functocall )(int ,int ));
7
8 int main ()
9 {
7.4. Pointers to functions 75
10 int m,n;
11 int (* minus )(int ,int) = subtraction ;
12 m = operation (6, 7, addition );
13 n = operation (30, m, minus );
14 cout << "The result is: " << n;
15 return 0;
16 }
17
18 int addition (int a, int b)
19 {
20 return (a+b);
21 }
22
23 int subtraction (int a, int b)
24 {
25 return (a-b);
26 }
27
28 int operation (int x, int y, int (* functocall )(int ,int ))
29 {
30 int g;
31 g = (* functocall )(x,y);
32 return (g);
33 }
Example 07
The following example of a C++ program demonstrates the passing by reference using pointers.
1 # include <iostream >
2 using namespace std;
3
4 void swap(int*, int *);
5
6 int main ()
7 {
8 int a = 10, b = 20;
9 cout << " Before swapping " << endl;
10 cout << "a = " << a << endl;
11 cout << "b = " << b << endl;
12 swap (&a, &b);
13 cout << endl << "After swapping " << endl;
14 cout << "a = " << a << endl;
15 cout << "b = " << b << endl;
16 return 0;
17 }
18
19 void swap (int* n1 , int* n2)
20 {
21 int temp;
76 Laboratory 7. Pointers
22 temp = *n1;
23 *n1 = *n2;
24 *n2 = temp;
25 }
After swapping
a = 20
b = 10
Post-laboratory Problems
1. Write and run a C++ program to test the following function that returns the sum of the floats pointed
to by the first n pointers in the array p.
float sum(float* p[], int n);
2. Write and run a C++ program that use pointers to swap four integer values.
3. Modify the program of Example 05 so that, it takes and prints values using the following two functions
respectively.
void get( double *&a, int& n);
void print( double *a, int n);
4. Following is a function for the (indirect) Bubble Sort. Here, on each iteration of the inner loop, if the
floats of adjacent pointers are out of order, then the pointers are swapped.
void sort(float* p[], int n)
{
float* temp;
for (int i = 1; i < n; i++)
for (int j = 0; j < n-i; j++)
if (*p[j] > *p[j+1])
{
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
Strings
8.1. Objective
This laboratory focuses on the concept of C-strings as well as the Standard C++ strings. Students will
learn to apply the useful functions defined in the header files for C-strings and Standard C++ strings. In
addition, students will develop knowledge on applying the concept of strings.
8.2. C-strings
A C-string (also called a character string) is a sequence of contiguous characters in memory terminated
by the NULL character ‘\0’. For example:
char c[] = "AUST EEE";
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it ap-
pends a null character ‘\0’ at the end by default.
0 1 2 3 4 5 6 7 8
A U S T E E E \0
C-strings are accessed by variables of type char* (pointer to char). For an example, if s has type char*,
then, cout << s << endl; will print the characters stored in the memory beginning at the address s and ending
with the first occurrence of NULL charater.
Example 01
The following example of a C++ program demonstrates the basic idea of the NULL character in strings.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 char str []="AUST";
6 for (int i = 0; i < 5; i++)
7 {
8 cout << "s[" << i << "] = " << str[i] << endl;
9 }
78 Laboratory 8. Strings
10 }
Example 02
The following example of a C++ program demonstrates the ways of initialization of C-string with string
literal.
1 # include <iostream >
2 using namespace std;
3 int main ()
4 {
5 char a[]= "Dhaka" ;
6 cout << "The default string is: " << a << endl;
7 int max_length = 7;
8 char b[ max_length ];
9 cout << "Enter a string not more than " << max_length << " characters : ";
10 cin. getline (b, max_length );
11 cout << "You entered : " << b << endl;
12 }
In line 5 of the above code, the C-string is initialize with a string literal. However, in line 10, we use the
cin.getline( ) function with two parameters. The call cin.getline(str, n) reads up to n characters into str and
ignores the rest. That is why, we got the output Bangla instead of Bangladesh.
Example 03
The following example of a C++ program demonstrates the strlen( ) function.
The strlen( ) function takes a string as an argument and returns its length (i.e., number of characters in
the string that precede the first occurrence of the NULL character). The returned value is of type size_t (the
unsigned integer type).
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char a[20] = " AUSTEEE ";
7 char b[20] = {’A’,’U’,’S’,’T’,’E’,’E’,’E’,’\0’};
8.2. C-strings 79
8 cout << " Length of string a: " << strlen (a) << endl;
9 cout << " Length of string b: " << strlen (b) << endl;
10 char buffer [80];
11 cout << "Enter string : ";
12 cin >> buffer ;
13 cout << " Length of the entered string : " << strlen ( buffer ) << endl;
14 }
Example 04
The following example of a C++ program demonstrates the strcpy( ) function.
The strcpy( ) function copies the string pointed by source (including the NULL character) to the desti-
nation. The strcpy( ) function also returns the copied string.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char S1[] = " ABCDEFGH ";
7 char S2[] = "xyz";
8 cout << " Before strcpy (S1 , S2)" << endl;
9 cout << " Content of S1: " << S1 << endl;
10 cout << " Length of S1: " << strlen (S1) << endl;
11 cout << " Content of S2: " << S2 << endl;
12 cout << " Length of S2: " << strlen (S2) << endl << endl;
13 strcpy (S1 , S2);
14 cout << "After strcpy (S1 , S2)" << endl;
15 cout << " Content of S1: " << S1 << endl;
16 cout << " Length of S1: " << strlen (S1) << endl;
17 cout << " Content of S2: " << S2 << endl;
18 cout << " Length of S2: " << strlen (S2) << endl;
19 }
The effect of strcpy(S1, S2) can be visualized as shown in Figure 8.2. Since S2 has a length of 3, strcpy(S1,
S2) copies 4 bytes (including the NULL character), overwriting the first 4 characters of S1. This changes the
length of S1 to 3.
S1 S2
A B C D E F G H \0 x y z \0
strcpy(S1,S2)
x y z \0 E F G H \0 x y z \0
S1 S2
Example 05
The following example of a C++ program demonstrates the strncpy( ) function.
The strncpy( ) function copies first n characters from the string pointed by source to the destination.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char S1[] = " ABCDEFGH ";
7 char S2[] = "xyz";
8 int n = 2;
9 cout << " Before strncpy (S1 , S2 , n)" << endl;
10 cout << " Content of S1: " << S1 << endl;
11 cout << " Length of S1: " << strlen (S1) << endl;
12 cout << " Content of S2: " << S2 << endl;
13 cout << " Length of S2: " << strlen (S2) << endl << endl;
14 strncpy (S1 , S2 , n);
15 cout << "After strncpy (S1 , S2 , n)" << endl;
16 cout << " Content of S1: " << S1 << endl;
17 cout << " Length of S1: " << strlen (S1) << endl;
18 cout << " Content of S2: " << S2 << endl;
19 cout << " Length of S2: " << strlen (S2) << endl;
20 }
Length of S1: 8
Content of S2: xyz
Length of S2: 3
The effect of strncpy(S1, S2, n) can be visualized as shown in Figure 8.3. Since n is 2 and S2 has a length
of 3, strncpy(S1, S2, n) copies 2 bytes (excluding the NULL character), overwriting the first 2 characters of
S1. This has no effect upon the length of S1 which is 8.
S1 S2
A B C D E F G H \0 x y z \0
strncpy(S1,S2,2)
x y C D E F G H \0 x y z \0
S1 S2
Example 06
The following example of a C++ program demonstrates the strcat( ) function.
The strcat( ) function contcatenates (joins) two strings. This function concatenates the destination string
and the source string, and the result is stored in the destination string.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char S1[] = " ABCDEFGH ";
7 char S2[] = "xyz";
8 cout << " Before strcat (S1 , S2)" << endl;
9 cout << " Content of S1: " << S1 << endl;
10 cout << " Length of S1: " << strlen (S1) << endl;
11 cout << " Content of S2: " << S2 << endl;
12 cout << " Length of S2: " << strlen (S2) << endl << endl;
13 strcat (S1 , S2);
14 cout << "After strcat (S1 , S2)" << endl;
15 cout << " Content of S1: " << S1 << endl;
16 cout << " Length of S1: " << strlen (S1) << endl;
17 cout << " Content of S2: " << S2 << endl;
18 cout << " Length of S2: " << strlen (S2) << endl;
19 }
Length of S2: 3
The effect of strcat(S1, S2) can be visualized as shown in Figure 8.4. Since S2 has length 3, strcat(S1, S2)
copies 4 bytes (including the NULL character), overwriting the NULL characters of S1 and its following 3
bytes. The length of S1 is increased to 11.
S1 S2
A B C D E F G H \0 x y z \0
strcat(S1,S2)
A B C D E F G H x y z \0 x y z \0
S1 S2
Example 07
The following example of a C++ program demonstrates the strncat( ) function.
This function appends not more than n characters from the string pointed to by source to the end of
the string pointed to by destination plus a terminating NULL character. The initial character of the source
string overwrites the NULL character present at the end of destination string.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char S1[] = " ABCDEFGH ";
7 char S2[] = "xyz";
8 int n = 2;
9 cout << " Before strncat (S1 , S2 , n)" << endl;
10 cout << " Content of S1: " << S1 << endl;
11 cout << " Length of S1: " << strlen (S1) << endl;
12 cout << " Content of S2: " << S2 << endl;
13 cout << " Length of S2: " << strlen (S2) << endl << endl;
14 strncat (S1 , S2 , n);
15 cout << "After strncat (S1 , S2 , n)" << endl;
16 cout << " Content of S1: " << S1 << endl;
17 cout << " Length of S1: " << strlen (S1) << endl;
18 cout << " Content of S2: " << S2 << endl;
19 cout << " Length of S2: " << strlen (S2) << endl;
20 }
8.2. C-strings 83
The effect of strcat(S1, S2) can be visualized as shown in Figure 8.5. Since, n is 2 and S2 has length 3,
strncat(S1, S2, n) copies 2 bytes overwriting the NULL character of S1 and the byte that follows it. Then it
puts the NULL character in the next byte to complete the C-string S1. This increases its length to 10.
S1 S2
A B C D E F G H \0 x y z \0
strncat(S1,S2,2)
A B C D E F G H x y \0 x y z \0
S1 S2
Example 08
The following example of a C++ program demonstrates the strcmp( ) function.
The function takes two parameters, e.g., S1 and S2, where both of them are string. This function
compares S1 and S2 character by character. If the strings are equal, the function returns 0. If the first
non-matching character in S1 is greater (in ASCII) than that of S2, the function returns a positive integer. If
the first non-matching character in S1 is lower (in ASCII) than that of S2, the function returns a negetaive
integer.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char S1[] = "AUST", S2[] = "aust", S3[] = "AUST";
7 int result ;
8 result = strcmp (S1 , S2);
9 cout << " strcmp (S1 , S2) = " << result << endl;
10 result = strcmp (S2 , S3);
11 cout << " strcmp (S2 , S3) = " << result << endl;
12 result = strcmp (S3 , S1);
84 Laboratory 8. Strings
13 cout << " strcmp (S3 , S1) = " << result << endl;
14 }
In the program, strings S1 and S2 are not equal. Hence, the result is a non-zero integer. Hoever, strings
S1 and S3 are equal. Hence, the result is 0.
Example 09
The following example of a C++ program demonstrates the strtok() function.
This function splits a string by some delimiter. Splitting a string is a very common task. For example,
we have a comma separated list of items from a file and we want individual items in an array.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 int main ()
5 {
6 char str [] = " Barishal , Chittagong , Dhaka , Khulna , Rajshahi , \
7 Rangpur , Mymensingh , Sylhet ";
8 char* token = strtok (str , ",");
9 while (token != NULL)
10 {
11 cout << token << endl;
12 token = strtok (NULL , ",");
13 }
14 }
Example 10
The following example of a C++ program demonstrates a user defined function to copy one string into
another string without using the predefined strcpy( ) function.
1 # include <iostream >
2 # include <cstring >
3 using namespace std;
4 char* stringcopy (char* str1 , char* str2)
5 {
6 char* p = str1;
8.3. Standard C++ Strings 85
Example 11
The following example of a C++ program counts the number of characters in a string.
1 # include <iostream >
2 # include <string >
3 using namespace std;
4 int main( )
5 {
6 string small , large;
7 small = "I am a student .";
8 large = "I study in the EEE department of AUST.";
9 cout << "The small string has " << small. length ()
10 << " characters ." << endl;
11 cout << "The large string has " << large. length ()
12 << " characters ." << endl;
13 }
Example 12
The following example of a C++ program transforms the lowercase characters into the uppercase char-
acters. This example also demonstrates to access the individual characters in a string.
1 # include <iostream >
2 # include <string >
3 using namespace std;
4 int main( )
5 {
6 string s;
7 cout << "Enter an string with lowercase characters : ";
8 getline (cin , s);
9 for (int i = 0; s[i] != ’\0’; i++)
10 {
11 if(s[i] >= ’a’ && s[i] <= ’z’)
12 s[i] = s[i] - (’a’-’A’);
13 }
14 cout << "After transforming into uppercase characters : "<< s << endl;
15 }
Example 13
The following example of a C++ program compares two strings.
1 # include <iostream >
2 # include <string >
8.3. Standard C++ Strings 87
To compare two strings for equality the ‘==’ and ‘ !=’ operators are used in the above example. You
can use ‘<’, ‘<=’, ‘>’, and ‘>=’ to compare strings as well. These operators compare strings lexicographically,
character by character and are case-sensitive. The following comparisons all evaluate to true: "A" < "B",
"App" < "Apple", "help" > "hello", "Apple" < "apple". The last one might be a bit confusing, but the ASCII
value for A is 65, and comes before a, whose ASCII value is 97. So "Apple" comes before "apple" (or, for that
matter, any other word that starts with a lower-case letter).
Example 15
The following example of a C++ program to append two or more strings.
1 # include <iostream >
2 # include <string >
3 using namespace std;
4 int main( )
5 {
88 Laboratory 8. Strings
Example 16
The following example of a C++ program to to search one or more characters within a string.
The string member function find is used to search within a string for a particular string or character. A
sample usage such as str.find(key) searches the receiver string str for the key. The parameter key can either
be a string or a character. There is an optional second integer argument to find which allows you to specify
the starting position; when this argument is not given, 0 is assumed. Thus, str.find(key, n) starts at position
n within str and will attempt to find key from that point on.
1 # include <iostream >
2 # include <string >
3 using namespace std;
4 int main( )
5 {
6 string sentence = "Yes , we went to class after we left the dorm.";
7 int first_we = sentence .find("we");
8 int second_we = sentence .find("we", first_we + 1);
9 int third_we = sentence .find("we", second_we + 1);
10 int c_pos = sentence .find(’c’);
11 int d_pos = sentence .find(’d’);
12 cout << " Position of first we: " << first_we << endl;
13 cout << " Position of second we: " << second_we << endl;
14 cout << " Position of third we: " << third_we << endl;
15 cout << " Position of c: " << c_pos << endl;
16 cout << " Position of d: " << d_pos << endl;
17 }
Position of d: 40
Post-laboratory Problems
1. Write and run a C++ program to test the strncmp( ) function.
2. Write and run a C++ program that does exactly the same task of strncpy( ) without using the default
strncpy( ) function.
3. Write and run a C++ program that does exactly the same task of strcat( ) without using the default
function strcat( ).
4. Write and run a C++ program that counts the vowels of a given string.
5. Write and run a C++ program that reads one line of text and then prints it with all its blanks removed.
6. Write and run a C++ program that reads one line of text and then prints the line in reverse order. Fol-
lowing is an example of the console output.
Input : Today is Friday .
Output : . yadirF si yadoT
Laboratory 9
9.1. Objective
This laboratory focuses on the concept of the Object Oriented Programming (OOP). Students will learn
to apply the OOP concept by introducing Structures and Classes. In addition, students will develop ability
to define as well as apply Structure and Class for solving problems.
9.2. Structure
Structure is a collection of variables of different data types under a single name. For example, a banking
app wants to store some information about one person, such as, name, account number and account balance.
As a programmer you can easily create different variables name, i.e., name, number, balance to store these
information separately. However, in the future, you would want to store information about multiple persons.
Now, you’d need to create different variables for each information per person, i.e., name1, number1, balane1,
name2, number2, balance2, name3, number3, balance3, etc. It can be easily visualize how big and messy the
code would look. Also, since no relation between the variables (information) would exist, it is going to be a
daunting task. A better approach will be to have a collection of all related information under a single name
Person, and use it for every person. Now, the code looks much cleaner, readable and efficient as well. This
collection of all related information under a single name Person is a structure.
Here a structure Bank is defined which has three members – name, number and balance. When a struc-
ture is created, no memory is allocated. The structure definition is only the blueprint for the creating of
variables. You can imagine it as a data type. When you define an integer as int n; the int specifies that,
variable n can hold integer element only. Similarly, structure definition only specifies that, what property a
structure variable holds when it is defined.
Once you declare a structure Bank as above, you can define a structure object as Bank account;. Thus,
an object account is defined which is of type structure Bank. When object is defined, only then the required
memory is allocated by the compiler.
92 Laboratory 9. Structures and Classes
Example 01
The following example of a C++ program demonstrates the basic idea of the structure.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 struct Bank
5 {
6 string name;
7 int number ;
8 double balance ;
9 };
10 int main ()
11 {
12 Bank account ;
13 cout << "Enter Full name: ";
14 getline (cin , account .name );
15 cout << "Enter account number : ";
16 cin >> account . number ;
17 cout << "Enter account balance : ";
18 cin >> account . balance ;
19 cout << endl << " Displaying Information ." << endl;
20 cout << "Full name: " << account .name << endl;
21 cout << " Account number : " << account . number << endl;
22 cout << " Account balance : " << account . balance << " BDT";
23 return 0;
24 }
Displaying Information .
Full name: Musa Aman
Account number : 1020304
Account balance : 50.5 BDT
Here a structure Bank is defined which has three members – name, number and balance. Inside the
main( ) function, a structure object account is defined. Then, the user is asked to enter information and data
entered by user is displayed.
Example 02
The following example of a C++ program demonstrates to pass any structure to a function by the Passing
by Value method.
Displaying Information .
Full name: Musa Aman
Account number : 1020304
Account balance : 50.5 BDT
In the line 15, the structure object account is passed to get_data( ) function which takes input from user
which is then returned to main( ) function. (The value of all members of a structure variable can be assigned
94 Laboratory 9. Structures and Classes
to another structure using assignment operator (=), if both structure variables are of same type. You don’t need to
manually assign each members.)
Then, the object account is to passed to a function using display_data(account); in line 16. The return
type of display_data( ) is void and a single argument of type structure is passed. Then the members of
structure Bank is displayed from this function.
Example 03
The following example of a C++ program elaborates the passing by reference method.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 struct Bank
5 {
6 string name;
7 int number ;
8 double balance ;
9 };
10 void display_data (Bank *acc );
11 int main ()
12 {
13 Bank account ;
14 cout << "Enter name: ";
15 cin >> account .name;
16 cout << "Enter account number : ";
17 cin >> account . number ;
18 cout << "Enter account balance : ";
19 cin >> account . balance ;
20 display_data (& account );
21 return 0;
22 }
23 void display_data (Bank *acc)
24 {
25 cout << endl << " Displaying Information . " << endl;
26 cout << "Name: " << acc ->name << endl;
27 cout << " Account number : " << acc -> number << endl;
28 cout << " Account balance : " << acc -> balance << endl;
29 }
Displaying Information .
Name: Kishor
9.2. Structure 95
This case is similar to the previous one (passing by value), the only difference is that this time, we are
passing the address of the structure object to the function. While declaring the function, we passed the
pointer of the copy acc of the structure object account in its parameter. In the function, we accessed the
members of the pointer using ‘–>’ sign.
Example 04
The following example of a C++ program creates a structure and use object with array of size 10 to store
information of 10 persons. Using for loop, the program takes the information of 10 persons from the user
and displays it on the screen.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 struct Bank
5 {
6 string name;
7 int number ;
8 double balance ;
9 };
10 int main ()
11 {
12 Bank account [10];
13 for(int i=0; i <10; i++)
14 {
15 cout << "Enter name: ";
16 cin >> account [i]. name;
17 cout << "Enter account number : ";
18 cin >> account [i]. number ;
19 cout << "Enter account balance : ";
20 cin >> account [i]. balance ;
21 }
22
23 cout << endl << " Displaying Information ." << endl << endl;
24 for(int i=0; i <10; i++)
25 {
26 cout << "Name: " << account [i]. name << endl;
27 cout << " Account number : " << account [i]. number << endl;
28 cout << " Account balance : " << account [i]. balance << " BDT" << endl;
29 }
30 return 0;
31 }
Displaying Information .
Name :: Kishor
Account number : 001
Account balance : 11000.50 BDT
Name :: Musa
Account number : 002
Account balance : 22000.75 BDT
Name :: Robin
Account number : 003
Account balance : 33000.25 BDT
.
.
.
.
.
.
.
9.3. Class
Classes are an expanded concept of data structures. Like data structures, they can contain data mem-
bers, but they can also contain functions as members. An object is an instantiation of a class. For a clear
understanding, in terms of variables, a class would be the type, and an object would be the variable.
In other words, A class is a blueprint for the object. You can think of a class as a sketch (prototype) of a
house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build
the house. House is the object.
int length ;
int breadth ;
public :
void set_length (int L);
void set_breadth (int B);
int get_area ();
};
We have defined our own class named Rectangle. Here, class is a keyword which means that Rectangle
is a class. Inside the Rectangle class, we declared two variables and three functions. These variables and
functions belong to the class Rectangle since these are declared inside the class and thus are called members
of the class. There are two types of members in a class – data members (e.g., length and breadth) and member
functions, e.g., set_length( ), set_breadth( ) and get_area( ).
We declared the member functions of the class as public. Here, public is an access modifier which allows
the members of a class to be accessed directly from outside the class. The access modifiers decide how the
members of a class can be accessed. Like public, there are two more modifiers – private and protected. In the
above code, the two data members of the class are declared as private. When we declare any class member
as public, that variable becomes available everywhere in the program, even outside the function in which it
was declared. The member declared as private can only be accessed inside the class in which it is declared.
Thus, the object of the class cannot directly access its members. By default, all the members of a class are
private.
Example 05
The following example of a C++ program demonstrates the basic idea of the class.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 class Rectangle
5 {
6 int length ;
7 int breadth ;
8 public :
9 void set_length (int L);
10 void set_breadth (int B);
11 int get_area ();
12 };
13 void Rectangle :: set_length (int L)
14 {
15 length = L;
16 }
17 void Rectangle :: set_breadth (int B)
18 {
98 Laboratory 9. Structures and Classes
19 breadth = B;
20 }
21 int Rectangle :: get_area ()
22 {
23 return length * breadth ;
24 }
25 int main ()
26 {
27 Rectangle rect;
28 rect. set_length (7);
29 rect. set_breadth (4);
30 int area = rect. get_area ();
31 cout << "Area of the rectangle : " << area << endl;
32 return 0;
33 }
While defining the member functions, we have written Rectangle:: before the function name. This is to
tell the compiler that the function belongs to the class Rectangle.
In line 28, rect.set_length(7); statement calls the function set_length( ) with the parameter value 7. To
call any function, we use dot (.) after the object and then call that function. Since rect is an object of the
Rectangle class, therefore, rect.set_length( ) calls the function set_length( ) of Rectangle class for rect. This
sets the value of length as 7 for rect.
Similarly, in line 29, rect.set_breadth(4) calls the function set_breadth( ) and sets the value of breadth as
4.
In line 30, rect calls the function get_area() which returns length * breadth which is 28 (since the value
of length is 7 and that of breadth is 4). This value then gets assigned to the variable area.
9.3.3. Constructor
What would happen in the previous example if we called the member function get_area( ) before having
called set_length( ) and set_breadth( )? An undetermined result, since the members length and breadth had
never been assigned a value. In order to avoid that, a class can include a special function called its constructor,
which is automatically called whenever a new object of this class is created, allowing the class to initialize
member variables or allocate storage.
In other words, a constructor is a special type of member function that is called automatically when an
object is created. In C++, a constructor has the same name as that of the class and it does not have a return
type.
Example 06
The following example of a C++ program demonstrates the basic idea of constructor.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 class Rectangle
5 {
6 int length ;
7 int breadth ;
9.3. Class 99
8 public :
9 Rectangle (int , int );
10 int get_area ();
11 };
12 Rectangle :: Rectangle (int L, int B)
13 {
14 length = L;
15 breadth = B;
16 }
17 int Rectangle :: get_area ()
18 {
19 return length * breadth ;
20 }
21 int main ()
22 {
23 Rectangle rect (7, 4);
24 int area = rect. get_area ();
25 cout << "Area of the rectangle : " << area << endl;
26 return 0;
27 }
In this example when you created the object rect of class Rectangle, the constructor Rectangle( ) auto-
matically got called and initialized the data members for the object rect. It initialized the length and breadth
of rect to 7 and 4 respectively.
When the constructor was called, length and breadth were created and then in the body of the construc-
tor, these member variables were assigned values.
Example 06
The following example of a C++ program demonstrates the basic idea of overloading constructors.
1 # include <iostream >
2 #include <string >
3 using namespace std;
4 class Rectangle
5 {
6 int length ;
7 int breadth ;
8 public :
9 Rectangle ();
10 Rectangle (int , int );
11 int get_area ();
12 };
13 Rectangle :: Rectangle ()
100 Laboratory 9. Structures and Classes
14 {
15 length = 10;
16 breadth = 3;
17 }
18 Rectangle :: Rectangle (int L, int B)
19 {
20 length = L;
21 breadth = B;
22 }
23 int Rectangle :: get_area ()
24 {
25 return length * breadth ;
26 }
27 int main ()
28 {
29 Rectangle rect_A (7, 4), rect_B (2, 10), rect_C ;
30 int area;
31 area = rect_A . get_area ();
32 cout << "Area of the rectangle A: " << area << endl;
33 area = rect_B . get_area ();
34 cout << "Area of the rectangle B: " << area << endl;
35 area = rect_C . get_area ();
36 cout << "Area of the rectangle C: " << area << endl;
37 return 0;
38 }
In the above example, three objects of class Rectangle are constructed: rect_A, rect_B and rect_C. Here,
rect_A, and rect_B both are constructed with two arguments. But this example also introduces a special kind
constructor – the “default constructor”. The default constructor is the constructor that takes no parameters,
and it is special because it is called when an object is declared but is not initialized with any arguments. In
the example above, the default constructor is called for rect_C.
Post-laboratory Problems
1. Write and run a C++ program that converts a number entered in Roman numerals to decimal. Your pro-
gram should consist of a class, say, roman_type. An object of type roman_type should do the following.
a) Store the number as a Roman numeral.
b) Convert and store the number into decimal form.
c) Print the number as a Roman numeral or decimal number as requested by the user. The decimal
values of the Roman numerals are:
M 1000
D 500
C 100
L 50
X 10
Post-laboratory Problems 101
V 5
I 1
10.1. Objective
This laboratory discusses the file processing in C++. Students will learn to open and close files as well
as to read and write on files. Apart from that, this laboratory also focuses on the standard C++ vectors.
Students will be familiarize with passing the vector to function as well as some necessary member functions
which makes adding and deleting elements from the vector easier.
Table 10.1. Data types used for file handling from the fstream library
Data type Description
ofstream It is used to create files and write on files.
ifstream It is used to read from files.
fstream It can perform the function of both ofstream and ifstream which means it
can create files, write on files, and read from files.
Example 01
The following example of a C++ program demonstrates how to open a file, then write and read that file
and, then close that file.
104 Laboratory 10. File I/O and Vector
We have opened the file example.txt for both reading and writing purposes. Therefore, you must create
the example.txt file in your working directory. We can also open the file for both reading and writing
purposes. You should remember that, C++ automatically close and release all the allocated memory. But
a programmer should always close all the opened files. We use << and >> to write and read from the file
’example.txt’ respectively. Now open the file example.txt and check the content.
Example 02
The following example of a C++ program demonstrates how to open a text file for appending. That
means, this example adds new text at the end of existing text of the example.txt file in your working direc-
tory.
1 # include <iostream >
2 # include <fstream >
3 using namespace std;
4 int main ()
5 {
6 char text [2000];
7 fstream file;
8 file.open (" example .txt", ios :: app );
9 cout << "Write the text to be added on the file:" << endl;
10 cin. getline (text , sizeof (text ));
11 file << text << endl;
12 file.close ();
13 return 0;
14 }
Now check the example.txt file for the change you have just made.
Example 03
The following example of a C++ program demonstrates reads words from the external file named in-
put.txt, capitalizes them, and then writes them to the external file named output.txt.
1 # include <fstream >
2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 ifstream infile ("input.txt");
7 ofstream outfile (" output .txt");
8 string word;
9 char c;
10 while ( infile >> word)
11 {
12 if (word [0] >= ’a’ && word [0] <= ’z’)
13 {
14 word [0] += ’A’ - ’a’;
15 }
16 outfile << word;
17 infile .get(c);
18 outfile .put(c);
19 }
20 return 0;
21 }
Now check the output.txt file for the change you have just made.
10.3. Vector
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is
inserted or deleted, with their storage being handled automatically by the container. Vector elements are
placed in contiguous storage so that they can be accessed and traversed using iterators (similar to pointer).
In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may
be a need of extending the array. Removing the last element takes only constant time because no resizing
happens. Inserting and erasing at the beginning or in the middle is linear in time.
You need to include the <vector> header in our program. Now, look at the declaration of a vector named
marks of type int to store the marks of students.
106 Laboratory 10. File I/O and Vector
We can also assign values to the vector after declaration as shown below.
vector <int > marks;
marks = {50, 45, 47, 65, 80};
In the above declarations, we stored the marks of 5 students in a vector named marks. Since we did not
declare the array length, so the length of marks became equal to the number of values it was initialized with.
Now, we may change the number of students, i.e. either store the marks of more students or remove the
marks of some students.
Example 04
The following example of a C++ program demonstrates the above iterators associated with the vector.
1 # include <iostream >
2 # include <vector >
3 using namespace std;
4 int main ()
5 {
6 vector <int > v1;
7 for (int i = 1; i <= 5; i++)
8 {
10.3. Vector 107
Example 05
The following example of a C++ program demonstrates the above capacity function associated with the
vector.
1 # include <iostream >
2 # include <vector >
3 using namespace std;
108 Laboratory 10. File I/O and Vector
4 int main ()
5 {
6 vector <int > v1;
7 for (int i = 1; i <= 5; i++)
8 {
9 v1. push_back (i);
10 }
11 cout << "Size : " << v1.size ();
12 cout << endl << " Capacity : " << v1. capacity ();
13 cout << endl << " Max_Size : " << v1. max_size ();
14 v1. resize (4);
15 cout << endl << "Size : " << v1.size ();
16 if (v1.empty () == false)
17 {
18 cout << endl << " Vector is not empty";
19 }
20 else
21 {
22 cout << endl << " Vector is empty";
23 }
24 v1. shrink_to_fit ();
25 cout << endl << " Vector elements are: ";
26 for (auto it = v1.begin (); it != v1.end (); it ++)
27 {
28 cout << *it << " ";
29 }
30 return 0;
31 }
Size : 5
Capacity : 8
Max_Size : 2305843009213693951
Size : 4
Vector is not empty
Vector elements are: 1 2 3 4
Table 10.5. Element access related functions associated with the vector
Function Description
reference operator [v] Returns a reference to the element at position v in the vector.
at(V) Returns a reference to the element at position v in the vector.
front() Returns a reference to the first element in the vector.
back() Returns a reference to the last element in the vector.
data() Returns a direct pointer to the memory array used internally by
the vector to store its owned elements.
Example 06
The following example of a C++ program demonstrates the above element access function associated
with the vector.
10.3. Vector 109
Example 07
The following example of a C++ program explains the above modifier function associated with vector.
1 # include <iostream >
2 # include <vector >
3 using namespace std;
4 int main ()
5 {
110 Laboratory 10. File I/O and Vector
Example 08
The following example of a C++ program demonstrate the sorting an unsorted vector.
1 # include <iostream >
2 #include <vector >
3 # include <algorithm >
4 using namespace std;
10.3. Vector 111
5 int main ()
6 {
7 vector <int > v = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
8 cout << " Unsorted : ";
9 for (auto x : v)
10 {
11 cout << x << " ";
12 }
13 sort(v.begin (), v.end ());
14 cout << endl << " Sorted : ";
15 for (auto x : v)
16 {
17 cout << x << " ";
18 }
19 sort(v.begin (), v.end (), greater <int >());
20 cout << endl << " Sorted Descending : ";
21 for (auto x : v)
22 {
23 cout << x << " ";
24 }
25 return 0;
26 }
Example 09
The following example of a C++ program demonstrate the process of reading a text file and storing the
data from that file in vector.
1 # include <iostream >
2 # include <fstream >
3 # include <sstream >
4 # include <vector >
5 using namespace std;
6 struct Weather
7 {
8 int a,b,e;
9 double c,d,f;
10 };
11 int main ()
12 {
13 vector <Weather > data_weather ;
14 Weather w;
15 string line;
16 ifstream myfile (" weather .txt");
17 if (! myfile . is_open ())
18 {
19 cerr << " unable to open file";
20 return 0;
112 Laboratory 10. File I/O and Vector
21 }
22 getline (myfile , line );
23 cout << line << endl;
24 while ( getline (myfile , line ))
25 {
26 istringstream buffer (line );
27 buffer >> w.a >> w.b >> w.c >> w.d >> w.e >> w.f ;
28 data_weather . push_back (w);
29 cout << line << endl;
30 }
31 myfile .close ();
32 cout << endl << endl <<" ========== READING VECTOR ======== "
33 << endl << endl;
34 for(auto w1: data_weather )
35 {
36 cout << w1.a <<"\t" << w1.b <<"\t"<< w1.c<<"\t" << w1.d
37 <<"\t" << w1.e <<"\t"<< w1.f <<"\n";
38 }
39 return 0;
40 }
In the above example, weather.txt is a text file that contains rows of data with a title row. Each data row
contain six data delaminated by space as the following.
1 a b c d e f
2 2004 9 20.5 8.8 0 37.4
3 2005 10 13.6 4.2 5 77.8
4 2006 11 11.8 4.7 3 45.5
5 2007 12 7.7 0.1 17 65.1
6 2008 11 7.3 0.8 14 74.6
7 2009 9 6.5 0.1 13 3.3
Since, the data contains six fields it is better to use a structure named Weather that contains six variables.
Out of these variables three are integer and other three are double. In the main program a vector named
data_weather of type Weather is used which contains all the 6 data with their corresponding sub fileds.
Post-laboratory Problems 113
myfile of ifstream type object is used to read the data from weather.txt file sequentially. getline(myfile,
line) is a function which reads the line from myfile and copy the text to line and send the iterator(pointer)
to the starting of next line. In the while loop this process continues until eof(). When eof() is reached get-
line(myfile, line) generates false or zero and while loop terminates.
buffer is of istringstream type which takes entire line and read each word delaminated by space. All
the data fields of single row is extracted and copied to Weather typed variable w. Then w is push_back (i.e.,
copied) to the vector named data_weather.
Post-laboratory Problems
1. Write and run a C++ program that counts and prints the number of lines, words, and letter frequencies
from an input text file.
2. Write and run a C++ program that reads full names, one per line from a text file and then prints them in
the standard Bangladeshi passport format (e.g., Last Name, First Name, Middle Name).
3. Write and run a C++ program to manage a shopping list. Each shopping list item is represented by a
string. Your design requires a print function that prints out the contents of the shopping list. Using a
vector to hold the shopping list items, write a print function to print out the contents of a vector of
strings. Test your print function with a main program that does the following:
a) Create an empty vector. Print it.
b) Append the items, "eggs," "milk," "sugar," "chocolate," and "flour" to the list. Print it.
c) Remove the last element from the vector. Print it.
d) Append the item, "coffee" to the vector. Print it.
e) Write a loop that searches for the item, "sugar" and replace it with "honey." Print the vector.
f) Write a loop that searches for the item, "milk," and then remove it from the vector. (You are permitted
to reorder the vector to accomplish the removal, if you want.) Print the vector.
g) Search for the item, "milk" and find a way to remove it without changing the order of the rest of the
vector. (This is not necessarily an efficient operation.) Print the vector one more time.