0% found this document useful (0 votes)
18 views

Eee 2110

The document provides an introduction to programming in C++, including familiarizing students with the local computer system, the program preparation process, installing and using the Code::Blocks IDE, and an outline of the course contents and assessment methods.

Uploaded by

joyerullas35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Eee 2110

The document provides an introduction to programming in C++, including familiarizing students with the local computer system, the program preparation process, installing and using the Code::Blocks IDE, and an outline of the course contents and assessment methods.

Uploaded by

joyerullas35
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Ahsanullah University of Science and Technology

Department of Electrical and Electronic Engineering

Laboratory Manual
for
Electrical and Electronic Engineering Sessional Course

Student Name :
Student ID :

Course no : EEE 2110


Course Title : Programming Language Laboratory

For the students of the


Department of Electrical and Electronic Engineering
2nd Year, 1st Semester
Preface

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

1. Title: Programming Language Lab


2. Code: EEE 2110
3. Credit hours: 1.5
4. Level: Year 2, Semester 1
5. Faculty: Engineering
6. Department: Electrical and Electronic Engineering (EEE)
7. Programme: B.Sc. in Electrical and Electronic Engineering
8. Synopsis from the approved curriculum: Laboratory experiment based on the theory and the con-
cept learnt in EEE 2109.
9. Type of course: Core
10. Prerequisite(s): no prerequisite course(s)
11. Themes to be covered: Intruduction to the programming language, data types, selection statements,
iteration, function, arrays, pointers, strings, files, and classes.
12. Course outcomes: By the end of this course, students are expected to
a) identify the given problem statements to solve systematically using a basic logic approach.
b) implement different functions for input and output, various data types, basic operators, files and
functions.
c) construct a C++ program correctly from the analyzed problems using structured approach.
d) implement programming techniques to solve problems in the C++ programming language.
13. Reference materials:
a) Books/Papers:
i. The C++ Programming Language by Bjarne Stroustrup.
ii. C++ How to Program 10th Edition by Paul Deitel, Harvey Deitel.
iii. Teach Yourself C++ by Herbert Schildt.
iv. Schaum’s Outline of Programming with C++ by John Hubbard .
b) Websites (if any):
i. https://www.cplusplus.com/doc/tutorial/
ii. https://www.programiz.com/cpp-programming
iii. https://www.geeksforgeeks.org/c-plus-plus/
c) Handout (if any):
i. none
d) Others:
i. none
iii

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:

Method Percentage (%)


Attendance and Lab Performance 10
Lab Test 1 10
Lab Test 2 10
Lab Test 3 10
Lab Test 4 10
Lab Test 5 10
Semester Project 20
Final Quiz 20
Contents
Laboratory 1. Introduction to the C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2. Familiarize with the local computer system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3. The Program Preparation Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4. Code::Blocks IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4.1. Install Code::Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4.2. Using Code::Blocks for the first time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5. Introduction to the C++ programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Laboratory 2. Variables, operators and type conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2. The variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3. The input operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4. Arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5. Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6. Examples on arithmetic operators and mathematical functions . . . . . . . . . . . . . . . . . . . . . . 13
2.7. Increment and decrement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.8. Composite assignment operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.9. Type conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.9.1. Implicit conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.9.2. Explicit conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.10. Numeric overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Laboratory 3. Selection statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.2. The if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3. The if...else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.4. Nested if...else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.5. if...else if...else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.6. The switch statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.7. Ternary operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.8. Compound conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Laboratory 4. Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2. The while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.3. The do...while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.4. The for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
4.5. Nested loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.6. Infinite loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
vi Contents

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

9.2.4. Structure to function (Passing by reference) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94


9.2.5. Array of structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
9.3. Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.3.1. Declaring and defining a class in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
9.3.2. Accessing members of a class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
9.3.3. Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
9.3.4. Overloading constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Laboratory 10. File I/O and Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.1. Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.2. File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.2.1. Creating and opening a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
10.3. Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.3.1. Declaration of vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
10.3.2. Initialization of vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.3.3. Functions associated with the vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Post-laboratory Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Laboratory 1

Introduction to the C++

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.

1.2. Familiarize with the local computer system

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.

1.3. The Program Preparation Process

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

1.4. Code::Blocks IDE


You will use Code::Blocks as your primary IDE for C++ programming in this laboratory. Code::Blocks
is an open-source, cross-platform (Windows, Linux, etc.), and free C/C++ IDE. It supports many compilers,
such as GNU GCC (MinGW and Cygwin) and MS Visual C++. It supports interactive debugging (via GNU
GDB or MS CDB). Code::Blocks is surprisingly versatile, and in my opinion, much better than the Visual
Studio suite. The mother site of Code::Blocks is www.codeblocks.org.

1.4.1. Install Code::Blocks

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.

For Ubuntu (and Ubuntu based other Linux distributions)


1. Make sure your computer is connected to the internet.
2. Go to the software center of Ubuntu. Then search for Code::Blocks in the search bar. From the list,
select Code::Blocks, and click the install button to install it.
3. Alternatively, you can install Code::Blocks via terminal with the help of the following command.
sudo apt install codeblocks

1.4.2. Using Code::Blocks for the first time


1. Launch the Code::Blocks. After opening the Code::Blocks window, launch the Project Wizard through
File > New > Project... to start a new project. A window will come up. You will find many pre-configured
templates here for various types of projects, including the option to create custom templates. From that
list select the Console application, as this is the most common for our laboratory experiment purposes.
Then click Go.
2. Click next until you get to the Language Selection window. In this window, you will be asked to choose
whether you want to use C or C++. Select C++ and click Next.
3. In the next screen, Code::Blocks will prompt you with where you’d like to save the console application.
Give the project a name and select a destination folder. Code::Blocks will generate the remaining entries
from these two.
4. Finally, the wizard will ask if this project should use the default compiler (normally GCC) and the two
default builds: Debug and Release. All of these settings are fine. You don’t need to do anything here. Just
accept the defaults by hitting Finish.
5. At this stage the project will be generated. The main window will turn gray, but that is not a problem.
Only the source file needs to be opened. In the Projects tab of the Management pane on the left expand
the folders and double click on the source file main.cpp to open it in the editor.
6. This main.cpp file contains the following standard code. This is a simple basic C++ code, which prints
Hello World! in the output console.
1.5. Introduction to the C++ programs 3

# include <iostream >

using namespace std;

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

a) The above message indicates your program is free of errors.


b) At the same time, you will get the following console output:
Hello world!

Process returned 0 (0x0) execution time : 0.002 s


Press ENTER to continue .

9. If you have compiler errors, follow the instruction below.


a) Click the Build log at the bottom of the Code::Blocks window.
b) To read the first error message, scroll to the top of the error list.
c) If you double click on an error message, a red mark in the editor will identify the statement corre-
sponding to the error message.
d) Return to the editor and correct the error. And recompile the program by hitting F9.
You now have a running program! To write your own C++ code simply edit the main.cpp and, then hit F9
to compile it and run it again.

1.5. Introduction to the C++ programs


In this part, you will write your first C++ program along with some other examples.

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 }

The console output will be as follows.


Hello world!
I’m a C++ program .

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

7 cout << "I’m a C++ program ." << endl;


8 cout << "I’ll show you todays ’ date." << endl;
9 cout << "Today is January " << 15 << " " << 2021 << "." << endl;
10 return 0;
11 }

The console output will be as follows.


Hello world!
I’m a C++ program .
I’ll show you todays ’ date.
Today is January 15 2021.

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

Variables, operators and type conversions

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.

2.2. The variables


A variable provides us with named storage that our programs can manipulate. Each variable in C++ has
a specific type, which determines the size and layout of the variable’s memory; the range of values that can
be stored within that memory; and the set of operations that can be applied to the variable.
Consider variables as the mailboxes, in which data necessary for program execution can be stored. You
can store many types of data in these mailboxes. Integers, Floating-point numbers, and Characters are a few
of these data types. Whole numbers, including 0 and negative whole numbers, are called integers. Decimal
numbers, including negative decimal numbers and all integers, are called floating-point numbers. A char-
acter type is an integral type whose variables represent characters like the letter A or the digit 8. Standard
C++ has 14 different fundamental data types which are shown in the Figure 2.1 .

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

Boolean Type bool

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

Figure 2.1. Fundamental data types

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

Process returned 0 (0 x0) execution time : 0.002 s


Press ENTER to continue .

2.3. The input operator


In C++, input is almost as simple as output. The input operator >‌> (also known as get operator or
extraction operator) works like the output operator << . The function for input is cin. It is used to accept
the input from the standard input device, such as, keyboard. Following example program will clarify the
operation of cin.

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

6 cout << "Enter two integers (use SPACE to separate ): ";


7 cin >> m >> n;
8 cout << "m = " << m << ", n = " << n << endl;
9 double x, y, z;
10 cout << "Enter three decimal numbers (use SPACE to separate ): ";
11 cin >> x >> y >> z;
12 cout << "x = " << x << ", y = " << y << ", z = " << z << endl;
13 char c1 , c2 , c3 , c4;
14 cout << "Enter four characters (use SPACE to separate ): ";
15 cin >> c1 >> c2 >> c3 >> c4;
16 cout << "c1 = " << c1 << ", c2 = " << c2 << ", c3 = " << c3;
17 cout << ", c4 = " << c4 << endl;
18 }

2.4. Arithmetic operators


Arithmetic operators are used to perform arithmetic operations on variables and data. For example, in
a + b; the + operator is used to add two variables a and b . Similarly there are various other arithmetic
operators in C++. The following two examples will show the exact use of different types of arithmetic
operators.

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

1 /* Floating -Point Arithmetic


2 Testing the operators +, -, *, /, and % */
3 # include <iostream >
4 using namespace std;
5 int main ()
6 {
7 float x=54, y=20;
8 cout << "x = " << x << " and y = " << y << endl;
9 cout << "x+y = " << x+y << endl;
10 cout << "x-y = " << x-y << endl;
12 Laboratory 2. Variables, operators and type conversions

11 cout << "x*y = " << x*y << endl;


12 cout << "x/y = " << x/y << endl;
13 }

2.5. Mathematical functions


C++ provides a large number of mathematical functions that can be used directly in the program. These
functions are widely used in the mathematical calculations. These functions are included in the cmath li-
brary. The following two examples demonstrate a few familiar mathematical functions.

Example 05

1 // Some important trigonometric functions


2 # include <iostream >
3 # include <cmath >
4 using namespace std;
5 int main ()
6 {
7 double PI = 3.14159;
8 cout << "cos (60) = " << cos (60.0* PI /180.0) << endl;
9 cout << "sin (60) = " << sin (60.0* PI /180.0) << endl;
10 cout << "tan (45) = " << tan (45.0* PI /180.0) << endl;
11 }

Example 06

1 // abs computes the absolute value of a given number .


2 // sqrt used to find the square root of the given number .
3 // pow returns the result by raising base to the given exponent .
4 // exp returns the exponential raised to the given argument .
5 // log returns the natural logarithm of the argument .
6 // log10 returns the base -10 logarithm of the argument .
7
8 # include <iostream >
9 # include <cmath >
10 using namespace std;
11 int main ()
12 {
13 double param , result ;
14 param = 10.57;
15 result = abs(param );
16 cout << " Absolute value of 10.57 is " << result << endl;
17 param = -10.57;
18 result = abs(param );
19 cout << " Absolute value of -10.57 is " << result << endl;
20 param = 25;
21 result = sqrt (param );
22 cout << " Square root of 25 is " << result << endl;
23 cout << "Value of 2^4 is " << pow (2, 4) << endl;
24 cout << "Value of e^5 is " << exp (5) << endl;
2.6. Examples on arithmetic operators and mathematical functions 13

25 cout << "Value of ln (10) is " << log (10) << endl;
26 cout << "Value of log (10) is " << log10 (10) << endl;
27 }

2.6. Examples on arithmetic operators and mathematical functions


Example 07
Write and run a C++ program that accepts the radius of a circle from the user and compute the area and
circumference.

1 # include <iostream >


2 # include <cmath >
3 using namespace std;
4 int main ()
5 {
6 float radius , area , circum , PI = 3.14159;
7 cout <<" Input the radius (1/2 of diameter ) of a circle : ";
8 cin >> radius ;
9 circum = 2*PI* radius ;
10 area = PI*pow(radius ,2);
11 cout << " The area of the circle is : " << area << endl;
12 cout << " The circumference of the circle is : " << circum << endl;
13 cout << endl;
14 }

The console output will be as follows.

Input the radius (1/2 of diameter ) of a circle : 7.8


The area of the circle is : 191.134
The circumference of the circle is : 49.0088

Example 08
Write a program in C++ to enter length in centimeter and convert it into meter and kilometer.

1 #include <iostream >


2 using namespace std;
3 int main ()
4 {
5 float km , met ,cent;
6 cout << "Input the distance in centimeter : ";
7 cin >> cent;
8 met = (cent /100);
9 km = (cent /100000);
10 cout << "The distance in meter is: " << met << endl;
11 cout << "The distance in kilometer is: " << km << endl;
12 cout << endl;
13 }

The console output will be as follows.


14 Laboratory 2. Variables, operators and type conversions

Input the distance in centimeter : 2000


The distance in meter is: 20
The distance in kilometer is: 0.02

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 }

The console output will be as follows.


Input the Principle : 1000
Input the Rate of Interest : 4
Input the Time: 4
The Simple interest for the amount 1000 for 4 years @ 4 % is: 160

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 console output will be as follows.

Time delay when talking to Mars: 182.796 seconds .


This is 3.04659 minutes .

2.7. Increment and decrement

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

1 // example of prefix and postfix


2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int m, n;
7 m = 44;
8 n = ++m;
9 cout << " Prefix increment : \t m = " << m << " and n = " << n << endl;
10 m = 44;
11 n = m++;
12 cout << " Postfix increment : \t m = " << m << " and n = " << n << endl;
13 m = 44;
14 n = --m;
15 cout << " Prefix decrement : \t m = " << m << " and n = " << n << endl;
16 m = 44;
17 n = m--;
18 cout << " Postfix decrement : \t m = " << m << " and n = " << n << endl;
19 }

The console output will be as follows.


16 Laboratory 2. Variables, operators and type conversions

Prefix increment : m = 45 and n = 45


Postfix increment : m = 45 and n = 44
Prefix decrement : m = 43 and n = 43
Postfix decrement : m = 43 and n = 44

2.8. Composite assignment operators


The standard assignment operator in C++ is the equals sign (i.e., =). In addition to this operator, C++
also includes the following composite assignment operators,
+ =, − =, ∗ =, / =, % =
When applied to a variable on the left, each applies the indicated arithmetic operation to it using the
value of the expression on the right .

Example 12

1 // example of omposite assignment operators


2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int n = 22;
7 cout << "The value of n = " << n << endl;
8 n += 9;
9 cout << "After n += 9, n = " << n << endl;
10 n -= 5;
11 cout << "After n -= 5, n = " << n << endl;
12 n *= 2;
13 cout << "After n *= 2, n = " << n << endl;
14 n /= 3;
15 cout << "After n /= 3, n = " << n << endl;
16 n %= 7;
17 cout << "After n %= 7, n = " << n << endl;
18 }

The console output will be as follows.


The value of n = 22
After n += 9, n = 31
After n -= 5, n = 26
After n *= 2, n = 52
After n /= 3, n = 17
After n %= 7, n = 3

2.9. Type conversions


C++ allows us to convert data of one type to that of another. This is known as type conversion. There are
two types of type conversion in C++.
1. Implicit conversion
2. Explicit conversion (also known as Type casting)
2.9. Type conversions 17

2.9.1. Implicit conversion


The type conversion that is automatically done by the compiler is known as implicit type conversion.
This type of conversion is also known as automatic conversion. Let look at two examples of implicit type
conversion.

Example 13

1 // conversion from int to double


2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int num_int = 9;
7 double num_double ;
8 num_double = num_int ;
9 cout << " num_int = " << num_int << endl;
10 cout << " num_double = " << num_double << endl;
11 return 0;
12 }

The console output will be as follows.


num_int = 9
num_double = 9

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

1 // conversion from double to int


2 # include <iostream >
3 using namespace std;
4 int main ()
5 {
6 int num_int ;
7 double num_double = 9.99;
8 num_int = num_double ;
9 cout << " num_int = " << num_int << endl;
10 cout << " num_double = " << num_double << endl;
11 return 0;
12 }

The console output will be as follows.


num_int = 9
num_double = 9.99

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)

Figure 2.2. Possible data loss during type conversion

2.9.2. Explicit conversion


When the user manually changes data from one type to another, this is known as explicit conversion.
In general, if T is a data type and v is a value of different data type, then either of the expressions (T )v or
T (v) converts v to type T . This type of conversion is also known as type casting. Following is an example
of the type casting.

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 }

The console output will be as follows.


num_double = 3.56
num_int1 = 3
num_int2 = 3

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 }

2.10. Numeric overflow


On most computers, the long int type allows 4,294,967,296 different values. That is a lot of value, but it
is still finite. Computers are finite, so the range of any type must also be finite. But in mathematics, there are
infinitely many integers. Consequently, computers are manifestly prone to error when their numeric values
become too large. That kind of error is called numeric overflow.

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 }

The console output will be as follows.


n = 1000
n = 1000000
n = 1000000000
n = -727379968

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.

3.2. The if statement


In C++ programming, the if statement allows the programmer to change the logical order of a program,
i.e., it makes the order in which the statements are executed differ from the order in which they are listed in
the program. In other words, the if statement is used to run a block code only when a certain condition is
met. For example, assigning grades based on marks obtained by a student.
— if the percentage is above 80, assign grade A+
— if the percentage is above 75, assign grade A
— if the percentage is above 70, assign grade A-
The if statement uses a Boolean expression to determine whether to execute a statement or to skip it. The
syntax of the if statement is as follows.
if ( condition )
{
statement ; // body of if statement
}

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 }

If the user enters 5, the console output will be as follows.


Enter an integer : 5
You entered a positive number : 5
This statement is always executed .

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 }

The console output will be as follows.


Enter three integers : 44 11 99
Their minimum is 11

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

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 }

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.

3.3. The if...else statement


The if...else statement uses a Boolean expression to determine which one of the two statements to exe-
cute. The syntax of the if...else statement is as follows
if ( condition )
{
// block of code if the condition is true
}
else
{
// block of code if the condition is false
}

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 }

If the user enters 4, the console output will be as follows.


Enter an integer : 4
You entered a positive integer : 4.
This statement is always executed .

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 }

3.4. Nested if...else statement


An if statement uses Boolean expression to determine whether to execute or skip a statement. An if...else
statement uses a Boolean expression to determine which one of the two statements to execute. The state-
ments to be executed or skipped could be simple statements or compound statements. They also can be an
if...else statement. An if...else statement within another if...else statement is called a nested if...else statement.
3.4. Nested if...else statement 25

Example 06

1 # include <iostream >


2 using namespace std;
3 int main ()
4 {
5 int num;
6 cout << "Enter an integer : ";
7 cin >> num;
8 if (num != 0)
9 {
10 if (( num % 2) == 0)
11 {
12 cout << "The number is even." << endl;
13 }
14 else
15 {
16 cout << "The number is odd." << endl;
17 }
18 }
19 else
20 {
21 cout << "The number is 0 and it is neither even nor odd." << endl;
22 }
23 cout << "This statement is always executed ." << endl;
24 }

If the user enters 34, the console output will be as follows.


Enter an integer : 34
The number is even.
This statement is always executed .

If the user enters 35, the console output will be as follows.


Enter an integer : 35
The number is odd.
This statement is always executed .

If the user enters 0, the console output will be as follows.


Enter an integer : 0
The number is 0 and it is neither even nor odd.
This statement is always executed .

Example 07

1 # include <iostream >


2 # include <cstdlib >
3 using namespace std;
4 int main ()
5 {
6 int magic , guess;
7 magic = rand ();
26 Laboratory 3. Selection statements

8 cout << "Enter your guess: ";


9 cin >> guess;
10 if (guess == magic)
11 {
12 cout << "Right Guess!" << endl;
13 cout << magic << " is the number ." << endl;
14 }
15 else
16 {
17 cout << "Sorry! You guessed wrong." << endl;
18 if (guess > magic)
19 {
20 cout << "Your guess is too high" << endl;
21 }
22 else
23 {
24 cout << "Your guess is too low." << endl;
25 }
26 }
27 return 0;
28 }

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 }

3.5. if...else if...else statement


The if...else statement is used to execute a block of code among two alternatives. However, if we need
to make a choice between more than two alternatives, we use the if...else if...else statement. The syntax of
the if...else if...else statement is as follows.
if ( condition1 )
{
// code block 1
}
else if ( condition2 )
{
// code block 2
}
else
{
// code block 3
}

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 }

If the user enters 1, the console output will be as follows.


Enter an integer : 1
You entered a positive integer : 1.
This statement is always executed .

If the user enters −2, the console output will be as follows.


Enter an integer : -2
You entered a negative integer : -2.
This statement is always executed .

If the user enters 0, the console output will be as follows.


Enter an integer : 0
You entered 0.
This statement is always executed .

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.

3.6. The switch statement


The switch statement allows programmers to execute a block of code among many alternatives. The
syntax of the switch statement is as follows.
switch ( expression )
{
case constant1 :
// code to be executed if
// expression is equal to constant1
break;
case constant2 :
// code to be executed if
// expression is equal to constant2
break;
.
.
.
default :
// code to be executed if
// expression doesn ’t match any constant
}

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 }

3.7. Ternary operator

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.

condition ? expression1 : expression2 ;

Here, condition is evaluated and


— if condition is true, then expression1 is executed.
— if condition is false, then expression2 is executed.
The ternary operator takes three operands (condition, expression1 and expression2). Hence, the name ternary
operator.

Example 12
The following example of a C++ program finds the minimum of two integers using ternary operator.

1 # include <iostream >


2 using namespace std;
3 int main ()
4 {
5 int x, y, result ;
6 cout << "Enter two integers : ";
7 cin >> x >> y;
8 result = (x<y) ? x : y;
9 cout << result << " is the minimum ." << endl;
10 }
3.8. Compound conditions 31

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 }

3.8. Compound conditions


Conditions such as n%d and x >= y can be combined to form compound conditions. This is done
using the logical operators && (and), || (or), and ! (not). They are defined by
— p&&q; evaluates to true if and only if both p and q evaluate to true
— p||q; evaluates to false if and only if both p and q evaluate to false
— !p; evaluates to true if and only if p evaluates to false
For example, (n%d||x >= y) will be false if and only if n is zero and x is less than y. The definitions of
the three logical operators are usually given by the truth tables in the Figure 3.1 below.

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

12 if (y <= x && y <= z)


13 {
14 cout << "Their minimum is " << y <<endl;
15 }
16 if (z <= x && z <= y)
17 {
18 cout << "Their minimum is " << z <<endl;
19 }
20 }

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.

4.2. The while loop


The syntax of the while statement is as follows.
while ( condition )
{
// body of the loop
}

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

The console output will be as follows.


1 2 3 4 5

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 console output will be as follows.


Enter a number : 6
Enter a number : 12
Enter a number : 7
Enter a number : 0
Enter a number : -2

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

9 while (i < bound)


10 {
11 sum += 1.0/++ i;
12 }
13 cout << "The sum of the first " << i << " reciprocals is " << sum << endl;
14 return 0;
15 }

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 }

The console output will be as follows.


Enter a positive integer : 100
Fibonacci Series : 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

4.3. The do...while loop


The do...while loop is a variant of the while loop with one important difference: the body of do...while
loop is executed once before the condition is checked. The syntax of the do...while statement is as follows.
do
{
// body of loop;
}
while ( condition );

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 }

The console output will be as follows.


1 2 3 4 5

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 }

The console output will be as follows.


Enter your number : 10249
The number in reverse order is: 94201
4.4. The for loop 37

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 }

The console output will be as follows.


Enter your number : 10249
The number in reverse order is: 94201

4.4. The for loop


The syntax of the for statement is as follows.
for ( initialization ; condition ; update )
{
// body of -loop
}

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 }

The console output will be as follows.


1 2 3 4 5

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 }

The console output will be as follows.


Enter a positive integer : 10
Sum = 55

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 }

The console output will be as follows.


Input a number to find the factorial : 5
The factorial of 5 is 120
4.4. The for loop 39

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 }

The console output will be as follows.


Enter the value of x: 2
Enter the number of terms: 5
2^1 + 2^2 + 2^3 + 2^4 + 2^5 = 62

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

The console output will be as follows.


Enter the number of terms: 3
Sum = 20

4.5. Nested loop


A loop within another loop is called a nested loop. That is, the inner loop is nested inside the outer loop.
Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the
data in the outer loop.

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 }

The console output will be as follows.


Week: 1
Day :1
Day :2
Day :3
Day :4
Day :5
Day :6
Day :7
Week: 2
Day :1
Day :2
Day :3
Day :4
Day :5
Day :6
Day :7
Week: 3
Day :1
Day :2
Day :3
4.5. Nested loop 41

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 }

The console output will be as follows.


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

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 }

The console output will be as follows.


42 Laboratory 4. Iteration

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 }

The console output will be as follows.


Enter number of rows: 4
* * * * * * *
* * * * *
* * *
*

4.6. Infinite loop


If the condition in a loop is always true, it runs forever (until memory is full). For example,
// infinite for loop
for (int i = 1; i > 0; i++)
{
// block of code
}
Post-laboratory Problems 43

// infinite while loop


while (true)
{
// body of the loop
}

// infinite do ... while loop


int count = 1;
do
{
// body of loop
}
while( count == 1);

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

5.3. C++ library functions


Library functions are the built-in functions in C++ programming. Programmers can use library func-
tions by invoking the functions directly; they don’t need to write the functions themselves. Some common
library functions in C++ are sqrt(), abs(), isdigit(), etc. In order to use library functions, we usually need to in-
clude the header file in which these library functions are defined. For instance, in order to use mathematical
functions such as sqrt() and abs(), we need to include the header file cmath.

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 }

The console output will be as follows.


Square root of 25 = 5

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.

5.4. C++ user-defined function


C++ allows the programmer to define their own function. A user-defined function groups code to per-
form a specific task and that group of code is given a name (identifier). When the function is invoked from
any part of the program, it all executes the codes defined in the body of the function.

5.4.1. C++ function declaration


The syntax to declare a function is as follows.
return_type function_name (parameter1 , parameter2 ,...)
{
// function body
}

Here is an example of a function declaration.


int max (int x, int y)
{
if (x < y)
return y;
else
return x;
}

5.4.2. Calling a function


In the above program, we have declared a function named max() before the main() function. To use the
max() function, we need to call it. Here’s how we can call the above max() function.
int max (int x, int y)
{
if (x < y)
return y;
else
return x;
}
int main ()
{
int m, n;
5.4. C++ user-defined function 47

cout << "Enter two integers : ";


cin >> m >> n;
cout << max(m,n) << " is the maximum ." << endl;
}

5.4.3. Function prototype


In C++, the code of function declaration should be before the function call. However, if we want to
define a function after the function call, we need to use the function prototype.

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 }

The console output will be as follows.


Enter two integers : 12 79
79 is the maximum .

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

8 for (int i=1; i <=6; i++)


9 {
10 cout << " " << fact(i);
11 }
12 cout << endl;
13 }
14
15 long fact (int n)
16 {
17 if (n < 0)
18 return 0;
19 int f = 1;
20 while (n > 1)
21 {
22 f *= n--;
23 }
24 return f;
25 }

5.5. The void function


A function needs not to return a value. In other programming languages, such a function is called a
procedure or a subroutine. In C++, such a function is identified simply by placing the keyword void where
the function’s return type would be. A type specifies a set of values. For example, the type short specifies the
set of integers from –32, 768 to 32, 768. The void type specifies the empty set. Consequently, no variable
can be declared with void type. A void function is simply one that returns no value.

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 }

The console output will be as follows.


Enter the date: 15
Enter the month: 3
Enter the year: 2021
The date is: March 15, 2021

5.6. Boolean functions


In some situations it is helpful to use a function to evaluate a condition, typically within an if statement
or a while statement. Such functions are called boolean functions. These functions can return bool values
just like any other type, which is often convenient for hiding complicated tests inside functions.

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

9 for (int n=0; n < 80; n++)


10 {
11 if ( is_prime (n))
12 cout << n << " ";
13 }
14 cout << endl;
15 }
16
17 bool is_prime (int n) // returns true if n is prime , false otherwise
18 {
19 if (n < 2)
20 return false ; // 0 and 1 are not primes
21 if (n < 4)
22 return true; // 2 and 3 are the first primes
23 if (n%2 == 0)
24 return false ; // 2 is the only even prime
25 for (int d=3; d <= sqrt(n); d += 2)
26 {
27 if (n%d == 0)
28 return false ; // n has a nontrivial divisor
29 }
30 return true; // n has no nontrivial divisors
31 }

The console output will be as follows.


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79

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 }

The console output will be as follows.


Enter a year: 2021
2021 is not a leap year.
Enter a year: 2020
2020 is a leap year.
Enter a year: 1
1 is not a leap year.

5.7. Passing arguments by value and by reference


In many programming languages, there are two ways to pass arguments — pass-by-value and pass-by-reference.
When arguments are passed-by-value, a copy of the argument’s value is made and passed to the called func-
tion. Changes to the copy do not affect an original variable’s value in the caller. When an argument is
passed-by-reference, the caller allows the called function to modify the original variable’s value.
Pass-by-value should be used whenever the called function does not need to modify the value of the
caller’s original variable. This prevents the accidental side effects (variable modifications) that so greatly
hinder the development of correct and reliable software sys- tems. Pass-by-reference should be used only
with trusted called functions that need to modify the original variable.

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 console output will be as follows.


a = 22, b = 44
a = 22, b = 99
a = 22, b = 99
52 Laboratory 5. Function

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.

5.8. Function overloading


In C++, two functions can have the same name if the number and/or type of arguments passed is differ-
ent. These functions having the same name but different arguments are known as overloaded functions. As
long as they have different parameter type lists, the compiler will regard them as different functions. To be
distinguished, the parameter lists must either contain a different number of parameters, or there must be at
least one position in their parameter lists where the types are different.

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

41 return (z > m ? z : m);


42 }

The console output will be as follows.


Enter three integers : 12 345 7890
Enter three floating point numbers : 1.23 45.76 897.235
Maximum of the first two integers is: 345
Maximum of the three integers is: 7890
Maximum of the first two floating numbers is: 45.76
Maximum of the three floating numbers is: 897.235

5.9. Default arguments (parameters)


In C++ programming, we can provide default values for function parameters. If a function with default
arguments is called without passing arguments, then the default parameters are used. However, if arguments
are passed while calling the function, the default arguments are ignored.

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 }

The console output will be as follows.


54 Laboratory 5. Function

Enter the value of x: 2.0003


Enter the value of a0 , a1 , a2 , and a3: 7 6 5 4
Considering x and a0 , the result is: 7
Considering x, a0 , and a1 , the result is: 19.0018
Considering x, a0 , a1 , and a2 , the result is: 39.0078
Considering x, a0 , a1 , a2 , and a3 , the result is: 71.0222

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.

6.2.1. Array declaration in C++


The syntax of declaring an array is as follows.
data_type array_name [ array_size ];

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.

6.2.2. Access elements in array


In C++, each element in an array is associated with a number. The number is known as an array index.
We can access elements of an array by using those indices. To refer to a particular location or element in the
array, we specify the array’s name and the array index of the particular element in the array as follows.
// syntax to access array elements
array_name [index ];
56 Laboratory 6. Arrays

First index

0 1 2 3 4 5 6 7 8 9 Array indices

-45 36 6 0 1543 -89 -6 1 79 25

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7] x[8] x[9] Array elements

Figure 6.1. Elements of an array in C++

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 .

6.2.3. Array initialization


In C++, it is possible to initialize an array during declaration. For example,
int x[10] = {-45, 36, 6, 0, 1543 , -89, -6, 1, 79, 25};

Following is another method to initialize array during declaration.


int x[] = {-45, 36, 6, 0, 1543 , -89, -6, 1, 79, 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 }

The console output will be as follows.


The numbers are: 7 5 6 12 35
6.2. Arrays 57

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 }

The console output will be as follows.


Enter 5 numbers : 12 67 -9 0 5
The numbers are: 12 67 -9 0 5

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

19 cout << " Largest element = " << arr [0];


20 return 0;
21 }

The console output will be as follows.


Enter total number of elements (1 to 100): 5

Enter Number 1 : 17
Enter Number 2 : 29
Enter Number 3 : 42
Enter Number 4 : 36
Enter Number 5 : 66
Largest element = 66

6.3. Passing array to function


In C++, we can pass arrays as an argument to a function. And, also we can return arrays from a function.
The syntax for passing an array to a function is as follows.
returnType functionName ( dataType arrayName [ arraySize ])
{
// function body
}

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

16 for (int i = 0; i < 5; ++i)


17 {
18 cout << " Student " << i + 1 << ": " << m[i] << endl;
19 }
20 }

The console output will be as follows.


Displaying marks:
Student 1: 88
Student 2: 76
Student 3: 90
Student 4: 61
Student 5: 69

6.3.1. Linear search


The simplest type of searching process is the linear search. In linear search algorithm, we compare
targeted element with each element of the array. If the element is found then its position is displayed.

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 }

The console output will be as follows.


Enter the number of elements in array: 5
Enter 5 numbers : 1 14 9 87 64
Enter a number to serach in Array: 9
Element found at index 2.

6.3.2. Bubble sort


Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if
they are in wrong order. Following is an elaborated example of the bubble sort. In this example, bubble sort
is used to arrange five numbers in ascending order.
First Pass:
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), here, the algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), swaps since 5 > 4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), swaps since 5 > 2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), since these elements are already in order (8 > 5), algorithm does not swap
them.
Second Pass:
(14258)→(14258)
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), swaps since 4 > 2
(12458)→(12458)
(12458)→(12458)
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm
needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)
(12458)→(12458)

Example 06
The following example of a C++ program utilizes the bubble sort algorithm.
1 # include <iostream >
6.4. Multidimensional arrays 61

2 using namespace std;


3
4 void bubble_sort (int array [], int size );
5 void print_array (int array [], int size );
6
7 int main ()
8 {
9 int data [] = {-2, 45, 0, 11, -9};
10 int size = sizeof (data) / sizeof (data [0]);
11 bubble_sort (data , size );
12 cout << " Sorted Array in Ascending Order: " << endl;
13 print_array (data , size );
14 }
15
16 void bubble_sort (int array [], int size)
17 {
18 for (int step =0; step <size -1; ++ step)
19 {
20 for (int i=0; i<size -step -1; ++i)
21 {
22 if (array[i] > array[i + 1])
23 {
24 int temp = array[i];
25 array[i] = array[i + 1];
26 array[i + 1] = temp;
27 }
28 }
29 }
30 }
31
32 void print_array (int array [], int size)
33 {
34 for (int i=0; i<size; ++i)
35 {
36 cout << " " << array[i];
37 }
38 cout << endl;
39 }

The console output will be as follows.


Sorted Array in Ascending Order:
-9 -2 0 11 45

6.4. Multidimensional arrays


The arrays we have used previously have all been one-dimensional. This means that they are linear, i.e.,
sequential. But the element type of an array can be almost any type, including an array type. An array of
arrays is called a multidimensional array. A one-dimensional array of one-dimensional arrays is called a
two-dimensional array, a one-dimensional array of two-dimensional arrays is called a three-dimensional
array, and so on. Data in multidimensional arrays are stored in tabular form (in row major order).
62 Laboratory 6. Arrays

Array member x[1][7]


0 1 2 3 4 5 6 7 8 9

0 34 89 -46 2 39 87 71 31 28 91

1 18 -13 -67 0 9 32 -73 53 66 100

2 -12 98 0 10 -56 87 54 15 86 28

Figure 6.2. Elements of a 2-dimensional array

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.

6.4.1. Declaration of multidimensional arrays


The syntax of declaring an array is as follows.
data_type array_name [size1 ][ size2 ]....[ sizeN ];

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

And thus, we can declare a three dimensional array as below.


int x [3][10][25];

6.4.2. Size of multidimensional arrays


Total number of elements that can be stored in a multidimensional array can be calculated by multiplying
the size of all the dimensions.
For example, the array int x[3][10] can store total (3∗10) = 30 elements. Similarly array int x[3][10][25]
can store total (3 ∗ 10 ∗ 25) = 750 elements.

6.4.3. Initialization of multidimensional arrays


We can initialize a two-dimensional array as follows.
int test [2][3] = { {2, 4, 5}, {9, 0, 19}};
6.4. Multidimensional arrays 63

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 }

The console output will be as follows.


Enter 15 integers (5 per row ):
Row 0: 9 7 5 3 1
Row 1: 2 4 6 8 0
Row 2: 1 2 8 9 5
You have entered the following integers :
9 7 5 3 1
2 4 6 8 0
1 2 8 9 5

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

24 cout << endl;


25 }
26 }
27 for (int i = 0; i < row; ++i)
28 {
29 for (int j = 0; j < column ; ++j)
30 {
31 transpose [j][i] = a[i][j];
32 }
33 }
34 cout << endl << " Transpose of Matrix : " << endl;
35 for (int i = 0; i < column ; ++i)
36 {
37 for (int j = 0; j < row; ++j)
38 {
39 cout << " " << transpose [i][j];
40 if (j == row - 1)
41 cout << endl;
42 }
43 }
44 }

The console output will be as follows.


Enter rows and columns of matrix : 3 4
Enter elements of matrix :
Enter element a11: 1
Enter element a12: 3
Enter element a13: 4
Enter element a14: 2
Enter element a21: 5
Enter element a22: 7
Enter element a23: 9
Enter element a24: 6
Enter element a31: 8
Enter element a32: 0
Enter element a33: 3
Enter element a34: 1

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

1 # include <iostream >


2 using namespace std;
3
4 int num_zeros (int a[][4][3] , int n1 , int n2 , int n3);
5
6 int main ()
7 {
8 int a [2][4][3] = {
9 { {5, 0, 2}, {0, 0, 9}, {4, 1, 0}, {7, 7, 7} },
10 { {3, 0, 0}, {8, 5, 0}, {0, 0, 0}, {2, 0, 9} }
11 };
12 cout << "This array has " << num_zeros (a ,2 ,4 ,3) << " zeros." << endl;
13 }
14
15 int num_zeros (int a[][4][3] , int n1 , int n2 , int n3)
16 {
17 int count = 0;
18 for (int i = 0; i < n1; i++)
19 {
20 for (int j = 0; j < n2; j++)
21 {
22 for (int k = 0; k < n3; k++)
23 {
24 if (a[i][j][k] == 0)
25 ++ count ;
26 }
27 }
28 }
29 return count;
30 }

The console output will be as follows.


This array has 11 zeros.

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

double stdev ( double x[], int n);

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.

7.2.1. Address-of operator (&)


The address of a variable can be obtained by preceding the name of a variable with an ampersand sign
(&), known as address-of operator. For example,
khulna = & dhaka;

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

20020 20021 20022 20023 20024 (memory)


... ... ... 19 ... ... ...
dhaka
&

19 20022
sylhet khulna

Figure 7.1. The address-of operator (&)

7.2.2. Dereference operator (∗)

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

Figure 7.2. The dereference operator

7.2.3. Pointer declaration

The syntax of declaring a pointer is as follows.

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 }

The console output will be as follows.


var = 5
&var = 0 x7ffced7ef74c
pointVar = 0 x7ffced7ef74c
* pointVar = 5

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 }

The console output will be as follows.


var = 5
* point_var = 5

Changing value of var to 7:


var = 7
* point_var = 7
72 Laboratory 7. Pointers

Changing value of * point_var to 16:


var = 16
* point_var = 16

7.3. Pointers and arrays


The concept of arrays is related to that of pointers. Pointers are variables that hold addresses of other
variables. Not only can a pointer store the address of a single variable, it can also store the address of cells
of an array. Consider the following example.
int *ptr;
int arr [5];
ptr = arr;

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

The console output will be as follows.


The numbers are: 10 20 30 40 50

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 }

The console output will be as follows.


Enter 5 numbers : 12 23 34 45 56
Displaying data:
12
23
34
45
56

7.3.1. Dynamic arrays


A dynamic array is quite similar to a regular array, but its size is modifiable during program runtime.
DynamArray elements occupy a contiguous block of memory. Once an array has been created, its size cannot
be changed. However, a dynamic array is different. A dynamic array can expand its size even after it has
been filled. The syntax of declaring a dynamic array is as follows.
pointer_variable = new data_type ;

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

1 # include <iostream >


2 using namespace std;
3 int main ()
4 {
5 int x, n;
6 cout << "How many numbers will you type?" << endl;
7 cin >> n;
8 int *arr = new int(n);
9 cout << "Enter " << n << " numbers :" << endl;
10 for (x = 0; x < n; x++)
11 {
12 cin >> arr[x];
13 }
14 cout << "You typed: ";
15 for (x = 0; x < n; x++)
16 {
17 cout << arr[x] << " ";
18 }
19 cout << endl;
20 delete [] arr;
21 return 0;
22 }

The console output will be as follows.


How many numbers will you type? 5
Enter 5 numbers :
11 22 33 44 55
You typed: 11 22 33 44 55

7.4. Pointers to functions


Like an array name, a function name is actually a constant pointer. You can think of its’ value as the
address of the code that implements the function. A pointer to a function is simply a pointer whose value is
the address of the function name. Since that name is itself a pointer, a pointer to a function is just a pointer
to a constant pointer.
The value of function pointers is that they help to define functions of functions. This is done by passing
a function pointer as a parameter to another function.

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 }

The console output will be as follows.


The result is: 17

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 }

The console output will be as follows.


Before swapping
a = 10
b = 20

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

Write and run a C++ program to test the above function.


Laboratory 8

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

Figure 8.1. Memory Diagram

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.

8.2.1. Initialization of C-strings

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 }

The console output will be as follows.


s[0] = A
s[1] = U
s[2] = S
s[3] = T
s[4] =

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 }

The console output will be as follows.


The default string is: Dhaka
Enter a string not more than 7 characters : Bangladesh
You entered : Bangla

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.

8.2.2. Standard C-string Functions

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 }

The console output will be as follows.


Length of string a: 7
Length of string b: 7
Enter string : Bangladesh
Length of the entered string : 10

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 console output will be as follows.


Before strcpy (S1 , S2)
Content of S1: ABCDEFGH
Length of S1: 8
Content of S2: xyz
Length of S2: 3

After strcpy (S1 , S2)


Content of S1: xyz
Length of S1: 3
Content of S2: xyz
Length of S2: 3
80 Laboratory 8. Strings

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

Figure 8.2. Illustration of Example 04

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 }

The console output will be as follows.


Before strncpy (S1 , S2 , n)
Content of S1: ABCDEFGH
Length of S1: 8
Content of S2: xyz
Length of S2: 3

After strncpy (S1 , S2 , n)


Content of S1: xyCDEFGH
8.2. C-strings 81

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

Figure 8.3. Illustration of Example 05

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 }

The console output will be as follows.


Before strcat (S1 , S2)
Content of S1: ABCDEFGH
Length of S1: 8
Content of S2: xyz
82 Laboratory 8. Strings

Length of S2: 3

After strcat (S1 , S2)


Content of S1: ABCDEFGHxyz
Length of S1: 11
Content of S2: xyz
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

Figure 8.4. Illustration of Example 06

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 console output will be as follows.


Before strncat (S1 , S2 , n)
Content of S1: ABCDEFGH
Length of S1: 8
Content of S2: xyz
Length of S2: 3

After strncat (S1 , S2 , n)


Content of S1: ABCDEFGHxy
Length of S1: 10
Content of S2: xyz
Length of S2: 3

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

Figure 8.5. Illustration of Example 07

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 }

The console output will be as follows.


strcmp (S1 , S2) = -32
strcmp (S2 , S3) = 32
strcmp (S3 , S1) = 0

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 }

The console output will be as follows.


Barishal
Chittagong
Dhaka
Khulna
Rajshahi
Rangpur
Mymensingh
Sylhet

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

7 for( ; *str2; p++, str2 ++)


8 {
9 *p=* str2;
10 }
11 *p= NULL;
12 return str1;
13 }
14 int main ()
15 {
16 char S1[] = " ABCDEFGH ", S2[] = "xyz" ;
17 cout << " Before stringcopy (S1 , S2)" << endl;
18 cout << " Content of S1: " << S1 << endl;
19 cout << " Length of S1: " << strlen (S1) << endl;
20 cout << " Content of S2: " << S2 << endl;
21 cout << " Length of S2: " << strlen (S2) << endl << endl;
22 stringcopy (S1 , S2);
23 cout << "After stringcopy (S1 , S2)" << endl;
24 cout << " Content of S1: " << S1 << endl;
25 cout << " Length of S1: " << strlen (S1) << endl;
26 cout << " Content of S2: " << S2 << endl;
27 cout << " Length of S2: " << strlen (S2) << endl;
28 }

The console output will be as follows.


Before stringcopy (S1 , S2)
Content of S1: ABCDEFGH
Length of S1: 8
Content of S2: xyz
Length of S2: 3

After stringcopy (S1 , S2)


Content of S1: xyz
Length of S1: 3
Content of S2: xyz
Length of S2: 3

8.3. Standard C++ Strings


The classic C-strings described in the previous section are an important part of C++. They provide a
very efficient means for fast data processing. However, as with ordinary arrays, the efficiency of C-strings
comes at a price - the risk of run-time errors, resulting primarily from their dependency upon the use of
the NULL character as a string terminator. Standard C++ strings provide a safe alternative to C-strings. By
encapsulating the length of the string with the string itself, there is no direct reliance on string terminators.
Standard C++ defines its string type in the <string> header file. Objects of type string can be declared
and initialized in several ways:
string s1; // s1 contains 0 characters
string s2 = " Chittagong "; // s2 contains 8 characters
string s3 (60, ’*’); // s3 contains 60 asterisks
string s4 = s3; // s4 contains 60 asterisks
string s5(s2 , 4, 2); // s5 is the 2- character string "ta"
86 Laboratory 8. Strings

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 }

The console output will be as follows.


The small string has 15 characters .
The large string has 38 characters .

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 }

The console output will be as follows.


Enter an string with lowercase characters : Hello World.
After transforming into uppercase characters : HELLO WORLD.

Example 13
The following example of a C++ program compares two strings.
1 # include <iostream >
2 # include <string >
8.3. Standard C++ Strings 87

3 using namespace std;


4 int main( )
5 {
6 string my_name = " Kishor ";
7 string user_name ;
8 while (true)
9 {
10 cout << "Enter your name (or ’quit ’ to exit ): ";
11 getline (cin , user_name );
12 if ( user_name == "Musa")
13 {
14 cout << "Hi , Musa! Welcome back!" << endl;
15 }
16 else if ( user_name == "quit")
17 {
18 cout << endl;
19 break;
20 }
21 else if ( user_name != my_name )
22 {
23 cout << "Hello , " << user_name << "!" << endl;
24 }
25 else
26 {
27 cout << "Oh , its you , " << my_name << "!" << endl;
28 }
29 }
30 }

The console output will be as follows.


Enter your name (or ’quit ’ to exit ): Kishor
Oh , its you , Kishor !
Enter your name (or ’quit ’ to exit ): Musa
Hi , Musa! Welcome back!
Enter your name (or ’quit ’ to exit ): Robin
Hello , Robin!
Enter your name (or ’quit ’ to exit ): quit

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

6 string firstname , middlename , lastname , fullname ;


7 cout << "Enter your first name: ";
8 getline (cin , firstname );
9 cout << "Enter your middle name: ";
10 getline (cin , middlename );
11 cout << "Enter your last name: ";
12 getline (cin , lastname );
13 fullname = firstname + " " + middlename + " " + lastname ;
14 cout << "Your full name: " << fullname << endl;
15 fullname += ", BSc in EEE.";
16 cout << "Your full name and qualification : " << fullname << endl;
17 }

The console output will be as follows.


Enter your first name: Kazi
Enter your middle name: Nazrul
Enter your last name: Islam
Your full name: Kazi Nazrul Islam
Your full name and qualification : Kazi Nazrul Islam , BSc in EEE.

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 }

The console output will be as follows.


Position of first we: 5
Position of second we: 8
Position of third we: 28
Position of c: 16
Post-laboratory Problems 89

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

Structures and Classes

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.

9.2.1. Declaring and defining a structure in C++


The struct keyword defines a structure type followed by an identifier (name of the structure). Then
inside the curly braces, you can declare one or more members (declare variables inside curly braces) of that
structure. For example,
struct Bank
{
string name;
int number ;
double balance ;
};

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

9.2.2. Accessing members of a structure


The members of structure object is accessed using a dot (.) operator. Suppose, you want to access balance
of the object account and assign a value of 50.5 to it. You can perform this task by using following code below.
Bank account ;
account . balance = 50.5;

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 }

The console output will be as follows.


Enter Full name: Musa Aman
Enter account number : 01020304
Enter account balance : 50.5

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.

9.2.3. Structure to function (Passing by value)


Here, you can pass structure object as an argument to a function similar to passing a variable.
9.2. Structure 93

Example 02
The following example of a C++ program demonstrates to pass any structure to a function by the Passing
by Value 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 Bank get_data (Bank );
11 void display_data (Bank );
12 int main ()
13 {
14 Bank account ;
15 account = get_data ( account );
16 display_data ( account );
17 return 0;
18 }
19 Bank get_data (Bank account )
20 {
21 cout << "Enter Full name: ";
22 getline (cin , account .name );
23 cout << "Enter account number : ";
24 cin >> account . number ;
25 cout << "Enter account balance : ";
26 cin >> account . balance ;
27 return account ;
28 }
29 void display_data (Bank account )
30 {
31 cout << endl << " Displaying Information ." << endl;
32 cout << "Full name: " << account .name << endl;
33 cout << " Account number : " << account . number << endl;
34 cout << " Account balance : " << account . balance << " BDT";
35 }

The console output will be as follows.

Enter Full name: Musa Aman


Enter account number : 01020304
Enter account balance : 50.5

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.

9.2.4. Structure to function (Passing by reference)


In passing by reference, the address of a structure object is passed to a function. In this, if we change
the object which is inside the function, the original structure object which is used for calling the function
changes. This was not the case in calling by value.

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 }

The console output will be as follows.


Enter name: Kishor
Enter account number : 010809
Enter account balance : 12000

Displaying Information .
Name: Kishor
9.2. Structure 95

Account number : 10809


Account balance : 12000

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.

9.2.5. Array of structures


You can also make an array of structures. Since structures are types, they can also be used as the type of
arrays to construct tables or databases of them.

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 }

The console output will be as follows.


Enter name: Kishor
96 Laboratory 9. Structures and Classes

Enter account number : 001


Enter account balance : 11000.50
Enter name: Musa
Enter account number : 002
Enter account balance : 22000.75
Enter name: Robin
Enter account number : 003
Enter account balance : 33000.25
.
.
.
.
.
.
.

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.

9.3.1. Declaring and defining a class in C++


A class is defined in C++ using keyword class followed by the name of the class. The body of the class is
defined inside the curly brackets and terminated by a semicolon at the end. For example,
class Rectangle
{
9.3. Class 97

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.

9.3.2. Accessing members of a class


The members of class object is accessed using a dot (.) operator. Suppose, you want to access the meme-
ber set_length( ) of the object rect and pass a value of 7 to it. You can perform this task by using following
code below.
Rectangle rect;
rect. set_length (7);

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 }

The console output will be as follows.


Area of the rectangle : 28

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 }

The console output will be as follows.


Area of the rectangle : 28

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.

9.3.4. Overloading constructors


Like any other function, a constructor can also be overloaded with diferent versions taking diferent
parameters: with a diferent number of parameters and/or parameters of diferent types. The compiler will
automatically call the one whose parameters match the arguments.

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 }

The console output will be as follows.


Area of the rectangle A: 28
Area of the rectangle B: 20
Area of the rectangle C: 30

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

d) Test your program using the following Roman numerals:


i. MCXIV
ii. CCCLIX
iii. MDCLXVI.
2. Write and run a C++ program to design and implement a class day_type that implements the day of the
week in a program. The class day_type should store the day, such as, Sun for Sunday. The program
should be able to perform the following operations on an object of type day_type.
a) Set the day.
b) Print the day.
c) Return the day.
d) Return the next day.
e) Return the previous day.
f) Calculate and return the day by adding certain days to the current day. For example, if the current
day is Monday and we add 4 days, the day to be returned is Friday. Similarly, if today is Tuesday and
we add 13 days, the day to be returned is Monday.
g) Add the appropriate constructors.
3. Write and run a C++ program to implement a Time class. Each object of this class will represent a
specific time of day, storing the hours, minutes, and seconds as integers. Include a constructor, access
functions, a function advance(int h, int m, int s) to advance the current time of an existing object, a
function reset(int h, int m, int s) to reset the current time of an existing object, and a print( ) function.
Laboratory 10

File I/O and Vector

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.

10.2. File I/O


When a program runs, the data is in the memory but when it ends or the computer shuts down, it gets
lost. To keep data permanently, we need to write it in a file. For this purpose, we will use fstream, which
is another C++ standard library like iostream and is used to read and write on files. Following are the data
types used for file handling from the fstream library.

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.

10.2.1. Creating and opening a file


We need to tell the computer the purpose of opening the file, e.g., to write on the file, to read from the
file, etc. Following are the different modes in which we can open a file.

Table 10.2. Modes for opening the file


Mode Description
ios::app opens a text file for appending. (appending means to add text at the end).
ios::ate opens a file for output and move the read/write control to the end of the file.
ios::in opens a text file for reading.
ios::out opens a text file for writing.
ios::trunc truncates the content before opening a file, if file exists.

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

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 :: out | ios ::in );
9 cout << "Write text to be written on file:" << endl;
10 cin. getline (text , sizeof (text ));
11 file << text << endl; // Writing on file
12 file >> text; // Reading from file
13 cout << endl << "The written text is:" << endl;
14 cout << text << endl;
15 file.close ();
16 return 0;
17 }

The console output will be as follows.


Write text to be written on file:
Ahsanullah University of Science and Technology

The written text is:


Ahsanullah University of Science and Technology

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 }

The console output will be as follows.


10.3. Vector 105

Write the text to be added on the file ::


Dhaka , Bangladesh

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.

10.3.1. Declaration of vector


The declaration syntax of vector is the same as that of array, with the difference that you do not need to
specify the array length along with the data type as shown below.
vector <datatype > array_name ;

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

vector <int > marks;

10.3.2. Initialization of vector


The initialization of an vector is also the same as that of array. We initialize an vector by the following
way.
vector <int > marks = {50, 45, 47, 65, 80};

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.

10.3.3. Functions associated with the vector

Table 10.3. Iterator related functions associated with the vector


Function Description
begin() Returns an iterator pointing to the first element in the vector
end() Returns an iterator pointing to the theoretical element that follows the last element
in the vector
rbegin() Returns a reverse iterator pointing to the last element in the vector (reverse
beginning). It moves from last to first element
rend() Returns a reverse iterator pointing to the theoretical element preceding the first
element in the vector (considered as reverse end)
cbegin() Returns a constant iterator pointing to the first element in the vector.
cend() Returns a constant iterator pointing to the theoretical element that follows the last
element in the vector.
crbegin() Returns a constant reverse iterator pointing to the last element in the vector (reverse
beginning). It moves from last to first element
crend() Returns a constant reverse iterator pointing to the theoretical element preceding the
first element in the vector (considered as reverse end)

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

9 v1. push_back (i);


10 }
11 cout << " Output of begin and end: \t";
12 for (auto i = v1.begin (); i != v1.end (); ++i)
13 {
14 cout << *i << " ";
15 }
16 cout << endl << " Output of cbegin and cend: \t";
17 for (auto i = v1. cbegin (); i != v1.cend (); ++i)
18 {
19 cout << *i << " ";
20 }
21 cout << endl << " Output of rbegin and rend: \t";
22 for (auto ir = v1. rbegin (); ir != v1.rend (); ++ir)
23 {
24 cout << *ir << " ";
25 }
26 cout << endl << " Output of crbegin and crend: \t";
27 for (auto ir = v1. crbegin (); ir != v1.crend (); ++ir)
28 {
29 cout << *ir << " ";
30 }
31 return 0;
32 }

The console output will be as follows.


Output of begin and end: 1 2 3 4 5
Output of cbegin and cend: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
Output of crbegin and crend: 5 4 3 2 1

Table 10.4. Capacity related functions associated with the vector


Function Description
size() Returns the number of elements in the vector.
max_size() Returns the maximum number of elements that the vector can hold.
capacity() Returns the size of the storage space currently allocated to the vector
expressed as number of elements.
resize(n) Resizes the container so that it contains ‘n’ elements.
empty() Returns whether the container is empty.
shrink_to_fit() Reduces the capacity of the container to fit its size and destroys all
elements beyond the capacity.
reserve() Requests that the vector capacity be at least enough to contain n elements.

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 }

The console output will be as follows.

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

1 #include <iostream >


2 # include <vector >
3 using namespace std;
4 int main ()
5 {
6 vector <int > v1;
7 for (int i = 1; i <= 10; i++)
8 {
9 v1. push_back (i*10);
10 }
11 cout << endl << " Reference operator [v] : v1 [2] = " << v1 [2];
12 cout << endl << "at : v1.at (4) = " << v1.at (4);
13 cout << endl << "front () : v1.front () = " << v1.front ();
14 cout << endl << "back () : v1.back () = " << v1.back ();
15 int* pos = v1.data ();
16 cout << endl << "The first element is " << *pos;
17 return 0;
18 }

The console output will be as follows.


Reference operator [v] : v1 [2] = 30
at : v1.at (4) = 50
front () : v1.front () = 10
back () : v1.back () = 100
The first element is 10

Table 10.6. Modifier related functions associated with the vector


Function Description
assign() It assigns new value to the vector elements by replacing old ones
push_back() It push the elements into a vector from the back
pop_back() It is used to pop or remove elements from a vector from the back.
insert() It inserts new elements before the element at the specified position
erase() It is used to remove elements from a container from the specified position
or range.
swap() It is used to swap the contents of one vector with another vector of same
type. Sizes may differ.
clear() It is used to remove all the elements of the vector container
emplace() It extends the container by inserting new element at position
emplace_back() It is used to insert a new element into the vector container, the new
element is added to the end of the vector

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

6 vector <int > v;


7 v. assign (5, 10);
8 cout << "The vector elements are: ";
9 for (int i = 0; i < v.size (); i++)
10 {
11 cout << v[i] << " ";
12 }
13 v. push_back (15);
14 int n = v.size ();
15 cout << endl << "The last element is: " << v[n - 1];
16 cout << endl << "The vector elements are: ";
17 for (int i = 0; i < v.size (); i++)
18 {
19 cout << v[i] << " ";
20 }
21 v. pop_back ();
22 cout << endl << "The vector elements are: ";
23 for (int i = 0; i < v.size (); i++)
24 {
25 cout << v[i] << " ";
26 }
27 v. insert (v.begin (), 5);
28 cout << endl << "The first element is: " << v[0];
29 v.erase(v.begin ());
30 cout << endl << "The first element is: " << v[0];
31 v. emplace (v.begin (), 15);
32 cout << endl << "The first element is: " << v[0];
33 v. emplace_back (20); n = v.size ();
34 cout << endl << "The last element is: " << v[n - 1];
35 v.clear ();
36 cout << endl << " Vector size after erase (): " << v.size ();
37 return 0;
38 }

The console output will be as follows.


The vector elements are: 10 10 10 10 10
The last element is: 15
The vector elements are: 10 10 10 10 10 15
The vector elements are: 10 10 10 10 10
The first element is: 5
The first element is: 10
The first element is: 15
The last element is: 20
Vector size after erase (): 0

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 }

The console output will be as follows.


Unsorted : 1 5 8 9 6 7 3 4 2 0
Sorted : 0 1 2 3 4 5 6 7 8 9
Sorted Descending : 9 8 7 6 5 4 3 2 1 0

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 }

The console output will be as follows.


a b c d e f
2004 9 20.5 8.8 0 37.4
2005 10 13.6 4.2 5 77.8
2006 11 11.8 4.7 3 45.5
2007 12 7.7 0.1 17 65.1
2008 11 7.3 0.8 14 74.6
2009 9 6.5 0.1 13 3.3

========== READING VECTOR ========


2004 9 20.5 8.8 0 37.4
2005 10 13.6 4.2 5 77.8
2006 11 11.8 4.7 3 45.5
2007 12 7.7 0.1 17 65.1
2008 11 7.3 0.8 14 74.6
2009 9 6.5 0.1 13 3.3

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.

You might also like