Unit 1-5
Unit 1-5
PROGRAMMING
USING C++
DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION
UNIVERSITY OF DELHI UNIVERSITY OF DELHI
Introduction to Programming Using C++
Editors
Prof. Ajay Jaiswal
Content Writers
Dr. Deepali Bajaj, Seema
Dr. Anuradha Singhal
.
Academic Coordinator
Mr. Deekshant Awasthi
Published by:
Department of Distance and Continuing Education
Campus of Open Learning/School of Open Learning,
University of Delhi, Delhi-110 007
Printed by:
School of Open Learning, University of Delhi
Printed at: Vikas Publishing House Pvt. Ltd. Plot 20/4, Site-IV, Industrial Area Sahibabad, Ghaziabad - 201 010 (1200 Copies)
SYLLABUS
Introduction to Programming Using C++
Syllabus Mapping
CONTENTS
1.9 Summary
1.10 Glossary
1.11 Answers to In-Text Questions
1.12 Self-Assessment Questions
1.13 References
1.14 Suggested Reading
2.7 Glossary
2.8 Answers to In-Text Questions
2.9 Self-Assessment Questions
2.10 References
2.11 Suggested Reading
7.9 Summary
7.10 Glossary
7.11 Answers to In-Text Questions
7.12 Self-Assessment Questions
7.13 References
7.14 Suggested Readings
LESSON 1 NOTES
INTRODUCTION TO OOP
A computer needs step-wise instructions to perform any action. The set of instructions
that tells the computer what to do is called a Program. The process of writing a program
in a computer language is called Programming. Each programming language has its
own specific rules. The evolution of programming has made it easier for programmers
to write and understand powerful application programs.
The evolution of programming languages can be categorized into several generations
or phases. Each generation represents advancements and new concepts introduced in
programming languages. Here is an overview of the different generations of
programming languages:
1. First Generation (Machine Language): The first programming languages
Self-Instructional
4 Material were machine languages, which directly corresponded to the binary instructions
understood by computers. They were difficult to write and understand, as they NOTES
involved low-level instructions specific to the computer architecture.
2. Second Generation (Assembly Language): Assembly languages provided
a more human-readable representation of machine language instructions. They
used mnemonic codes and symbols to represent the machine instructions, making
programming slightly more accessible.
3. Third Generation (Procedural Languages): The third generation brought
the concept of high-level programming languages, such as FORTRAN (1957),
COBOL (1959), and ALGOL (1958). These languages introduced concepts
like variables, loops, conditionals, and subroutines. They focused on algorithmic
and procedural programming and offered more abstraction from the underlying
machine.
4. Fourth Generation (Domain-Specific Languages): Fourth-generation
languages (4GL) were designed to address specific domains or problem areas.
They aimed to provide higher-level abstractions and simplify the programming
process for specific tasks like database management, report generation, and
data analysis. Examples of fourth-generation languages include SQL (Structured
Query Language) and MATLAB.
5. Fifth Generation (Logic Programming): The fifth generation involved the
development of logic programming languages, which focused on declarative
programming. Prolog (1972) is a notable example. These languages use formal
logic to specify problems and solutions, rather than traditional procedural or
imperative approaches. The introduction of Object-Oriented Programming
(OOP) languages, such as Smalltalk (1972) and C++ (1983), brought a
paradigm shift. OOP emphasizes organizing code around objects, encapsulation,
inheritance, and polymorphism. It enables modular, reusable, and extensible
code, making it easier to manage complex systems. Scripting languages like
Perl (1987), Python (1991), and Ruby (1995) gained popularity due to their
ease of use and rapid development capabilities. These languages are often
interpreted, allowing for dynamic and flexible programming. They excel in tasks
like web development, automation, and scripting.
Self-Instructional
Material 5
NOTES
1.3 TRANSLATOR PROGRAM
As you know, a computer can understand only machine language, so programs written
in any other language have to be converted into machine language. The translator
program is used to convert source language programs into machine language programs.
A program written in a high-level language is called the source program or source
code whereas a program converted into machine language by a translator program is
called Object program or Object code as shown in Figure 1.1.
A translator is a program that converts source code into machine code. Generally,
there are three types of translators: assemblers, interpreters, and compilers.
Assembler: An assembler is a program that translates assembly language code
into machine code.
Interpreter: An interpreter is a software program that translates source code
written in a high-level programming language into low-level language. It reads
the source code line by line, interprets each line, and executes the corresponding
instructions in real time.
Compiler: A compiler is a program that translates source code written in a
high-level programming language into machine code. It translates the whole
program at once. It generates the object code for the program along with a list
of errors (if any). The execution speed of the compiler is faster as compared to
the interpreter.
The high-level programming languages are broadly categorized into two
categories:
(1) Procedure-Oriented programming (POP) language
Self-Instructional
6 Material (2) Object-Oriented programming (OOP) language
NOTES
1.4 PROCEDURE-ORIENTED PROGRAMMING
NOTES 3. Global Data: Procedure-oriented languages often use global data, which can
be accessed and modified by multiple procedures as shown in Figure 1.2. Global
data provides a way to share information between procedures, but it can make
the code more complex and harder to manage as the program grows.
4. Emphasis on Algorithms and Logic: Procedure-oriented programming focuses
on defining algorithms and logical steps to solve a problem. The code is typically
organized around sequences of statements, loops, and conditionals to control
the flow of execution.
5. Lack of Data Abstraction: Procedure-oriented languages often lack strong
mechanisms for data abstraction and encapsulation. Data and procedures are
treated separately, and there is less emphasis on Modelling real-world entities
as objects. This can make it harder to manage and reuse code in larger programs.
6. Procedural Flow: The program’s execution follows a linear and procedural
flow. Statements are executed one after another, and the flow can be altered
using control structures such as loops and conditionals.
7. Limited Code Reusability: In procedure-oriented programming, code
reusability is typically achieved by creating reusable procedures or functions.
However, the reuse is limited to the procedures themselves, and sharing data
between procedures can lead to code dependencies and potential issues.
8. Efficient Resource Utilization: Procedure-oriented languages are generally
optimised for memory and performance. These languages regulate system
resources at the hardware level.
Here, we will study the meaning and benefits of using Object-Oriented programming
along with the reasons of its popularity.
1.5.1 Introduction
Self-Instructional
10 Material
There are several significant reasons why object-oriented programming has become
the dominant programming paradigm over the past two decades. A few of them are
given below:
1. Object-oriented programming scales very well, from the simplest to the most
complex problems.
2. It provides a form of abstraction that resonates with the methods people use to
solve commonplace problems.
3. OOP provides a scalable approach to system development. It enables the
decomposition of complex systems into smaller, manageable objects, allowing
large-scale systems to be built with greater ease and maintainability.
4. OOP promotes flexibility to enable code to be written in a way that handles
various object types without explicitly knowing their specific implementation. Self-Instructional
Material 11
NOTES 5. There are a growing number of libraries that facilitate the creation of applications
for numerous domains.
6. OOP aligns well with the design and development of graphical user interfaces
(GUIs).
7. Object-oriented programming is the most recent proposed solution to help and
solve the software crisis.
1.6.1 Class
A class is an abstract data type that has been defined by the user. It is made up of data
members and member functions that may be accessed and used by instantiating the
class. It indicates the collection of attributes or methods shared by all objects of the
Self-Instructional same type. A class is similar to an object’s blueprint.
12 Material
For Example: Consider the Class of Cars. There may be many cars with different NOTES
names and brands but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and
wheels, speed limits, and mileage are its properties.
1.6.2 Object
1.6.4 Encapsulation
Encapsulation is the process of enclosing data in a single unit. It is the mechanism that
connects code and the data that it manipulates. Encapsulation means that a class’
variables or data remain hidden from other classes and can only be accessed through
member function of the class in which they are specified as shown in Figure 1.5.
Because the data in a class is hidden from other classes, it is sometimes referred to as
data hiding.
Self-Instructional
14 Material Fig. 1.5 Encapsulation in OOP
1.6.5 Inheritance
Self-Instructional
Material 15
Having a variety of different forms is what is meant by the term polymorphism. The
capacity of a message to be presented in more than one form is an example of
polymorphism, which we can explain using more straightforward language. For instance,
one person can simultaneously exhibit a variety of qualities just like a man fulfils the
roles of father, spouse, and worker. Therefore, a person can behave differently
depending on the circumstances he is in. This phenomenon is known as polymorphism.
Figure 1.7 shows an example of polymorphism. Animal class can have different types
of animals that exhibit different properties but still belongs to same class, i.e., Animal
class.
Self-Instructional
16 Material
OOP provides a clear structure to the programs. It makes the code easier to maintain,
modify and debug. OOP makes it possible to create full reusable applications with less
code and shorter development time. Following are the reasons that promote the use of
OOP:
To make it easier to create projects and keep them running.
To offer the ability to hide info, which is good for security.
To solve problems that happen in the real world.
Promotes code reusability.
Avoids repeatedly re-writing the code.
In-Text Questions
1. Which of the following is NOT a fundamental principle of OOP?
a) Encapsulation b) Inheritance
c) Abstraction d) Compilation
2. What is the process of creating a new object from an existing object called?
a) Inheritance b) Encapsulation Self-Instructional
c) Polymorphism d) Copying Material 17
Self-Instructional
18 Material
Self-Instructional
Material 19
NOTES
1.9 SUMMARY
8. OOP benefits include code reuse, modularity, extensibility, adaptability, and NOTES
code organisation. Better software design, developer cooperation, and scalable
codebases are possible with it.
1.10 GLOSSARY
1. d) Compilation
2. d) Copying
3. a) Objects Self-Instructional
Material 21
NOTES 4. c) Polymorphism
5. a) Code reusability
6. d) Inheritance
Q1. What is object-oriented programming (OOP), and what are its key principles?
Q2. Explain the concept of encapsulation in OOP and provide an example.
Q3. What is the difference between a class and an object in OOP? Provide a brief
explanation.
Q4. Describe the concept of inheritance in OOP and provide an example to illustrate
it.
Q5. What is polymorphism in OOP? Explain the difference between compile-time
polymorphism and runtime polymorphism.
Q6. Describe the benefits of using OOP in software development.
1.13 REFERENCES
Self-Instructional
22 Material
Barbara, Stanley B. Lippman Josée Lajoie, and E. Moo. “C++ Primer.” (2013).
Meyers, Scott. Effective C++: 55 specific ways to improve your programs
and designs. Pearson Education, 2005.
McLaughlin, Brett, Gary Pollice, and David West. Head First Object-Oriented
Analysis and Design: A Brain Friendly Guide to OOA&D. “ O’Reilly Media,
Inc.”, 2007.
https://www.learncpp.com/
http://www.cplusplus.com/doc/tutorial/oop/
https://www.programiz.com/cpp-programming/object-oriented-programming
Self-Instructional
Material 23
LESSON 2 NOTES
NOTES
2.1 LEARNING OBJECTIVES
To familiarize students with the basic syntax and structure of C++ programs
To explain the terminology related to C++ like variable, token, identifier and
constant
To describe the usage of various data types and introduction to operators
Here, we will study the terms used in C++ such as tokens, keywords, identifiers,
variables and constants.
2.3.1 Tokens
As in the English language, in a paragraph, all the words, punctuation marks, and
blank spaces are called Tokens, all the C++ statements having Keywords, Identifiers,
Constants, Strings, Operators, and Special Symbols in a C++ program are also called
C++ Tokens. C++ Tokens are an essential part of a C++ compiler and are very useful
in C++ programming. A Token is an individual entity of a C++ program.
For example, some C++ Tokens used in a C++ program are as follows:
Reserve words: long, do, if, else etc.
Identifiers: Pay, salary etc.
Constant: 470.6,16,49 etc.
Strings: “Dinesh”, “2013-01” etc.
When a language is defined, one has to design a set of instructions to be used for
communicating with the computer to carry out specific operations. The words that are
Self-Instructional
used in programming language for special purpose are called keywords. These are
28 Material
also known as reserved words of the language. They have a specific meaning for the NOTES
C++ compiler and should be used for giving specific instructions to the computer.
These words cannot be used for any other purpose, such as naming a variable. C++ is
a case-sensitive language and it requires that all keywords be in lowercase. C++
keywords are shown in Figure 2.1.
2.3.3 Identifiers
Identifiers refer to the name of the variable, functions, array, class, etc., that are defined
by the programmer. Each language has its own rule for naming the identifiers. The
following rules are common for both C and C++:
1. Only alphabetic characters, digits and underscore are permitted.
2. The name can not start with a digit.
3. Upper case and lower case letters are distinct.
4. A declared keyword can not be used as a variable name.
5. An identifier must be unique in a program.
Self-Instructional
Material 29
Po178_ddm //valid
_78hhvt4 //valid
902gt1 //invalid as it starts with a digit
Tyy;ui8 //invalid as it contains the ‘;’ character
for //invalid as it is a C++ keyword
Fg026 neo //invalid as it contains space
2.3.4 Variable
A variable is a named area in memory used to store values during program execution.
A variable has a symbolic name and can be given a variety of values. When a variable
is given a value, that value is actually placed in the memory space assigned to the
variable. It is required to declare variables before they can be used. The general form
of a declaration is:
type variable_list;
Here, type must be a valid data type plus any modifiers and variable_list may consist
of one or more identifier names separated by commas. Here are some declarations:
int i, j, l;
short int si;
unsigned int ui;
double balance, profit, loss;
2.3.5 Constants
Constants refer to fixed values that the program cannot alter. Constants can be of any
of the basic datatypes. The way each constant is represented depends upon its type.
Constants are also called literals.
We can use keyword ‘const’ prefix to declare constants with a specific type as follows:
const type variable Name = value;
For example,
Self-Instructional const int LENGTH = 10;
30 Material
NOTES
2.4 DATA TYPES
A data type defines the size and type of values that a variable can store along with the
set of operations that can be performed on that variable. For example, a Boolean
variable can have Boolean data and an integer variable can hold integer data.
While coding, we require different variables to store different information. Variables
are storage locations reserved for storing values. Therefore, when you create the
variable, you reserve some space in memory. Figure 2.2 shows different data types
used in C++.
In C++, Data Types can be classified as follows:
1. Primitive/Built-in Data Types
2. Derived Data Types
3. Abstract/User-defined Data Types
C++ provides built-in data types that correspond to integers, characters, floating-
point values, and Boolean values. There are seven basic data types in C++ as shown
below in Table 2.1.
Self-Instructional
Material 31
The figure 2.3 and figure 2.4 shows the program and output of memory in bytes used NOTES
for built-in data types.
#include<bits/stdc++.h>
using namespace std;
int main() {
cout << “Size of following Datatypes in bytes:
\n”;
cout << “int : “ << sizeof(int) << endl;
cout << “unsigned int : “ << sizeof(unsigned int)
<< endl;
cout << “short int : “ << sizeof(short int) <<
endl;
cout << “long int : “ << sizeof(long int) << endl;
cout << “unsigned short int : “ << sizeof(unsigned
short int) << endl;
cout << “unsigned long int : “ << sizeof(unsigned
long int) << endl;
cout << “long long int : “ << sizeof(long long
int) << endl;
c ou t < < “ u n si gn e d l o n g l o n g i nt : “ < <
sizeof(unsigned long long int) << endl;
cout << “signed char : “ << sizeof(signed char) <<
endl;
cout << “unsigned char : “ << sizeof(unsigned
char) << endl;
cout << “wchar_t : “ << sizeof(wchar_t) << endl;
cout << “float : “ << sizeof(float) << endl;
cout << “double : “ << sizeof(double) << endl;
Fig. 2.3 Program to Find Size of Built-In Data Types
Output:
Size of following Datatypes in bytes:
int: 4
unsigned int: 4 Self-Instructional
short int: 2 Material 33
Derived Data Types are data types that are created by combining primitive or built-in
data types. There are four different types of derived data types. These are given
below:
1. Function: A function is a code segment or a block of code defined to accomplish
a specific purpose. A function is often designed to spare the user from repeatedly
writing the same lines of code for the same input. All the lines of code are
combined into a single function that may be invoked from anywhere. Every
C++ application includes a default function called main (). The function also has
a return type, which is used to specify the type of data the function would return
when its execution is complete.
2. Array: An array is a set of elements that are kept in memory in a continuous
manner and also have the same type of data present within the array. The purpose
of an array is to store a lot of data in a single variable name and sequential order.
3. Pointer: Pointers are symbolic representations of addresses. Pointers store the
addresses of the variables having the same data type as that of the pointer. The
size of the pointer is either 4 bytes or 8 bytes, no matter what the data type is.
4. Reference: When a variable is declared as a reference, it becomes an alternative
name for an existing variable. A variable can be declared as a reference by
putting '&' in the declaration.
Self-Instructional
34 Material
The Abstract data type, also known as user-defined data type, is a type of data defined
by the user.
Examples of these are as follows:
1. Class: A Class is a C++ building piece that leads to Object-Oriented
programming. It is a user-defined data type with its own set of data members
and member functions that can be accessed and used by establishing a class
instance. A class defines the blueprint for a data type.
2. Structure: A Structure data type is a user-defined data type that combines
objects of potentially different data types into a single type.
3. Enumeration: In C++, an enumeration (or enum) is a data type that the user
creates. It is primarily used to give integral constant names, making the program
easier to comprehend and maintain. In enumeration, if we do not provide the
integral values explicitly to the strings, then, in that case, the strings automatically
start assigning the integral values starting from value 0, the same as the case of
0-based indexing.
Example:
enum result {pass = 100, fail = 0};
Here, we have given the integer value 100 to be pass and 0 as fail; therefore, if
we write,
enum result res;
res = pass;
Then, the value of res would automatically be 100.
By default, the enumerators are assigned integer values starting with 0 for the
first enumerator, 1 for the second and so on. We can also write
enum color {red, blue=4,green=8};
enum color {red=5,blue,green};
Self-Instructional
Material 35
NOTES
2.5 STRUCTURE OF C++ PROGRAM
Note that C++ provides the flexibility of writing a program with or without a
class and its member functions definition. A simple C++ program (without a class)
includes comments, headers, namespace, main (), and input/output statements.
Now we will see first C++ program without classes.
My First C++ program
// A Simple C++ Program
#include<iostream.h>
using namespace std;
#include<conio.h>
int main()
{
cout<< “Hello SOL!!. It is a Simple C++ program without
using class”;
return 0;
}
Self-Instructional
36 Material
Double slash (//) is used to represent comments. Comments are a vital element of a
program that are used to increase the readability of a program and to describe its
functioning. Comments are not executable statements and hence, do not increase the
size of a file. C++ supports two comment styles as given below:
i) Single line comment
ii) Multiline comment
Single line comments are used to define line-by-line descriptions. To understand
the concept of single line comment, consider this statement.
/ / An example to demonstrate single line comment It can also be written as
/ / An example to demonstrate
/ / single line comment
Multiline comments are used to define multiple lines descriptions and comments
are written within / * ….* /.
For example, consider this statement:
/* An example to demonstrate multiline comment.
Both of these lines are comments */
Generally, multiline comments are not used in C++ as they require more space on the
line. However, they are useful within the program statements where single-line comments
cannot be used.
Lines beginning with a hash sign (#) are directives that are read and interpreted
by what is known as the pre-processor. They are special lines interpreted before the
compilation of the program itself begins. In this case, the directive #include
<iostream.h>, instructs the pre-processor to include a section of standard C++
code, known as header iostream. The <iostream> header file provides the
necessary declarations and definitions for standard input/output streams to perform
operations, such as writing the output of program to the screen and taking input from
the keyboard.
Generally, a program includes various programming elements like built-in
functions, classes, keywords, constants, operators, etc., that are already defined in Self-Instructional
the standard C++ library. In order to use such pre-defined elements in a program, an Material 37
NOTES appropriate header must be included in the program. The standard headers contain
information like prototype, definition and return type of library functions, constants,
etc. As a result, programmers do not need to explicitly declare (or define) the predefined
programming elements.
Namespace: Since its creation, C++ has gone through many changes by the C++
Standards Committee. One of the new features added to this language is namespace.
A namespace permits grouping of various entities like classes, objects, functions and
various C++ tokens, etc., under a single name. Different users can create separate
namespaces and thus can use similar names of the entities. This avoids compile-time
error that may exist due to identical-name conflicts.
The function named main is a special function in all C++ programs; it is the function
called when the program is run. The execution of all C++ programs begins with the
main function, regardless of where the function is actually located within the code. The
compiler executes all the instructions written within the opening and closing curly braces’
{}’ that enclose the body of main ( ). Once all the instructions in main () are executed,
the control passes out of main ( ), terminating the entire program and returning a value
to the operating system.
The program ends with this statement:
return 0;
This causes zero to be returned to the calling process (which is usually the
operating system). Returning zero indicates that the program terminated normally.
Abnormal program termination should be signalled by returning a nonzero value.
The open brace ({) indicates the beginning of main’s function definition, and the
closing brace (}) indicates its end.
Self-Instructional The objects cin and cout are pre-defined objects that serve as representations of the
38 Material
standard input and output streams, respectively. The standard output stream is a
representation of the display device, typically the screen, used for outputting data. NOTES
Conversely, the standard input stream is a representation of the input device, typically
the keyboard, used for accepting user input.
cout<< “Hello SOL!!. It is a Simple C++ program without
using class”;
causes the string in quotation marks to be displayed on the screen. The identifier
cout (pronounced as c out) denotes an object. It points to the standard output
device namely the console monitor. The operator << is called the insertion operator. It
directs the string on its right to the object on its left.
cin: It is the standard input stream that is associated with the standard input device
(keyboard) and is used to take the input from users.
cout: It is the standard output stream that is associated with the standard output
device (monitor) and is used to display the output to users.
The operator << is called the insertion operator and the operator >> is called
the extraction operator.
Figure 2.6 illustrates the usage of more C++ statements like cin and cout.
Fig. 2.6 Usage of more C++ Statements Like cin and cout
Self-Instructional
Material 39
It is possible to use the insertion and extraction operators repeatedly in cin and cout
statements. Multiple use of these operators is called Cascading. For example, the
extraction operator can be cascaded as follows:
cout<<“ \n The value of a is “<<a ;
This statement first print “The value of a is” and then the value of variable a will be
printed. The insertion operator can be cascaded as follows:
cin>> a>>b;
The values are assigned from left to right.
In-Text Questions
Q 1. Which of the following is not the keyword in C++?
a) volatile b) for
c) enum d) cout
Q 2. ‘cin’ is an __
a) Class b) Object
c) Package d) Namespace
Q 3. A user defined header file is included by following statement in general.
a) #include “file.h” b) #include <file.h>
c) #include <file> d) #include file.h
Q 4. Which data type can be used to hold a wide character in C++?
a) unsigned char b) int
c) wchar_t d) none of the above
Q5. In CPP, cin and cout are the predefined stream __________ .
a) Operator b) Functions
c) Objects d) Data types
Self-Instructional
40 Material
NOTES
2.6 SUMMARY
In C++, data types can be categorized into three main groups: built-in, derived, and
abstract. Built-in data types include fundamental types like integers (int), floating-point
numbers (float, double), characters (char), and boolean (bool), which store basic
values. Derived data types are constructed from the built-in types and include arrays,
pointers, and user-defined types like structures and classes. Abstract data types refer
to user-defined classes that encapsulate data and methods to represent complex
structures.
Tokens in C++ are called as building blocks of a program. All the sub-parts of
tokens are: keywords, identifiers, constants, strings, special symbols, and
operators equally important and play a vital role in framing the programs in C++.
A typical C++ program is structured with a main() function at its core, serving
as the entry point. It may include preprocessor directives, global variable declarations,
user-defined functions, and external library inclusion. The program’s logic is typically
organized into functions, and control flow is managed through conditional statements
(if, else) and loops (for, while). Objects and classes are used to create modular, reusable
code, and memory management is a crucial aspect, often managed through new and
delete operators or smart pointers. C++ also supports exception handling to deal with
errors gracefully. Proper understanding and utilization of these data types and program
structures are essential for developing efficient and robust C++ applications.
2.7 GLOSSARY
Built-in Data Types: These are fundamental data types provided by the C++
language, including int (integers), float (floating-point numbers), double (double-
precision floating-point numbers), char (characters), and bool (boolean values).
Derived Data Types: Data types constructed from built-in types or other
derived types. Examples include arrays (collections of elements of the same
data type) and pointers (variables that store memory addresses).
Self-Instructional
Material 41
NOTES Abstract Data Types (ADTs): User-defined data types created using classes
and encapsulating data and methods to represent complex structures. Examples
include classes that define objects with specific properties and behaviors.
Main () Function: The core function in a C++ program, serving as the entry
point for program execution. It defines the starting point of program execution
and typically contains the program’s primary logic.
Preprocessor Directives: Instructions to the C++ preprocessor, such as
#include for including external libraries and #define for defining constants and
macros.
Global Variables: Variables declared outside of any function, making them
accessible throughout the entire program. They can be accessed and modified
from different functions.
User-Defined Functions: Custom functions created by the programmer to
encapsulate specific blocks of code. They are invoked when needed to perform
a specific task, enhancing code modularity and reusability.
Control Flow: The management of program execution based on conditions
and loops. Common control flow constructs in C++ include if-else statements
and for/while loops.
Objects and Classes: Objects are instances of classes, which are user-defined
data types that bundle together data attributes (properties) and methods
(functions) to represent real-world entities or abstract concepts.
Token: In programming, a token is the smallest individual unit of a program’s
source code. It can be a keyword, identifier, operator, or any other discrete
element with a specific meaning within the programming language.
Keyword: Keywords are reserved words in a programming language that have
special meanings and purposes. They cannot be used as identifiers or variable
names. Examples in C++ include “int,” “if,” “else,” and “class.”
Identifier: Identifiers are user-defined names used to represent variables,
functions, classes, and other program entities. They follow specific naming rules
and conventions.
Self-Instructional
42 Material
NOTES
2.8 ANSWERS TO IN-TEXT QUESTIONS
1. (c) enum
2. (b) Object
3. (a) #include “file.h”
4. (c) wchar_t
5. (c) Objects
2.10 REFERENCES
Self-Instructional
44 Material
LESSON 3 NOTES
Structure
3.1 Learning Objectives
3.2 Arithmetic Operators
3.3 Assignment Operators
3.4 Relational Operators
3.5 Logical Operators
3.6 Bitwise Operators
3.7 Operators and their Precedence
3.8 Expressions
3.9 Typecasting in C++
3.9.1 Implicit Conversion
3.9.2 Explicit Conversion
3.10 Library Functions
3.11 Header Files and Library Files
3.11.1 Header Files
3.11.2 Library Files
3.12 #include Usage
3.12.1 System/Library Header Files
3.12.2 User-Defined Header Files
3.13 Solved Exercise
3.14 Summary
3.15 Glossary
3.16 Answers to In-Text Questions
3.17 Self-Assessment Questions
3.18 References
3.19 Suggested Readings Self-Instructional
Material 47
NOTES
3.1 LEARNING OBJECTIVES
Output is 5.0
/ Division Divides left hand p/q 8/2
operand value by Output is 4
right hand operand 6.2 / 3
value. Returns Output is 2.067
floating point 20 / 10
(decimal) Output is 2
% Modulus Divides left hand p%q 6%4
operand value by Output is 2
right hand operand
value and returns 10 % 30
remainder. It can Output is 10
Self-Instructional only be used with
48 Material integers.
NOTES
++ Increment Increases value by 1 ++p p=7
Pre-increment ++p will be 8
Unary Operator
p++
Post-increment
-- Decrement Decreases value by 1 --p p=7
Pre-increment --p will be 6
p--
Post-increment
Note: While using division operator, if both dividend and divisor are integers, result
obtained will be integer. However if either of them is float, result will also be float.
Example 3.1: Write a program to explain arithmetic operators in C++.
#include <iostream>
using namespace std;
int main() {
int variable1, variable2;
int sum, difference, product, quotient, remainder;
return 0;
}
Output
Enter the first number: 8
Enter the second number: 9
Sum: 17
Difference: -1
Product: 72
Quotient: 0
Remainder: 8
Explanation
In this program, the user is prompted to enter two numbers. The program then performs
various arithmetic operations on these numbers using the arithmetic operators. Finally,
the results are displayed.
Note: Operators which requires two operands to operate are binary operators, and
which require just one operator are termed as unary operators.
Example 3.2: Write a C++ program to illustrate post and pre increment operators.
#include <iostream>
using namespace std;
int main() {
int variable1= 5;
int variable2 = 10;
// Post-increment operator
Self-Instructional
50 Material cout << “Post-increment:” << endl;
// Pre-increment operator
cout << “\nPre-increment:” << endl;
cout << “variable2: “ << variable2<< endl;
cout << “++variable2: “ << ++variable2 << endl;
cout << “After pre-increment, variable2: “ <<
variable2<< endl;
return 0;
}
Output
Post-increment:
variable1: 5
variable1++: 5
After post-increment, variable1: 6
Pre-increment:
variable2: 10
++variable2: 11
After pre-increment, variable2: 11
Explanation
NOTES result of the expression is the updated value of variable2. Finally, we print the
updated value of variable2.
Same logic is applied to post and pre decrement operator
Assignment operators are used to assign data values to variables. Assignment operators
are depicted in Table 3.2.
Table 3.2 Assignment Operators
int main() {
int variable1= 10;
int variable2= 5;
// Simple assignment
int result = variable1;
cout << “Simple assignment: “ << result << endl;
// Addition assignment
result += variable2;
cout << “Addition assignment: “ << result <<
endl;
// Subtraction assignment
result -= variable2;
cout << “Subtraction assignment: “ << result <<
endl;
// Multiplication assignment
result *= variable2;
cout << “Multiplication assignment: “ << result
<< endl;
// Division assignment
result /= variable2;
cout << “Division assignment: “ << result <<
endl;
// Modulus assignment
result %= variable2; Self-Instructional
Material 53
return 0;
}
Simple assignment: 10
Addition assignment: 15
Subtraction assignment: 10
Multiplication assignment: 50
Division assignment: 10
Modulus assignment: 0
Explanation
In this program, we have two variables variable1 and variable2. We perform
various assignment operations using different assignment operators.
Simple assignment (=): Assigns the value of variable1 to the variable
result.
Addition assignment (+=): Adds the value of variable2 to result
and assigns the sum back to result.
Subtraction assignment (-=): Subtracts the value of variable2
from result and assigns the difference back to result.
Multiplication assignment (*=): Multiplies the value of result by
variable2 and assigns the product back to result.
Division assignment (/=): Divides the value of result by variable2
and assigns the quotient back to result.
Modulus assignment (%=): Computes the remainder of result divided by
variable2 and assigns the remainder back to result.
Self-Instructional Relational or comparison operators are used for comparison. They compare two
54 Material
values and return Boolean value ‘True’ or ‘False’. They are given in Table 3.3.
int main() {
int variable1= 5;
int variable2 = 10;
// Equal to operator
bool isEqual = (variable1 == variable2);
cout << “Equal to operator: “ << isEqual <<
Self-Instructional
endl; Material 55
NOTES
// Not equal to operator
bool isNotEqual = (variable1 != variable2);
cout << “Not equal to operator: “ << isNotEqual
<< endl;
return 0;
}
Output
Equal to operator: 0
Not equal to operator: 1
Greater than operator: 0
Less than operator: 1
Greater than or equal to operator: 0
Self-Instructional
56 Material Less than or equal to operator: 1
Explanation NOTES
In this program, we have two variables variable1 and variable2. We perform various
relational operations using different relational operators.
Equal to operator (==): Checks if variable1 is equal to variable2.
Not equal to operator (!=): Checks if variable1 is not equal to
variable2.
Greater than operator (>): Checks if variable1 is greater than variable2.
Less than operator (<): Checks if variable1 is less than variable2.
Greater than or equal to operator (>=): Checks if variable1
is greater than or equal to variable2.
Less than or equal to operator (<=): Checks if variable1
is less than or equal to variable2.
The result of each operation is stored in a boolean variable1 (true or
false) and then printed.
These statements are used to check if expression statement is true or false. Table 3.4
shows various logical operators.
Table 3.4 Logical Operators
// Logical OR operator
bool resultOR = variable1 || variable2;
cout << “Logical OR operator: “ << resultOR <<
endl;
return 0;
}
Logical AND operator: 0
Logical OR operator: 1
Logical NOT operator: 0
Explanation
variable1 is true, the NOT operator returns false, and if variable1 is false, NOTES
it returns true.
The logical operators evaluate the logical conditions and return a boolean result
based on the evaluation
Bitwise operators are used to manipulate individual bits of integer types. They perform
operations at the bit level, allowing you to perform tasks such as bit manipulation,
bitwise logical operations, and shifting.
Table 3.5 Bitwise Operators
Operator Description
Performs a bitwise AND int a = 5; // Binary:
operation between the 0101
corresponding bits of two int b = 3; // Binary:
& Bitwise AND 0011
operands.
int result = a & b; //
Binary: 0001
Performs a bitwise OR operation int a = 5; // Binary:
between the corresponding bits 0101
of two operands. int b = 3; // Binary:
| Bitwise OR 0011
int result = a | b; //
Binary: 0111
Performs a bitwise exclusive OR int a = 5; // Binary:
(XOR) operation between the 0101
corresponding bits of two int b = 3; // Binary:
^ Bitwise XOR 0011
operands.
int result = a ^ b; //
Binary: 0110
Flips the bits of the operand, i.e., Flips the bits of the operand, i.e.,
~ Bitwise Not
performs a bitwise negation. performs a bitwise negation.
Shifts the bits of the left operand int a = 5; //
to the left by the number of Binary: 0101
Binary Shift
<< positions specified by the right int result = a << 2;
Left // Binary: 010100
operand.
(Decimal: 20)
Shifts the bits of the left operand Shifts the bits of the left operand
Binary Shift to the right by the number of to the right by the number of
>>
Right positions specified by the right positions specified by the right
operand. operand. Self-Instructional
Material 59
int main() {
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110
// Bitwise AND
int resultAnd = a & b;
cout << “Bitwise AND: “ << resultAnd << endl; // Output: 2 (Binary: 0010)
// Bitwise OR
int resultOr = a | b;
cout << “Bitwise OR: “ << resultOr << endl; // Output: 14 (Binary: 1110)
// Bitwise XOR
int resultXor = a ^ b;
cout << “Bitwise XOR: “ << resultXor << endl; // Output: 12 (Binary:
1100)
// Bitwise NOT
int resultNot = ~a;
cout << “Bitwise NOT: “ << resultNot << endl; /
/ Output: -11 (Binary: 111111111111111111111111111
10101)
// Left Shift
int resultLeftShift = a << 2;
Self-Instructional
60 Material
// Right Shift
int resultRightShift = a >> 2;
cout << “Right Shift: “ << resultRightShift <<
endl; // Output: 2 (Binary: 10)
return 0;
}
Operators
Bitwise AND: 2
Bitwise OR: 14
Bitwise XOR: 12
Bitwise NOT: -11
Left Shift: 40
Right Shift: 2
This program demonstrates the usage of bitwise AND, OR, XOR, NOT, left
shift, and right shift operators. It performs the operations on two integer variables a
and b and outputs the results.
In C++, operators have different precedence levels, which determine the order in
which they are evaluated when multiple operators are present in an expression. If
two operators have the same precedence, their evaluation order depends on the
associativity of the operators. Table 3.6 depicts operators in highest to lowest
precedence.
Self-Instructional
Material 61
return 0;
}
Output
Result 1: 14
Result 2: 20
Result 3: 2
Self-Instructional
Result 4: -10 Material 63
NOTES Result 5: 26
Result 6: 26
Expressions involving addition, subtraction, multiplication, and division operators
are evaluated. The results are stored in different variables (result1 to result6) to
demonstrate the effect of operator precedence and the use of parentheses to override
it.
Example 3.8: Write a program to show operator associativity.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5, c = 2;
int result1 = a - b - c; // Left associativity:
Evaluates from left to right
int result2 = a / b / c; // Left associativity:
Evaluates from left to right
int result3 = a % b % c; // Left associativity:
Evaluates from left to right
return 0;
Self-Instructional
64 Material }
Output NOTES
Result 1: 3
Result 2: 1
Result 3: 0
Result 4: 2
a: 2
b: 2
c: 2
Explanation
3.8 EXPRESSIONS
Typecasting refers to the process of converting one data type into another. It allows
you to explicitly specify the desired type conversion and can be used to convert between
built-in types, user-defined types, or even between related types. We will discuss two
types of typecasting.
Implicit conversions are performed automatically by the compiler when the conversion
is safe and does not result in a loss of data. For example, converting an int to a float or
assigning a smaller integer type to a larger integer type.
Example 3.9: Write a program to show implicit conversion.
#include <iostream>
using namespace std;
int main() {
int num1 = 10;
double num2 = num1; // Implicit conversion
from int to double
Self-Instructional
66 Material
char ch = ‘A’;
int ascii = ch; // Implicit conversion from
char to int
int a = 5;
int b = 2;
double result = a / b; // Implicit conversion
during integer division
return 0;
}
Output
num1: 10
num2: 10
ch: A
ascii: 65
result: 2
Explanation
The use of explicit conversion changes data values from one type to another.
C-style casting involves using casting operators such as (type) or type(value) to perform
explicit type conversions. It can be used to perform various conversions, but it can
also be potentially unsafe if used incorrectly.
Example 3.10: Write a program that demonstrates C-style type casting.
#include <iostream>
using namespace std;
int main() {
int num1 = 10;
double num2 = (double)num1; // C-style casting
from int to double
int a = 5;
int b = 2;
double result = (double)a / b; // C-style casting
during integer division
char ch = ‘A’;
int ascii = (int)ch; // C-style casting
from char to int
cout << “ch: “ << ch << endl; // Output: A
cout << “ascii: “ << ascii << endl; // Output: 65
return 0;
Self-Instructional }
68 Material
Output NOTES
num1: 10
num2: 10
result: 2.5
ch: A
ascii: 65
Explanation
int main() {
int num1 = 10;
double num2 = static_cast<double>(num1); // Static
cast from int to double
int a = 5;
Self-Instructional
int b = 2; Material 69
char ch = ‘A’;
int ascii = static_cast<int>(ch); // Static cast
from char to int
return 0;
}
Output
num1: 10
num2: 10
result: 2.5
ch: A
ascii: 65
Explanation
Self-Instructional
70 Material
NOTES
3.10 LIBRARY FUNCTIONS
A rich set of library functions is available in C++ that cover a wide range of functionality.
Here are some commonly used libraries in C++ and their functions:
1. <iostream>: Input/output operations.
std::cin: Reads input from the user.
std::cout: Writes output to the console.
std::endl: Inserts a newline character and flushes the output stream.
std::getline: Reads a line of input from the user.
2. <cmath>: Mathematical functions.
std::sqrt: Calculates the square root of a number.
std::pow: Raises a number to a power.
std::sin, std::cos, std::tan: Trigonometric functions.
std::abs: Returns the absolute value of a number.
3. <string>: String manipulation operations.
std::string: Represents a sequence of characters.
std::getline: Reads a line of input from a stream into a string.
std::substr: Extracts a substring from a string.
std::find: Searches for a character or substring within a string.
4. <fstream>: File input/output operations.
std::ifstream: Reads input from a file.
std::ofstream: Writes output to a file.
std::getline: Reads a line from a file into a string.
std::open: Opens a file for reading or writing.
These are just a few examples of the libraries and functions available in C++.
The C++ Standard Library provides many more functions and containers to handle
various programming tasks efficiently.
Self-Instructional
Material 71
NOTES
3.11 HEADER FILES AND LIBRARY FILES
In C++ programming, header files and library files play important roles in organizing
and reusing code. Here is a brief explanation of each:
Library files (also called binary or object files) are compiled code files that
contain precompiled functions and classes.
Library files have file extensions like ‘.lib‘ (Windows) or ‘.a‘ (Unix/Linux) for
static libraries, and ‘.dll‘ (Windows) or ‘.so‘ (Unix/Linux) for dynamic/shared
libraries.
Library files provide precompiled code that can be linked with your program at
compile-time or runtime.
They can include functions, classes, data structures, and other code that can be
used by your program without needing to reimplement them.
Library files can be either system libraries (provided by the operating system)
Self-Instructional or third-party libraries (developed by external developers).
72 Material
To use a library in your C++ program, you typically need to include the NOTES
appropriate header file(s) and link against the library file(s).
It is worth noting that header files and library files are closely related. Header
files provide declarations for the functions and classes in library files, while library files
contain the compiled implementations of those functions and classes. When writing
C++ programs, it is common to include necessary header files and link against required
library files to access their functionalities and reuse existing code.
The #include directive is used to include header files into your program. There
are two common ways to use #include in C++, which are discussed here.
#include <header_file>
In this form, the angle brackets ‘< >’ are used to enclose the header file name.
This syntax is typically used for including standard library header files or system-level
header files. The compiler will search for these header files in the standard system
directories.
Example:
#include <iostream>
#include <vector>
#include “header_file”
In this form, double quotation marks ‘“ ”’ are used to enclose the header file
name. This syntax is typically used for including user-defined header files that are
present in the current directory or in specified paths.
Example:
#include “my_header.h” Self-Instructional
Material 73
NOTES Both forms of #include directives allow you to bring in the declarations
and definitions from the included header files into your C++ program. This enables
you to use the functions, classes, and other entities defined in those header files in your
code.
It is worth noting that header files usually contain declarations, not definitions. Definitions
for the declarations in the header files are typically found in corresponding
implementation files (e.g., ‘.cpp‘ files) or library files.
int main() {
// Prompt for two numbers
cout << “Enter two numbers: “;
double num1, num2;
cin >> num1 >> num2;
// Display menu
cout << “Select an operation:\n”;
cout << “1. Addition\n”;
Self-Instructional
74 Material
cout << “2. Subtraction\n”;
NOTES break;
}
return 0;
}
Output
Enter two numbers: 5
9
Select an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1-4): 3
Result: 45
Explanation
Program prompts you to enter two numbers and select an operation to perform. After
you make a choice, the program will calculate the result and display it.
2. Write a program that converts temperature between Celsius and Fahrenheit
scales.
#include <iostream>
using namespace std;
int main() {
// Prompt for temperature
cout << “Enter a temperature value: “;
double temperature;
cin >> temperature;
Self-Instructional
// Display menu
76 Material
return 0;
}
Output
Enter a temperature value: 45
Self-Instructional
Select conversion direction: Material 77
Explanation
Program prompts to enter a temperature and select the conversion direction. After
you make a choice, the program will perform the conversion and display the converted
temperature.
In-Text Questions
1. What is the result of the expression: 10 % 3?
a) 1 b) 3
c) 0 d) 10
2. What does the following expression evaluate to: (5 > 3) && (4 < 2)?
a) true b) false
c) 1 d) 0
3. What is the associativity of the assignment operator (=) in C++?
a) Right to left b) Left to right
c) Top to bottom d) Bottom to top
4. Which operator is used to perform explicit typecasting in C++?
a) () b) <>
c) ** d) ><
5. Which operator is used to determine the size of an object or data type in
C++?
a) sizeof b) size
c) sizeofof d) memoryof
Self-Instructional
78 Material
NOTES
3.14 SUMMARY
3.15 GLOSSARY
NOTES Bitwise Operators: Operators that perform operations at the binary level,
including bitwise AND (&), bitwise OR (|), bitwise XOR (^), and bit shifting
(<< and >>).
Conditional (Ternary) Operator: A shorthand operator represented as ? : that
allows you to assign a value based on a condition.
Expression: A combination of operators, variables, and literals that evaluates
to a value. For example, x + y is an expression.
Type Casting (Type Conversion): The process of converting a value from
one data type to another. In C++, it can be explicit or implicit.
1. a) 1
2. b) false
3. b) Left to right
4. a) ()
5. a) sizeof
Q1. Describe the purpose and use of conditional statements (if, else) in C++.
Provide examples.
Q2. What are loops in C++? Explain the difference between for, while, and
do-while loops with examples.
Q3. Define and explain the concept of functions in C++. Provide an example of a
user-defined function.
Q4. How can you explicitly convert data from one data type to another in C++?
Self-Instructional
Give examples of type casting.
80 Material
NOTES
3.18 REFERENCES
Self-Instructional
Material 81
LESSON 4 NOTES
Structure
4.1 Learning Objectives
4.2 Introduction
4.3 if Statement
4.4 if-else Statement
4.5 Nested if Statement
4.6 if-else-if Ladder
4.7 switch Statement
4.8 Conditional Operator
4.9 Summary
4.10 Glossary
4.11 Answers to In-Text Questions
4.12 Self-Assessment Questions
4.13 References
4.14 Suggested Readings
NOTES
4.2 INTRODUCTION
In daily life, we take many decisions, like …. Shall I go for shopping? If I go for
shopping, shall I purchase jeans or not? In C++ programming also we need to make
decisions to handle the flow of program. For decision making purpose, decision
statements are used in C++. They evaluate condition(s) and based on the outcome,
the decision regarding whether the statement(s) is executed or not is taken and the
flow of program is decided.
Decision making statements govern the flow of program execution in C++. They are
also known as conditional statements. Decision making statements used in C++ are
as follows:
if Statement
if-else Statement
Nested if Statement
if-else-if Ladder
switch Statement
Conditional Operator
They are discussed one by one below.
4.3 if STATEMENT
NOTES if (variable % 2 == 0)
{
cout<< variable <<“ is even number”;
}
cout<< “ \n I am not part of if statement block”;
//this is always executed
return 0;
}
Output
Enter variable to check: 68
68 is even number
I am not included in if statement
if statements execute block only if condition evaluates to true. There are situations
when statements need to be executed for both true and false, i.e., we need to execute
certain statements when condition evaluates to true and some other statements when
condition evaluates to false. In that case, if-else statement is used. Structure of
if-else statement is depicted below.
if (expression statement)
{
// Statement(s) are executed if expression statement
evaluates to true
}
else
{
// Statement(s) are executed if expression statement
evaluates to false
}
Self-Instructional
88 Material
NOTES
NOTES {
cout<<variable<<“ is even number”;
}
else
{
cout<<variable<<“ is odd number”;
}
return 0;
}
Output
Enter Number: 5
5 is odd number
Enter Number: 8
8 is even number
Example 4.3: Write a program to print bigger number out of two input numbers.
#include <iostream>
using namespace std;
int main()
{
int value1, value2;
cout << “Enter two numeric Numbers: “ ;
cin>> value1 >> value2;
cout<<“two entered numbers are “<<value1 <<“
and “<<value2;
if (value1 > value2)
cout<<endl<< value1 <<“ is greater”;
else
cout<<endl<<value2 <<“ is greater”;
cout<< “ \n I am always executed”; // Statement is
always executed
return 0;
}
Self-Instructional
90 Material
Output NOTES
Enter two numeric Numbers: 5
9
two entered numbers are 5 and 9
9 is greater
I am always executed
Explanation
In above code, curly braces are not present after if and else blocks which makes
only immediate statement to be executed depending on condition.
We have situations when one condition is placed inside another. For example if I buy
blue colour denim then I needs to buy black colour coat also. When we have hierarchy
of conditions, i.e., one condition inside another then nested if statements are used.
The structure of nested if statement is depicted below.
if (condition expression1)
{
if (condition expression2)
{
}
else
{
}
else
{
Self-Instructional
} Material 91
NOTES
Example 4.4: Write a program to find greatest of three numbers input from user.
#include <iostream>
using namespace std;
int main()
{
int variable1, variable2, variable3;
cout<<“Enter three numbers to be checked: “;
cin >> variable1>> variable2>> variable3 ;
Self-Instructional if(variable1>variable2)
92 Material
{ NOTES
/* This is executed if num1 is greater than
num 2 */
if(variable1>variable3)
{
cout<<“Greatest Number is :”<<variable1;
}
else
{
cout<<“Greatest Number is :”<<variable3;
}
}
else
{
/* This is executed if num2 is greater than
num1 */
if(variable2>variable3)
{
cout<<“Greatest Number is :”<<variable2;
}
else
{
cout<<“Greatest Number is :”<<variable3;
}
}
return(0);
}
Output
Enter three numbers to be checked: 5
6
9
Greatest Number is : 9
Self-Instructional
Material 93
NOTES
4.6 if-else-if LADDER
Self-Instructional
94 Material
NOTES
to 60% grade D is awarded, average between 40 to 50% grade E is awarded, below NOTES
40% Fail.
A switch statement is used to evaluate variable for equality for specified list of
values. Each value is checked in case statement, and the variable to be tested is checked
in switch expression. It is also used as an alternative to if-else-if ladder.
While using switch, following points must be followed:
Expression in switch statement must evaluate to integer, character or
enumerated data type.
Switch statement can have any number of case statements. Case statement
contains constant value to be compared and must be same data type of expression
in which switch evaluates to.
Case statements are executed based on value of switch expression.
Break statements are optional with case. If break statement is found,
switch terminates and flow of execution jumps to first statement after
switch. If no break is found, subsequent case statements are executed
until break is found.
Default statement is optional and must appear at the end of switch
block. They are used for executing pieces of code when no condition in case
statements is met. Break statement is not used in default.
The structure of switch statement is as follows and the flowchart is depicted
in Figure 4.5.
switch (expression)
{
case value1:
statement(s);
break; //optional
case value2:
statement(s);
break; //optional Self-Instructional
case value3: Material 97
NOTES statement(s);
break; //optional
case value4:
statement(s);
break; //optional
default:
statement(s);
}
Self-Instructional
98 Material Fig. 4.5 Flowchart of switch
Example 4.6: Write a program to check if the entered character is a vowel or a NOTES
consonant.
#include <iostream>
using namespace std;
int main()
{
char character;
cout<<“Enter character to be checked: “;
cin>> character;
switch (character)
{
case ‘a’:
cout <<“It is a vowel”<<endl;
break;
case ‘e’:
cout <<“It is a vowel”<<endl;
case ‘i’:
cout <<“It is a vowel”<<endl;
case ‘o’:
cout <<“It is a vowel”<<endl;
case ‘u’:
cout <<“It is a vowel”<<endl;
default:
cout<<“It is a consonant”;
}
}
Output
Enter character to be checked: a
It is a vowel
NOTES It is a vowel
It is a vowel
It is a consonant
In first output, since break is mentioned after case ‘a’, rest of the case
statements are skipped. In second output, no break statement in case ‘i’ was mentioned
which caused all subsequent case and default statement to be executed.
The difference between if-else and switch statement is given in Table 4.1.
Table 4.1 Difference between if-else and switch
if-else switch
Testing expression Can test expressions on Expression in switch statement
range of values must evaluate to integer, character
or enumerated data type
Readability In case of multiple If there are multiple conditions,
conditions, code is not switch provides much better
readable readability of code
Speed of execution Good for less than five Provides faster speed when there are
conditions five or more cases
default:
cout<<“Operator is not correct”;
}
}
Output
Enter two numbers :5
9
Enter operator (+, -, *, /): *
5 * 9 = 45
Conditional operator as discussed earlier can also replace if-else statement. The
structure of conditional operator is given below:
(Conditional Expression) ? Statement1:Stataement2
In-Text Questions
1. Which decision control statement is used to execute a block of code only if
the condition is true?
a) for loop
b) while loop
c) if statement
d) do-while loop
2. What is the syntax of the if statement in C++?
a) if (condition) { // code block }
b) if { // code block } (condition)
c) { // code block } if (condition)
d) { // code block } (condition) if
Self-Instructional
102 Material
4.9 SUMMARY
In the chapter on Decision and Control Statements in C++, we’ve delved into the
essential elements of control flow within C++ programming. These statements are the
foundation for creating programs that can make choices, repeat actions, and manage
the sequence of execution. We’ve explored conditional statements such as if, else if,
and else, gaining insight into crafting meaningful conditions using relational and logical
operators. The chapter also covered switch statements, which enable you to select
specific code blocks based on the value of an expression. Additionally, we’ve learned
about the various types of loops, including while, do-while, and for, and how to control
them with break and continue. The conditional operator was introduced as a concise
means to make choices in a single line of code. Throughout the chapter, the importance
of clean coding practices, like proper indentation, naming conventions, and informative Self-Instructional
Material 103
NOTES comments, was stressed. In essence, understanding decision and control statements is
pivotal for creating adaptable and efficient C++ programs, as they are the core constructs
for logic and flow control in the language.
4.10 GLOSSARY
NOTES
4.11 ANSWERS TO IN-TEXT QUESTIONS
1. c) if statement
2. a) if (condition) { // code block }
3. c) Multiple alternatives (if-else if-else)
4. a) int, char, and float
5. b) The program continues executing the code in the next case.
Q1. What is the primary purpose of the if statement in C++, and how does it differ
from the else if and else blocks?
Q2. How does the switch statement differ from a series of if-else statements
in terms of control flow?
Q3. In a for loop, what are the three components: initialization, condition, and
update, and how do they work together?
Q4. When is the while loop typically used in C++ programming, and how does it
differ from a for loop?
Q5. Explain the key feature of a do-while loop and provide a scenario where it
might be more suitable than a while loop.
Q6. Describe the concept of nested loops and provide an example of a situation
where they would be beneficial.
Q7. How is the break statement used within a loop, and when might you use it?
Q8. Explain the purpose of the continue statement and provide an example of when
it can be valuable in a loop.
Q9. Why should you be cautious about creating infinite loops in your C++ programs,
and what measures can you take to prevent them?
Self-Instructional
Material 105
NOTES Q10. Write a program to generate an electricity bill. Take number of consumed
units as input from the user. Criteria are as follows:
For the first 50 units 0.50/unit
For the next 100 units 0.75/unit
For the next 100 units 1.20/unit
For unit above 250 1.50/unit
An additional surcharge of 20% is added to the bill
Q11. Write a program to check if an individual is eligible to vote or not. Take age as
an input.
Q12. Write a program to check if the entered year is a leap year or not.
4.13 REFERENCES
Self-Instructional
106 Material
LESSON 5 NOTES
LOOPS IN C++
Structure
5.1 Learning Objectives
5.2 Introduction
5.3 for Loop
5.4 while Loop
5.5 do while Loop
5.6 Jump Statements
5.6.1 break
5.6.2 continue
5.6.3 goto
5.6.4 return
5.7 Summary
5.8 Glossary
5.9 Answers to In-Text Questions
5.10 Self-Assessment Questions
5.11 References
5.12 Suggested Readings
To understand the use of loop statements in C++ such as for loop, while
loop and do while loop
To explain the concept of jump statements such as break, continue, goto and
Self-Instructional
return Material 107
NOTES
5.2 INTRODUCTION
In daily life, there are situations where we need to perform some operations again and
again until a condition is met. When the condition becomes false, we stop operation.
For example if we need to play a list of songs, we simply form a playlist. Now the
music player will keep on playing songs until the playlist is empty. For handling repeated
execution of statement(s) in C++, loops are used. For example if we need to execute
statement or block of statements more than once, we make use of loops in C++.
Loop statements used in C++ are as follows:
for loop
while loop
do while loop
They are discussed one by one below.
for loop is the easiest loop in C++. It is used to execute statement(s) a fixed number
of times. for loop is used when we know in advance how many times statement(s)
need to be executed. The syntax of for loop is given below:
for(initialization; condition; iteration) // please
note no semicolon is present here
{
//statements to be executed
}
Initialization: Here initialization of variables occurs. Single or multiple variables can
be initialized here. Initialization expression is executed only once, at beginning of for
loop.
Self-Instructional
108 Material
Self-Instructional
Material 109
NOTES
Self-Instructional
110 Material Fig. 5.1 Flowchart of for loop
int main()
{
int num;
}
Output
Enter number : 5
1
2
3
4
5
Self-Instructional
Material 111
} NOTES
return 0;
}
Output
11
22
33
44
55
Working of program
Iteration Variable Condition Action performed
i<4 || j < 6
(i is less than 4 or j is less than 6)
1 Variable i 1<4 || 1< 6 i=1
and j are is true j=1
initialized to printed
1 Control moves to
iteration expression, i
and j are incremented
2 i=2 2<4 || 2< 6 i=2
j=2 true j=2
printed
Control moves to
iteration expression, i
and j are incremented
3 i=3 3<4 || 3< 6 i=3
j=3 true j=3
printed
Control moves to
iteration expression, i
and j are incremented
4 i=4 4<4 || 4< 6 i=4
j=4 true j=4
i and j are 4 printed
Control moves to
Test condition has two expressions iteration expression, i
First: i<4 and j are incremented
Second: j<6
Self-Instructional
Material 113
}
Output
infinite for loop
infinite for loop
infinite for loop
terminated forcefully
Explanation
Self-Instructional
When we omit test condition for loop, it will result in infinite loop
114 Material
Example NOTES
We can also nest one for loop inside another.
Example 5.4: Write a program that takes a positive integer n and produces n lines of
output as shown: (n=4 as output)
*
**
***
****
#include <iostream>
using namespace std;
int main()
{
int lines;
cout<<“Enter the lines “;
cin>> lines;
for (int p=1;p<= lines;p++)
{
for (int m=1;m<=p;m++)
{
cout<<“*”;
}
cout<<endl;
}
return 0;
}
Output
Enter the num4
*
**
***
Self-Instructional
Material 115
int i, num;
int i, n;
cout<<“Enter number: “;
cin >>n;
for loops are used, when we know in advance how many times loop needs to be
executed. But there are situations where number of times loop will execute is not
known, here while loops are used. Similar to the for loop, while loop is also
an entry controlled loop as whether the loop will execute or not is determined the by
test condition in entry phase.
Syntax of while loop is as follows:
while(test expression) // no semicolon is present
here
{
//statements to be executed
}
Initialization expression is present before while loop.
Self-Instructional
118 Material
int i=1, n;
int fact=1;
while (i <= n)
{
fact = fact *i;
i++; //i variable is updated
}
{ NOTES
cout<<endl<<“infinite while loop”;
}
return 0;
}
Output
infinite loop
infinite loop
infinite loop
Forcefully terminated
void main()
{
int n, first, second, third ;
cout<<“Enter num: “;
cin>>n;
first =0;
second =1;
third = first + second;
}
Output
Enter num: 20
Fibonacci series is: 0 1 1 2 3 5 8 13
Solved Exercise
1. Write a program to accept a number, reverse it and print the sum of its digits.
#include <iostream>
using namespace std;
int main()
{
int num, nd, sum, rem,reverse_num=0;
cout<<“Enter a Number : “;
cin>>num;
nd = 0;
sum = 0;
while (num > 0)
{
rem = num % 10;
sum = sum+ rem;
num = num / 10;
reverse_num = reverse_num *10 + rem;
Self-Instructional
122 Material
“<<reverse_num; NOTES
return 0;
}
Output
Enter a Number : 1298
The sum of digit is 20
The reverse of digit is 8921
In while loop, first condition is evaluated and if it is true then only the body is
executed. But there are situations where we want to execute the body of the loop
atleast once before condition statement is checked. Here do while loop is used.
do while loop is a variant of while loop where condition statement is evaluated
after execution of the body of the loop. It is an exit controlled loop, i.e., body of the
loop is executed first, and then condition expression is evaluated. If condition expression
evaluates to true, then body of the loop is executed again. In do while loop, body
of the loop is executed atleast once before the condition statement is met. The syntax
is as follows:
do
{
//body of loop
}while (condition);
Self-Instructional
Material 123
NOTES
Self-Instructional
124 Material
Example 5.8: Write a program to find sum of positive numbers only. NOTES
#include <iostream>
using namespace std;
int main()
{
int num, sum_numbers;
sum_numbers =0;
num=0;
do {
sum_numbers += num;
cout<<“Enter Number: “;
cin>>num;
}while (num >=0);
int main()
{
int var =65;
Self-Instructional
do { Material 125
Solved Exercise
int main()
{
int choice, num;
do
{
cout<<endl<<“Menu is as follows.”;
cout<<endl<<“1. To check whether a given number
is odd or even”;
cout<<endl<<“2. Display a Fibonacci series”;
Self-Instructional cout<<endl<<“3. Compute factorial of a number”;
126 Material
switch (choice)
{
case 1: // print num is even or odd number
if (num % 2 ==0)
cout<<endl<<num <<“ is a even number”;
else
cout<<endl<<num <<“ is a odd number”;
break;
case 2: //print Fibonacci series
{
int first =0, second =1;
int third = first + second;
first = second;
second = third;
third= first + second;
}
break;
} Self-Instructional
Material 127
}
Output
Menu is as follows.
1. To check whether a given number is odd or even
2. Display a Fibonacci series
3. Compute factorial of a number
4. Exit
Please choose choice: 1
3 is a odd number
Self-Instructional
128 Material
NOTES while loop is used when condition has to be checked before executing the
loop body.
do while loop is used when we need to execute the body atleast once
irrespective of the condition is met or not.
5.6.1 break
int main()
{
int num;
cout<<“Enter the variable: “ ;
cin>>num;
{ NOTES
break;
}
cout<<“ “<<i;
}
Explanation
int i, n;
bool is_prime = true;
cout << “Enter a numeric: “;
cin >> n;
NOTES if (n % i == 0) {
is_prime = false;
break; //If a number is divisible by any number,
it is not checked further. With break statement control
is transferred out of loop skipping any further
iterations
}
}
if (is_prime)
cout << n << “ is a prime number”;
else
cout << n << “ is not a prime number”;
return 0;
}
Output
Enter a numeric: 6
6 is not a prime number
Explanation
5.6.2 continue
Sometimes when a condition is met, we do not want to skip the entire loop, but
only that particular iteration. For this purpose continue statements are used. Instead
Self-Instructional
132 Material
of transferring control to immediate next statements after loop, only that particular NOTES
iteration is skipped. Execution of the entire loop is not stopped, instead a particular
iteration where condition is met is skipped and the loop is resumed from next
iteration.
Syntax is as follows:
continue;
Example 5.12: Write a program to demonstrate continue statement.
#include <iostream>
using namespace std;
int main()
{
int num;
cout<<“Enter the number: “ ;
cin>>num;
Self-Instructional
Material 133
NOTES Explanation
Please see, only iteration for i==2 is skipped, and rest of loop executes as it is.
5.6.3 goto
The goto statement is used to transfer control of program from one statement to another
within same function.
Syntax is as follows:
goto label; //label is called
label: //label is defined
Example 5.13: Write a program to demonstrate the use of goto statement.
#include <iostream>
int main()
{
int num;
if (num % 2 == 0)
goto printeven; //label is called
else
cout<<endl <<“It is odd number”;
Explanation
5.6.4 return
This statement is used to return the control of a program or function. When the return
statement is encountered, the execution of program stops and the control is returned.
Also, it returns a value. For void function, no value is returned but for non-void functions
value must be returned.
Syntax is as follows:
return value;
Exercise
1. Write a program to find sum of all numbers between 200 and 300 which are
divisible by 7.
2. Write a program to print the series and its sum: 1 + 1/2! + 1/3! + … + 1/n!.
3. Write a C++ program to make a pattern of pyramid with an asterisk.
Sample Output:
Input number of rows: 4
*
* *
* * *
* * * *
Self-Instructional
Material 135
NOTES
In-Text Questions
1. Which loop in C++ is used to execute a block of code repeatedly based on a
condition?
a) for loop b) while loop
c) do while loop d) if-else loop
2. What is the syntax of the for loop in C++?
a) for (initialize; condition; update) { // code
block }
b) for { // code block } (initialize; condition;
update)
c) { // code block } for (initialize; condition;
update)
d) for [initialize; condition; update] { // code
block }
3. How many times will a do while loop execute its code block if the condition
is false initially?
a) 0 times b) 1 time
c) At least once d) It depends on the loop body.
4. For what is the continue statement in a loop used?
a) Exit the loop entirely
b) Restart the loop from the beginning
c) Skip the current iteration and move to the next iteration
d) End the program execution
5. What happens if the condition is false initially in a while loop?
a) The loop will never execute.
b) The loop will execute indefinitely.
c) The loop will execute exactly once.
d) The loop will execute for a random number of times.
Self-Instructional
136 Material
6. Which loop is more suitable when the number of iterations is known NOTES
beforehand?
a) for loop b) while loop
c) do while loop d) All loops are equally suitable
7. The for loop and the while loop can be used interchangeably. Is it true or
false?
a) True b) False
8. What does the break statement do in a loop?
a) Continues to the next iteration of the loop.
b) Exits the loop entirely.
c) Restarts the loop from the beginning.
d) Skips the current iteration and moves to the next iteration.
9. To what is the scope of the loop control variable limited in a for loop?
a) Limited to the loop body only b) Limited to the for statement only
c) Limited to the current function only d) Limited to the entire program
10. When is the condition in a do while loop checked?
a) Before executing the loop body.
b) After executing the loop body.
c) It is not possible to have a condition in a do while loop.
d) Do while loop does not require a condition.
5.7 SUMMARY
The chapter on loops in C++ delves into the critical aspect of control flow within
programming, enabling the repetition of specific code blocks. It introduces three primary
types of loops: the for loop, the while loop, and the do-while loop. The for
loop is an excellent choice for iterating over a known range of values and is often used
in counting or traversing arrays. The while loop continues execution as long as a
Self-Instructional
Material 137
NOTES given condition remains true, providing adaptability in loop control. The do-while
loop ensures at least one execution of the block, even if the condition is initially false.
These loops are instrumental in handling iterative tasks, processing data collections,
and implementing complex algorithms efficiently in C++ programs. Mastery of these
loop structures is crucial for writing organized and effective code, as they are fundamental
tools for managing control flow and automating repetitive tasks in C++.
5.8 GLOSSARY
1. b) while loop
2. a) for (initialize; condition; update) { // code
block }
3. c) At least once
Self-Instructional
138 Material 4. c) Skip the current iteration and move to the next iteration
Q1. Explain the differences between the for loop, while loop, and do-while
loop in C++. When would you choose one over the other for a particular
programming task?
Q2. How does the concept of loop control variables play a role in managing loops?
Provide an example of a situation where a loop control variable is used effectively.
Q3. What are the potential risks associated with infinite loops, and how can they be
avoided when using loops in C++? Provide an example of a scenario where an
infinite loop might occur.
Q4. In what types of programming scenarios are iterative algorithms commonly used,
and how do loops facilitate the implementation of these algorithms in C++?
Q5. Write a C++ program that uses a for loop to print all even numbers between
1 and 20.
Q6. Create a C++ program that utilizes a while loop to calculate the factorial of
a given positive integer entered by the user.
5.11 REFERENCES
NOTES
5.12 SUGGESTED READINGS
Self-Instructional
140 Material
LESSON 6 NOTES
FUNCTIONS IN C++
Structure
6.1 Learning Objectives
6.2 Introduction
6.3 Uses of Functions
6.4 Types of Functions
6.4.1 Built-in Functions
6.4.2 User Defined Functions
6.5 Call Methods in Function
6.6 Function Overloading
6.7 Default Arguments
6.7.1 Ambiguity in Function Overloading When Done Using Default
Arguments
6.8 Return by Reference
6.9 Solved Exercise
6.10 Summary
6.11 Glossary
6.12 Answers to In-Text Questions
6.13 Self-Assessment Questions
6.14 References
6.15 Suggested Readings
6.2 INTRODUCTION
Block of code or group of statements which are used to perform specified tasks is
termed as function in C++. Functions can be used again and again during the life time
of a program.
Syntax of functions is as follows:
return_type function_name (parameter 1, parameter
2, ….)
{
//body
}
Return type specifies data type of value function will return. If return type is
void, functions do not return anything else they return value.
Function name specifies the name of function by which it is called.
Parameters are arguments given to a function. A function can have zero or more
arguments.
Task assigned to a function is performed in the body of the function.
Example 6.1: Write a function to calculate the area of a circle.
#include <iostream>
using namespace std;
float area_circle (float radius); //declaration of
function
int main()
{
float radius, result;
cout <<“Enter the radius of circle: “;
cin>>radius;
Self-Instructional
144 Material result=area_circle(radius); //function is called
Explanation
float area_circle (float radius);
This statement is function declaration.
Function declaration constitutes, return type, function name and parameters
inside brackets. Parameters name may or may not be specified. Function declaration
is also termed as signature statement of function.
If we are defining function after it is being called in main function, then we need
to specify function declaration before. That means function declaration can be skipped
altogether if we are defining function before it is being invoked.
result=area_circle(radius);
In this statement function is being called or invoked inside main. By this statement
control of program is transferred to part of program where function is defined. And
after function body is executed again control returns back to this statement and value
is returned in result. Function can be invoked any number of times.
float area_circle (float radius) //definition of
function
{
Self-Instructional
float area; Material 145
Self-Instructional There are two types of functions in C++ as shown in Figure 6.1.
146 Material
NOTES
Built-in functions also known as library functions are already present in C++. Their
definitions are picked up from header files used in a program. sqrt(), abs(),
setw(), isdigit() are some of the common library functions available in
C++. To use library function in a program, corresponding header file is included in the
program and the function is called. User does not write the definition of function,
compiler automatically picks up the definition from header file.
Example 6.2: Write a program to demonstrate the use of built-in functions.
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float number, square_root;
cout<<“Enter the Number: “;
cin>>number;
square_root = sqrt(number);
NOTES Explanation
if (isdigit(ch))
{
cout<<endl<<ch<<“ is a digit”;
}
else
{
cout<<endl<<ch<<“ is a character”;
}
}
Output
Enter the character: 9
9 is a digit
Functions that are defined by the user are termed as user defined functions. They can
be further divided as given below:
Self-Instructional
148 Material
No return value and has no parameters: The functions which have no return NOTES
type and do not take any arguments as inputs come in this category. Return type
void is for such functions.
No parameters but has return value: No arguments are passed to the
function, but there is a return value.
Parameters but no return value: The function has arguments, but there is no
return value, i.e., it has void return type.
Argument and return value: The function has both arguments and returns
value.
Example 6.4: Write a program for function having no return value and no parameter.
#include <iostream>
#include<cmath>
using namespace std;
func();
}
Self-Instructional
Material 149
NOTES Explanation
func has no return type and does not take any input arguments
Example 6.5: Write a program to calculate the area of a rectangle and demonstrate
function having return value and parameters.
#include <iostream>
#include<cmath>
using namespace std;
result=area(side1,side2); //calling
cout<<endl<<“Area of rectangle is: “<<result;
}
Explanation
int area (int, int); //Function declaration
Self-Instructional
150 Material
result=area(side1,side2);
side1 and side2 are parameters passed to function. Please note data type of
parameters passed matches to that of parameters in function declaration and definition.
Parameters passed to function are also known as actual parameters. Here side1,
side2 are actual parameters.
Inline Functions
Inline functions are also defined by the user but they vary with other user defined
functions in terms of the execution behaviour. They are offered by C++ to minimize the
overhead associated with the behaviour of function calling. The “inline” keyword is
used to make a function inline and should be defined above the main function.
The syntax of the inline function is as follows:
inline return-type function-name(parameters) {
//function body
}
Example 6.6: Write a program to demonstrate the inline function.
#include <iostream>
NOTES {
cout<<“The square of 3 is “<<square(3);
return 0;
}
Output
The square of 3 is 9
Explanation
The square function is an inline function. While execution, the control is not transferred
to the square function, because compiler will replace the function call of square in
cout statement of main function with its body. We can call the main function as
calling function, and square function as called function.
The behaviour of simple user-defined function and inline function is defined as follows:
Simple user-defined function: When a function call is encountered by the
calling function, some extra processing is done by the system. The control is
first transferred to the called function, and after execution of the called function,
the control is transferred back to the calling function. This extra processing for
control transfer is treated as overhead.
User-defined inline function: Instead of transferring control to the calling
function, the body of the calling function replaces the function call.
The main advantage of using an inline function is the fast execution as compared to
other function. The execution becomes fast as there is no overhead of controlling
transfer to the calling function. We can make a simple and short function as inline, but
we cannot make a function inline if the function is of following types:
Containing loop, or static variable
Recursive function
Return type is void
Contains goto or switch statement
Self-Instructional
152 Material
NOTES
6.5 CALL METHODS IN FUNCTION
}
Output
Enter the two numbers: 4
6
In swap function
Numbers are: 6 4
In main function
Numbers are: 4 6
Explanation
swap(num1,num2); //actual parameters
In above statement, actual parameters num1 and num2 of swap function are
having value 4 and 6
When function swap is called, x and y formal parameters receive value 4 and 6.
x and y occupy different memory locations then actual parameters num1 and num2. x
and y also receive values as 4 and 6.
After swapping of values on x and y variables in swap function, now x and y
have values 6 and 4 respectively. The same is also printed.
Any change made in the value in formal parameters x and y will not reflect in
actual parameters. Scope of variables x and y are limited to function swap. When we
move back to main function, scope of x and y is terminated.
When control moves back to the main function, values of num1 and num2 are 4 and 6
respectively.
Call by Reference: In call by reference method, address of actual parameters
is passed to formal parameters. Both actual and formal parameters share same
memory locations. That means any change in the value of formal parameters
will be reflected in the value of actual parameters.
Self-Instructional
154 Material
swap(num1,num2);
cout<<endl<<“In main function”;
cout<<endl<<“Numbers are: “<<num1<<“ “<<num2;
}
}
Output
Enter the two numbers: 4
7
In swap function
Numbers are: 7 4
In main function
Self-Instructional
Numbers are: 7 4 Material 155
When two or more functions have same name but number or data type of parameters
differ, then it is known as function overloading. Functions overloaded may or may not
have same return data type, but the number of parameters must differ in number or
data type.
Self-Instructional
156 Material
float area(double a) { }
Float Data type value is passed.
int main()
{
int side1,side2;
float radius, result;
int ch;
do Self-Instructional
{ Material 157
cout<<endl<<“Enter Choice: “;
cin>>ch;
switch (ch)
{
case 1:
{
cout<<“Enter the radius: “;
cin>> radius;
result = area(radius);
cout<<endl<<“Area of circle is
:”<<result;
}
break;
case 2:
{
cout<<“Enter the side: “;
cin>> side1;
result= area(side1);
cout<<endl<<“Area of square is
:”<<result;
}
break;
case 3:
{
cout<<“Enter the two sides :”;
cin>> side1>>side2;
result= area(side1,side2);
Self-Instructional cout<<endl<<“Area of rectangle is :”<<
158 Material
result; NOTES
}
break;
default:
cout<<endl<<“Wrong choice”;
break;
}
}while(ch != 4);
}
Wrong choice
Explanation
int area(int, int);
int area(int);
float area(float);
This is an example of function overloading as three functions have same name
area and they have different parameters or data type of parameters differs.
int area(int, int);
This function has two parameters.
int area(int);
This function has one parameter.
Self-Instructional
Material 161
int area(int);
float area(float);
Above statements are examples of function overloading with different data types
of parameters.
int area(int, int);
int area(int);
Above statements are examples of function overloading with different number
of parameters.
When values are assigned to parameters or arguments in function definition, then those
arguments are termed as default arguments. When value is not passed to default
arguments while call to function is made, then compiler automatically uses default
values. And when values are passed to the parameters during call to function, default
arguments are overridden.
Example 6.10: Write a program to demonstrate default arguments in functions.
#include <iostream>
using namespace std;
Self-Instructional
162 Material
result = average (2,5, 6);
result = (a + b + c + d + e) / 5;
return result;
}
Output
// Valid
void sum(int x, int y, int z = 3);
// Invalid code
int main() {
show();
}
When we are doing function overloading and using default parameters, we should see
that compiler should not get confused while calling, which function is to be called.
Example 6.11: Write a program to demonstrate Ambiguity in function overloading
when done using default arguments.
#include<iostream>
using namespace std;
int add(int a,int b, int c=10) // c int is default
parameter
{
return (a + b + c);
Self-Instructional
}
164 Material
We have discussed how to pass value to arguments by reference, here we will learn
how we can return value by reference.
Example 6.12: Write a program, to demonstrate return by reference.
#include <iostream>
using namespace std; Self-Instructional
Material 165
NOTES
int test_variable; //global varaible
// function declaration
int& test_function();
int main() {
return 0;
}
// function definition
// returns the address of int variable
int& test_function() {
return test_variable;
}
Output
10
Return type of function is int&. It returns reference to variable, i.e., address
of variable.
Please make note test_function() is placed on left as compared to
other places where call to function is always placed on right.
Here, in the function definition, reference to variable is returned so variable can
be assigned a value. It is same as writing variable = 10;
Some important points to consider while using returning by reference are as follows:
Normal functions return values, but here we are returning reference to variable.
Self-Instructional So a constant value can not be returned from this function.
166 Material
Since the scope of local variables is only within function, so we cannot return NOTES
reference to local variable from these functions. As soon as the function called is
returned, local variables are removed from the stack, so reference to global
variables are returned from these functions.
Some invalid code examples while using return by reference
int& test_function() {
return 10;
}
Explanation: Constant value is being returned. So the code written above is an invalid
code.
int& test_fuinction() {
int x = 10;
return x;
}
Explanation: Reference to local variables can not be returned. So the code written
above is an invalid code.
1. Write a program using functions to print the series and its sum: 1 + 1/2! + 1/3!
+ … + 1/n!.
#include <iostream>
using namespace std;
int factorial(int);
float series_sum(int);
int main()
{
int n;
cout<<“Enter the number: “;
cin>> n;
Self-Instructional
Material 167
cout<< endl<<“Series sum is :”<< series_sum(n);
NOTES }
float series_sum(int x)
{
float sum=0;
int i=1;
while(i<=x)
{
int factorial(int x)
{
int fact =1;
int i=1;
while(i<=x)
{
fact *= i;
i++;
}
return fact;
}
Output
Enter the number: 5
Series sum is :1.71667
Explanation
The factorial function is called from within series_sum function.
Self-Instructional
The sum of series is obtained and returned back to the main function.
168 Material
NOTES
In-Text Questions
1. Functions in C++ are used for:
a) Controlling the flow of the program
b) Defining classes and objects
c) Grouping and organizing code for reusability
d) Handling exceptions and errors
2. The return type of a C++ function can be:
a) Only integers
b) Any data type, including user-defined types
c) Only built-in data types (int, char, etc.)
d) Only float and double
3. What is the keyword used to define a function in C++?
a) func b) function
c) method d) void
4. The process of passing arguments by reference in a function allows:
a) Reducing the number of arguments passed to the function
b) Modifying the original values of the arguments inside the function
c) Enabling the function to return multiple values
d) Reducing the function's execution time
5. A function prototype in C++ is used for:
a) Specifying the return type of the function
b) Providing a function declaration before its actual definition
c) Declaring a function that takes no arguments
d) Defining a function within another function
6. What is the default return type of a function in C++ if it is not specified?
a) int b) void
c) float d) char
Self-Instructional
Material 169
NOTES
6.10 SUMMARY
Functions in C++ are fundamental building blocks for organizing and reusing code.
They enable you to encapsulate a set of instructions into a named block, making code
more modular and readable. C++ functions consist of a function signature, which
defines the function’s name, return type, and parameters, along with a function body
containing the code to be executed. You can declare functions before their use, and
the actual implementation can be defined separately. Functions can accept parameters,
allowing data to be passed into the function, and can return values as a result. This
chapter covers function creation, parameter passing, return values, function overloading,
and the use of standard library functions, emphasizing the role of functions in code
organization, reusability, and the development of efficient and maintainable C++
programs.
6.11 GLOSSARY
Function Declaration: It consists of its name, return type, and parameter list,
defining its interface and how it can be called.
Function Body: The part of a function that contains the actual code to be
executed when the function is called.
Parameter: A variable used within a function to accept data passed into the
function during its invocation, allowing for flexibility and reusability of the code.
Return Value: The value that a function can optionally return to the calling
code, conveying the result of the function’s execution.
Function Overloading: A feature in C++ that allows you to define multiple
functions with the same name but different parameter lists, providing flexibility in
function usage and enabling polymorphism in the language.
Self-Instructional
170 Material
NOTES
6.12 ANSWERS TO IN-TEXT QUESTIONS
Q1. How can functions in C++ be used to encapsulate and modularize code, and
what are the advantages of doing so?
Q2. How are member functions in C++ classes utilized to model and manipulate
objects, and what benefits do they provide in object-oriented programming?
Q3. Write a menu driven program for the following:
a. to check whether a given number is odd or even.
b. display a Fibonacci series
c. compute factorial of a number
Perform these operations by calling functions.
Q4. Write a program to accept a number, reverse it and print the sum of its digits.
Reversal and sum of digits should be implemented in different functions.
6.14 REFERENCES
Self-Instructional
172 Material
LESSON 7 NOTES
Structure
7.1 Learning Objectives
7.2 Introduction of Arrays
7.3 Initialization and Declaration of Array
7.3.1 Initializing Values to Array during Declaration
7.3.2 Assigning Values to Array after Declaration
7.4 Types of Array in C++
7.4.1 Single Dimensional Array
7.4.2 Multi-Dimensional Array
7.5 Passing Array to Function
7.6 Pointers
7.7 Pointer- Declaration and Initialization
7.8 Solved Exercise
7.9 Summary
7.10 Glossary
7.11 Answers to In-Text Questions
7.12 Self-Assessment Questions
7.13 References
7.14 Suggested Readings
Array is the collection of homogeneous data items which are stored continuously in
memory. In simple words we can define array as a group of similar items which are
stored one after another in memory. Similar items which occupy continuous memory
space are termed as array. It is the most used data type in C++.
In Figure 7.1, similar data items, i.e., int data type elements (7, 10, 2, 23, 12, 6)
are stored in adjacent memory locations and can be accessed by 0, 1, 2, 3, 4, 5 array
index. By default in C++, array index starts from 0 and goes till the size of array -1. In
Figure 7.1, there are total 6 elements in array. We can have array of any data type like
int, float, char, etc.
For declaration of array in C++, we need to have data type of elements, name and
size of array. Basic syntax is represented below:
data_type array_name [size];
Example7.1: int num[5];
Self-Instructional
174 Material
Explanation NOTES
num is name of array. 5 is size of array and data type of num array is int. 5
int data type variables are stored together in memory.
Array elements are accessed by index. For example here array elements will be
accessed from index 0…. to 4. They are accessed like num[0],
num[1]……., num[4].
First element of array is stored at index 0 and can be accessed by using num[0],
similarly last element can be used by accessing num[4].
Array elements are stored continuously in memory. For example
If size of int data type is 4 bytes in memory,
First element of array num[0] is stored at 1000 memory location,
num[1] will be stored at 1004
num[2] will be stored at 1008
num[3] will be stored at 1012
last element num[4] will be stored at 1016
Here num array contains 5 elements and from index 0 to 4. If we try to access
5th element we will get “out of bound error”.
Initialization of arrays in C++ can be done in two ways as given below:
Initializing values to array during declaration
Assigning values to array after declaration
These two ways are described below.
Explanation
Array of name x , data type int has 5 elements and has been assigned values and they
Self-Instructional
can be accessed in following way Material 175
NOTES x[0]=18
x[1]=23
x[2]=5
x[3]=6
x[4]=89
Example 7.3: int x[] = {18, 23, 5, 6, 89};
Explanation
Array of name x , data type int has been assigned values and they can be accessed in
the following way:
x[0]=18
x[1]=23
x[2]=5
x[3]=6
x[4]=89
Size of array is not assigned. But compiler automatically computes the size
depending on the values assigned.
Here, an array is simply declared, i.e., data type and size of the array is defined. The
values are assigned at a later stage.
Example 7.4: Write a program to enter and display array elements.
#include <iostream>
using namespace std;
int main()
{
int num[5];
cout << “Enter the elements of array: “;
for (int i=0;i<5;i++) //loop for input of array
elements
Self-Instructional cin>>num[i];
176 Material
NOTES
cout << “Print the elements of array: “;
for (int i=0;i<5;i++) //loop for display of array
elements
cout<<endl<<“num[“<<i<<“]: “<<num[i];
return 0;
}
Output
Enter the elements of array: 5
1
6
45
89
Print the elements of array:
num[0]: 5
num[1]: 1
num[2]: 6
num[3]: 45
num[4]: 89
Explanation
int num[5];
In the above statement, num array of data type int and size 5 is declared.
Values are not assigned.
There are two types of array in C++, viz., single dimensional array and multi-dimensional
array.
Arrays in which elements are stored in single dimension are termed as single dimensional
arrays.
The syntax is as follows:
data_type array_name[size];
float num[5];
Single dimensional array is represented in Figure 7.2.
Example 7.5: Write a program to calculate sum and average of array elements.
/* Online C++ Compiler and Editor */
#include <iostream>
int main()
{
Self-Instructional int num[5], sum;
178 Material float average;
average = sum/5.0;
return 0;
}
Output
Enter the elements of array: 4
7
8
2
67
Print the elements of array:
num[0]: 4
num[1]: 7
Self-Instructional
num[2]: 8 Material 179
NOTES num[3]: 2
num[4]: 67
Sum of array elements are:88
Average of array elements are:17.6
Here num[5] array single dimensional array is declared.
Values are assigned after declaration.
Multi-Dimensional array represents an array that can have any number of dimensions.
The syntax is as follows:
data_type array_name[size1][size2];
size1, size2 represents the number of elements in dimension1 and dimension2.
Example
float matrix [5][5]; // two dimensional array
float matrix[3][4][5]; // three dimensional array
Self-Instructional
180 Material Fig. 7.3 Two Dimensional Array
Example 7.6: Write a program to input marks of five students where each student has NOTES
five subjects. Also calculate the average marks for each student.
#include <iostream>
int main()
{
int marks[5][5], sum[5];
float average[5];
cout << “Enter the marks of students: “;
for (int i=0;i<5;i++)
{
cout << endl<<“Enter the marks of “<< i+1<< “
student: “;
for (int j=0;j<5;j++)
cin>>marks[i][j];
}
return 0;
}
Enter the marks of students:
Enter the marks of 1 student: 78
90
78
99
88
Enter the marks of 2 student: 99
67
56
89
67
Enter the marks of 3 student: 89
90
89
78
90
Enter the marks of 4 student: 78
67
56
89
90
Self-Instructional
Enter the marks of 5 student: 90
182 Material
98 NOTES
98
97
94
Print the marks of students:
Marks of 1student are:
78
90
78
99
88
Average marks of1students is:86.6
Marks of 2student are:
99
67
56
89
67
Average marks of2students is:75.6
Marks of 3student are:
89
90
89
78
90
Average marks of3students is:87.2
Marks of 4student are: Self-Instructional
Material 183
NOTES 78
67
56
89
90
Average marks of4students is: 76
Marks of 5student are:
90
98
98
97
94
Average marks of 5students is: 95.4
Explanation
return 0;
}
minimum = num[0];
for (int i=1;i<5;i++)
{
return minimum;
}
Output
Enter elements of array45
12
34
78
90
int main()
{
int num[5], maximum;
cout<<“Enter elements of array”;
for (int i=0;i<5;i++)
{
cin>>num[i];
}
return 0;
}
maximum = arr[0];
for (int i=1;i<5;i++)
{
maximum = arr[i];
}
}
return maximum;
}
Output
Enter elements of array45
90
43 Self-Instructional
Material 187
NOTES 76
23
Printing elements in array45 90 43 76 23
The maximum element in array is: 90
7.6 POINTERS
Pointers are used to store memory addresses of variables in C++. When we define
variables of any data type in C++, they are assigned address in memory. Pointers are
variables that are used to store these addresses.
The syntax is as follows:
int element; // simple int data type variable element
int *pr; // pointer variable pr of int data type. pr
variable can store memory address
Some of the advantages of using pointers are given below:
With pointers, execution speed of program becomes faster. Pointer variables
directly accesses memory locations, thus making speed faster.
Pointers save memory space.
We can declare array using pointers of any data type without specifying the size
of array.
data_type *pointer_varaible_name;
Data type can be int, char, float, etc.
Self-Instructional
188 Material *operator tells variable declared is pointer
pr = &element;
cout<<endl<<“Element is: “<<element;
cout<<endl<<“Adderess of element is: “<<&element;
cout<<endl<<“pr pointer to element contains
address: “ <<pr;
cout <<endl <<“Value of address stored in pr is:
“<<*pr;
}
Output
Element is: 90
Addresses of element is: 0x7ffe2897a05c
pr pointer to element contains address: 0x7ffe2897a05c
Value of address stored in pr is: 90
Self-Instructional
Material 189
NOTES
Example 7.10: Write program to create and access array elements using pointers.
#include <iostream>
using namespace std;
int main()
{
int *arr, size;
Self-Instructional
190 Material
}
Explanation
In this program, size of array is not declared initially rather it is delayed till runtime.
This is known as dynamic allocation and achieved using pointers.
nt array of specified size is assigned to pointer variable ptr at run time. Elements
are assigned to array through for loop
ptr is pointing to base addrerss of array, i.e., arr[0]
when arr++ is used, pointer starts pointing to next address that is arr[1] and so
on.
This is how successive array elements are accessed.
cout<<endl<<“Element at address “<<arr<<“is: “<<*arr
<<“ “;
Above line prints first address of element and then element present at that address
Since size of int is 4 bytes, please note addresses represented in hexadecimal
notation are increased by four every time
Please note that the size of note depends on compiler. It may vary depending on
compiler from 2 bytes to 4 bytes. Self-Instructional
Material 191
NOTES
7.8 SOLVED EXERCISE
1. Write a program that will prompt the user for a list of n prices. Compute the
average of the prices and find out all the prices that are higher than the calculated
average.
#include <iostream>
using namespace std;
int main()
{
int *arr, size;
float average_price;
cout<<“Enter the number of elements of array: “;
cin>>size;
check_larger_average (arr,size,average_price);
Self-Instructional
192 Material
} NOTES
average = sum/size;
return average;
}
void check_larger_average(int *arr, int size, float
num)
{
cout<<endl<<“Prices larger than average price are:
“;
for (int i=0; i<size;i++)
{
if (num < arr[i])
{
cout <<endl<< arr[i];
}
}
}
NOTES 12
90
The elements of array are:
Element of array are: 23
Element of array are: 67
Element of array are: 45
Element of array are: 12
Element of array are: 90
Average of prices are: 47.4
Prices larger than average price are:
67
90
2. Write a program to perform the following operations on an input string
a. Print length of the string
b. Find frequency of a character in the string
c. Print whether characters are in uppercase or lowercase
d. to check whether a given string is palindrome or not
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[100];
cout<<“Enter the string: “;
Self-Instructional
cin.get(str,100);
194 Material
check_palindrome(str,strlen(str));
check_case(str,strlen(str));
check_freq(str,strlen(str));
return 0;
}
if (flag)
{
cout<<endl<<“String is not palindrome”;
}
else
{
cout<<endl<<“String is palindrome”;
} Self-Instructional
Material 195
NOTES }
void check_case(char arr_str[], int size)
{
cout<<endl<<“String in function check_case is:
“<<arr_str;
for(int i=0;i < size ;i++)
{
if(isupper(arr_str[i]))
{
cout<<endl<<“Char “<<arr_str[i]<<“ is in
Upper case”;
}
else
{
cout<<endl<<“Char “<<arr_str[i]<<“ is in
Lower case”;
}
}
}
Exercise
In-Text Questions
1. What is an array in C++?
a) A collection of objects with different data types
b) A collection of elements of the same data type, stored in contiguous memory
locations
c) A built-in function to handle multiple values
d) A data structure used for sorting elements
2. How do you access elements of an array in C++?
a) Using the dot (.) operator
b) Using the -> operator
c) By specifying the element’s index in square brackets
d) By using the @ symbol followed by the element number
3. What is the index of the first element in an array?
a) 0
b) 1
c) -1
Self-Instructional
d) It depends on the programmer’s choice.
198 Material
4. The size of an array must be known at compile time. True or False? NOTES
a) True b) False
5. How do you declare and initialize an array of integers with elements 1, 2, 3, 4,
and 5?
a) int arr[1, 2, 3, 4, 5];
b) int arr[5] = {1, 2, 3, 4, 5};
c) int arr = {1, 2, 3, 4, 5};
d) int arr[] = {1, 2, 3, 4, 5};
6. Can the size of an array be changed once it is declared?
a) Yes, using the realloc() function. b) Yes, using the resize() function.
c) No, the size is fixed once declared. d) Only if the array is empty.
7. What happens if you try to access an element beyond the array’s size in C++?
a) The program throws an error and terminates.
b) The program continues to execute, but the result is unpredictable.
c) The program automatically resizes the array.
d) The program adds new elements to the array.
8. How do you find the length of an array in C++?
a) Using the size() function
b) Using the length() function
c) By subtracting the index of the first element from the index of the last element
d) There is no direct method to find the length of an array.
9. An array can hold elements of different data types in C++. Is it true or false?
a) True b) False
10. Which of the following do you need to pass in order to pass an array to a
function in C++?
a) The entire array
b) The size of the array and each element individually
c) Only the size of the array
d) Only the elements that need modification
Self-Instructional
Material 199
NOTES
7.9 SUMMARY
Arrays and pointers are fundamental concepts in C++ that play a crucial role in managing
and manipulating data efficiently. Arrays are collections of elements of the same data
type stored in contiguous memory locations. They are declared with a fixed size and
are accessed using zero-based indexing. Pointers, on the other hand, are variables
that store memory addresses. In C++, arrays and pointers are closely related, as an
array’s name can be considered a constant pointer to its first element, enabling
convenient access to array elements using pointer notation. Additionally, pointers are
used for dynamic memory allocation and deallocation, allowing for the creation of
variable-sized data structures. Understanding the relationship between arrays and
pointers is essential for effective memory management and data handling in C++.
Pointer arithmetic is a powerful feature that allows for traversing arrays and
accessing elements efficiently. However, it also requires caution to prevent accessing
memory outside the allocated boundaries. Dynamic memory allocation using pointers
is particularly valuable when creating data structures with varying sizes at runtime.
Arrays of pointers enable the storage of multiple pointers in an array, each pointing to
different data, a common use case when managing arrays of strings. Overall, mastering
arrays and pointers is vital for C++ programmers to work with data structures effectively
and ensure proper memory handling in their applications.
7.10 GLOSSARY
NOTES
7.13 REFERENCES
Self-Instructional
202 Material
LESSON 8 NOTES
Structure
8.1 Learning Objectives
8.2 Introduction to Classes
8.3 Classes and Objects
8.4 Advantages of Objects and Classes in C++
8.5 Member Function in Classes
8.5.1 Inside Class
8.5.2 Outside Class
8.6 Constructors in C++
8.7 Destructors in C++
8.8 Objects as Arguments
8.9 Returning Objects from Functions
8.10 Inheritance in C++
8.10.1 Access Modes in Inheritance
8.11 Types of Inheritance
8.11.1 Single Inheritance
8.11.2 Multiple Inheritance
8.11.3 Multilevel Inheritance
8.11.4 Hierarchical Inheritance
8.12 Solved Exercise
8.13 Summary
8.14 Glossary
8.15 Answers to In-Text Questions
8.16 Self–Assessment Questions
8.17 References
8.18 Suggested Readings
Self-Instructional
Material 205
NOTES
8.1 LEARNING OBJECTIVES
We have studied about inbuilt data types like integer, float, char and boolean. In this
lesson, we will study about user defined data types Classes. Objects are real world
entity like car, employee, student, and vehicle. These real world entities have some
common properties and some common functions. For example all vehicles have tyres,
engine and their function is to move people or things around. We can say that object,
a real world entity, has some property and functionality. In C++, we term property as
data members whereas functionality as member functions.
Classes act as a blueprint to create real world entities, i.e., objects. They club together
properties and functionality under one roof. Objects are created at run time. An object
is an instance of class. All members of class are accessed through objects.
Self-Instructional
206 Material Fig 8.1 Class Representation in Memory
class vehicle
{
public: //access specifier is public
int wheels;
string colour;
int mileage; // miles on car
void print()
{ Self-Instructional
Material 207
int main()
{
vehicle car_ob;
car_ob.wheels = 4;
car_ob.colour=”Blue”;
car_ob.mileage=20;
vehicle bike_obj;
bike_obj.wheels = 2;
bike_obj.colour=”Red”;
bike_obj.mileage=15;
return 0;
}
Output
Details of car are
Vehicle has 4 wheels
Vehilce has Blue colour
Vehilce has mileage 20 mileage
Self-Instructional
208 Material
Explanation
vehicle car_ob;
vehicle bike_obj;
Objects for class vehicle are created: car_obj and bike_obj
This means both car_obj and bike_obj have above data members and
member functions.
Both objects can access their respective data and functions.
bike_obj.wheels = 2;
bike_obj.colour=”Red”;
bike_obj.mileage=15;
Data members of class are accessed
bike_obj.print();
member function of class is accessed
Access Specifier is public which means data members and member functions
are public and can be used anywhere in program
We can also have combination of private, protected, and public access modifiers.
Self-Instructional
Material 209
NOTES
Private access specifier signifies that the data member or functions are private
to class and can only be accessed within the class. It is also a default access specifier
which means if no access specifier is mentioned, then by default those data members
or member functions are considered private.
Public access specifier signifies data member or functions are public to class
and can be accessed anywhere, inside or outside the class.
Example 8.2: Write a class to show how private and public members of class are
accessed.
/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;
class vehicle
{
private:
int wheels;
string colour;
int mileage; // miles on car
public:
void set(int w, string c, int m)
{
wheels = w;
colour= c;
Self-Instructional
210 Material mileage = m;
} NOTES
void display()
{
cout<<endl<<“Vehicle has “<< wheels<<“ wheels”;
cout<<endl<<“Vehilce has “ <<colour<<“ colour”;
cout<<endl<<“Vehilce has mileage “<<mileage<<“
mileage”;
}
};
int main()
{
vehicle car_ob;
NOTES Explanation
Private data members can be accessed only from inside class or from member functions.
private:
int wheels;
string colour;
int mileage;
public:
void set(int w, string c, int m){};
void display(){};
class FindSquare {
private:
// private variables
int input, result;
public:
void square(int x)
{
input = x;
result = input * input;
cout<<“The square of “<<input<<“ is
“<<result<<endl;
}
};
int main()
{
FindSquare sq;
sq.square(5);
/* In valid block of code
cout<<sq.input; */
return 0;
Self-Instructional
} Material 213
NOTES Output
The square of 5 is 25
Explanation
The private members input and result are only accessible to the member function
“square()” of the class and not accessible outside the class. In other words, the details
and working of private members of the class are hidden from the outside world of the
class, and can be accessed through the class members only. The variables input and
result are not accessible even with the object “sq” of the class, since they are declared
private.
Inheritance: C++ supports inheritance, which allows you to create new classes
based on existing ones. Inheritance enables code reuse and promotes the concept
of “is-a” relationships. By deriving a new class from a base class, we inherit its
attributes and behaviours while adding or modifying them as needed. Inheritance
helps in creating hierarchies of classes and promotes code extensibility and
flexibility.
Polymorphism: Polymorphism is the ability to treat objects of different classes
in a uniform manner. C++ supports both compile-time polymorphism (function
overloading) and runtime polymorphism (virtual functions). Polymorphism allows
you to write generic code that can work with the objects of different types,
improving code flexibility and reusability. For the implementation of function
overloading, please consult section 6.6.
Object instances: Objects are instances of classes. They represent specific
entities in your program. By creating multiple objects of the same class, you can
work with different instances of data and behaviour. This enables you to model
and manipulate complex systems more effectively.
These advantages of classes and objects in C++ contribute to writing more
modular, maintainable, and reusable code, enhancing the overall efficiency and structure
of your programs.
Self-Instructional
214 Material
NOTES
8.5 MEMBER FUNCTION IN CLASSES
In C++, member functions can be defined inside class or outside class definition. Both
are defined below.
In the previous examples, we have observed member functions being defined inside
class. Let us see one more example when member function is defined inside class
definition.
Example 8.4: Write a program to illustrate when member function is defined inside
class definition.
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
int width;
public:
int perimeter() {
return 2 * (length + width); Self-Instructional
} Material 215
NOTES };
int main ()
{
Rectangle myRectangle;
myRectangle.set(5,4);
cout << endl <<“Area is: “ <<myRectangle.area() ;
cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;
return 0;
}
Output
Area is: 20
Perimeter is: 18
Explanation
Data members are private and can be accessed only inside class or by class member
functions.
Here all member functions are defined inside class definition.
Member functions can also be defined outside class definition. To define member
function outside class definition, scope resolution operator :: is used along with class
name and function name.
Example 8.5: Write a program to illustrate when member function is defined outside
class definition.
#include <iostream>
using namespace std;
Self-Instructional
216 Material
public:
void set(int l, int b);
int area();
int perimeter();
};
int main ()
{
Rectangle myRectangle;
myRectangle.set(5,4);
cout << endl <<“Area is: “ <<myRectangle.area() ;
cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;
Self-Instructional
Material 217
NOTES return 0;
}
Output
Area is: 20
Perimeter is: 18
Explanation
In C++, constructors are special member functions that are automatically called when
an object of a class is created. Constructors are responsible for initializing the object’s
data members and preparing them for use. They have the same name as the class and
do not have a return type (not even void).
There are different types of constructors in C++. Some of them are given below:
Default Constructor: It is a constructor that is automatically generated by the
compiler if no constructor is defined explicitly. It does not take any arguments
and initializes the data members to their default values (e.g., zero for numeric
types, blank for char, etc.).
Parameterized Constructor: It is a constructor that accepts parameters,
allowing you to initialize the object’s data members with specific values at the
time of creation.
Self-Instructional
218 Material
class Rectangle {
private:
int length;
int width;
public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}
int area();
int perimeter();
};
NOTES }
int main ()
{
Rectangle myRectangle;
return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4
Explanation
Rectangle()
is default constructor with same name as class and no return type.
Here data members are assigned default values.
Rectangle myRectangle;
When myRectangle object is created, since member functions are not
initialized so values in default constructor are assigned to length and width.
Example 8.7: Write a program to illustrate parametrized constructors in C++.
/* Online C++ Compiler and Editor */
#include <iostream>
Self-Instructional
220 Material #include <cstring>
class Rectangle {
private:
int length;
int width;
public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}
int area();
int perimeter();
};
NOTES }
int main ()
{
Rectangle myRectangle;
Rectangle myRectangle2(5,6);
return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4
I am in Parametrized constructor
Area is: 30
Perimeter is: 22
Explanation
Rectangle myRectangle;
Here default constructor is called.
class Rectangle {
private:
int length;
int width;
public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}
int area();
int perimeter();
};
NOTES width = w;
}
int main ()
{
Rectangle myRectangle;
Rectangle myRectangle2(5,6);
cout << endl <<“Area is: “ <<myRectangle2.area()
;
cout<< endl <<“Perimeter is: “
<<myRectangle2.perimeter() ;
; NOTES
cout<< endl <<“Perimeter is: “
<<myRectangle3.perimeter() ;
Rectangle myRectangle4(myRectangle2) ;
return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4
I am in Parametrized constructor
Area is: 30
Perimeter is: 22
I am in Copy constructor
Area is: 30
Perimeter is: 22
I am in Copy constructor
Area is: 30
Perimeter is: 22
Explanation
class MyClass {
public:
int value;
// Default constructor
MyClass() {
cout<<endl<<“I am in default constructor”;
value = 0;
}
int main ()
Self-Instructional {
226 Material
NOTES
MyClass obj1;
MyClass obj2(5);
MyClass obj3(3, 4);
return 0;
}
Output
I am in default constructor
I am in constructor with one parameter
I am in constructor with two parameter
Explanation
MyClass obj1;
Calls the default constructor, obj1.value = 0
MyClass obj2(5);
Calls the parameterized constructor with one argument, obj2.value = 5
MyClass obj3(3, 4);
Calls the parameterized constructor with two arguments, obj3.value = 7
By providing Overloaded constructors, you can create objects of the MyClass
class in different ways, depending on your needs.
class MyClass {
public:
// Constructor
MyClass() {
cout<<endl<<“I am in constructor”;
}
// Destructor
~MyClass() {
cout<<endl<<“I am in Destructor”;
}
};
int main()
{
MyClass obj;
return 0;
}
Output
I am in constructor
I am in Destructor
Explanation
MyClass obj;
The destructor is useful for performing cleanup operations such as releasing NOTES
memory, closing file handles, or releasing any other resources acquired by the object.
It ensures that the object leaves a clean state before its memory is deallocated.
Few important points regarding destructors are as follows:
Destructors do not have parameters and do not return any value.
A class can have only one destructor, and it cannot be overloaded.
Destructors are automatically invoked in the reverse order of the object’s
construction within a scope.
class Integer {
public:
int x;
// Constructor
Integer() {
cout<<endl<<“I am in constructor”;
x = 0;
}
Integer(int a) {
c o ut <<en dl<<“ I am in p ar am et riz ed
constructor”;
Self-Instructional
x = a; Material 229
NOTES }
};
int main()
{
Integer obj1(4), obj2(5);
addition(obj1,obj2);
return 0;
}
Output
I am in parametrized constructor
I am in parametrized constructor
I am in copy constructor
my Value is: 5
I am in copy constructor
my Value is: 4
Self-Instructional
230 Material
I am in constructor NOTES
Addition of two Integer Objects is : 9
Explanation
Integer class is created. It contains only public data members and member functions
Integer obj1(4), obj2(5);
obj1 and obj2 objects are created. Parametrized constructor is called and
values are initialized.
addition(obj1,obj2);
When addition function is called and obj1 and obj2 are passed as arguments,
copy of both obj1 and obj2 are created and passed to function.
In addition function, Integer obj3;
is created and default constructor is called.
Addition of two Integer objects is performed.
NOTES Integer(int a) {
c o ut <<en dl<<“ I am in p ar am et riz ed
constructor”;
x = a;
}
Explanation NOTES
Integer obj1(4), obj2(5);
obj1 and obj2 objects are created and parametrized constructor is called.
In subtraction method
temp.x = x - obj.x;
current object is obj2
Passed object is obj1
So obj2.x-obj1.x is performed.
Self-Instructional
Material 233
// Derived class
class Circle : public Shape // Circle class Inherits
Shape Class
{
public:
void calculateArea() {
// Calculate the area of the circle
}
};
Explanation
In above example, the Shape class is the base class, and the Circle class is the derived
class. The Circle class publicly inherits from Shape using the public access specifier.
This means that the draw() function from the Shape class is accessible in the Circle
class.
We can create objects of the derived class and use both the inherited members
and the new members defined in the derived class.
Inheritance allows us to create a hierarchy of classes, where derived classes
can further inherit from other base classes. This helps in achieving code reuse, extensibility,
and provides a way to model real-world relationships between objects.
Self-Instructional
234 Material
// Base class
class Shape {
public:
void draw() {
cout<<endl<<“Hi i am in Shape Base class Draw”;
}
};
// Derived class
class Circle : public Shape {
public:
void calculateArea() {
cout<<endl<<“Hi i am in circle Derived class
calculateArea”;
}
};
int main() {
Circle circle;
circle.draw(); // Accesses the
inherited draw() function
circle.calculateArea(); // Accesses the new
calculateArea() function
return 0;
}
Output
Hi i am in Shape Base class Draw
Hi i am in circle Derived class calculateArea
Self-Instructional
Material 235
NOTES Explanation
class Circle : public Shape
Circle class publicly inherits Shape class.
It can access draw function.
In this example, we can call the draw() function from the base class through
the circle object of the derived class. Additionally, we can call the
calculateArea() function, which is specific to the Circle class.
Inheritance is used to represent is-a relationship. For example
Dog is a mammal.
Circle is a shape.
In C++, classes can be inherited using three access modes, i.e., Public, Private and
Protected.
These access modes are described below:
public: If base class is inherited in public mode, then the data members and
member functions of the base class are inherited by the derived class just as
they are.
private: If base class is inherited in private mode, then the data members and
member functions of the base class, become private members in the derived
class.
protected: If base class is inherited in protected mode, then the public members
of the base class become protected members in the derived class.
To Note: The private members of the base class are always private in the derived
class.
How access specifier of data members and member functions of base class
changes in derived class when inherited by derived class in public, private and protected
mode is depicted below.
Self-Instructional
236 Material
class Shape{
int var1;
int var2;
public:
void area (int var1, int var2); Self-Instructional
}; Material 237
NOTES
void Shape:: area (int var1, int var2)
{
};
int main() {
Rectangle obj1;
obj1.area(4,5);
Self-Instructional
238 Material
Output NOTES
Hi i am in Rectangle area: 20
Explanation
class Rectangle: public Shape
Please note that here both classes Rectangle and Shape have function area
with void return type and two int parameters.
This concept where function in derived class has same signature as that of function
in base class is known as overriding function.
Rectangle obj1;
obj1.area(4,5);
When obj1 is created, obj1 of derived class is called and that of base class
is overridden.
Example 8.15: Write a program to show single inheritance when base class is inherited
using private access modifier by derived class.
#include <iostream>
using namespace std;
class Base{
private:
int var;
public:
void print (int v);
};
Self-Instructional
} Material 239
NOTES
class Derived: private Base {
private:
int xyz;
public:
void displayall (int abc, int pqr);
};
int main() {
Derived obj1;
obj1.displayall(4,5);
}
Output
Hi i am in Derived : 4
Hi i am in Base: 5
Explanation
Since base class is inherited using private, so its data members and member functions
cannot be accessed outside body of class definition.
Self-Instructional
240 Material
When derived class has more than one base class, then it is multiple inheritance. It is
also depicted in Figure 8.4.
class Base1{
public:
Base1()
{
cout<<endl<<“Hi i am in Base 1”;
}
};
class Base2{
public:
Base2()
{
cout<<endl<<“Hi i am in Base 2”;
}
};
NOTES {
cout<<endl<<“Hi i am in Derived”;
}
};
int main() {
Derived obj1;
}
Output
Hi i am in Base 1
Hi i am in Base 2
Hi i am in Derived
Explanation
When we create object of Derived class, constructors of both base classes and derived
classes are called. Constructors of base class are called in order of inheritance. Here
Base class 1 is inherited first, so its constructor is called first.
Self-Instructional
242 Material Fig 8.5 Multilevel Inheritance
class Base{
public:
Base()
{
cout<<endl<<“Hi i am in Base “;
}
};
};
};
int main() {
Derived2 obj1;
Self-Instructional
} Material 243
NOTES Output
Hi i am in Base
Hi i am in Derived
Hi i am in Derived2
When Derived2 object is created, constructors are called in order objects are
instantiated.
First Base class constructor is called, then Derived class constructor is called
and lastly Derived2 class constructor is called.
When we have more than one derived class, inheriting from same base class then it is
known as hierarchical inheritance.
class Base{
public:
Base()
{
cout<<endl<<“Hi i am in Base “;
}
};
Self-Instructional
244 Material
};
};
int main() {
Derived1 obj1;
Derived2 obj2;
}
Output
Hi i am in Base
Hi i am in Derived1
Hi i am in Base
Hi i am in Derived2
Explanation
Both Derived1 and Derived classes inherit from Base class. When their objects are
created, in both cases first base class constructor is called and then derived class Self-Instructional
Material 245
constructor is called.
NOTES
8.12 SOLVED EXERCISE
1. Design a class named Vehicle, having registration number and year as its private
members. Define a suitable constructor and a method to print the details of a
vehicle. Write a C++ program to test the above class.
#include<iostream>
using namespace std;
class Vehicle
{
private:
int registration_number;
int year;
public:
Vehicle()
{
cout<<endl<<“I am in default constructor”;
registration_number = 1234;
year = 2000;
}
Vehicle(int r, int y)
{
cout<<endl<<“I am in parametrized constructor”;
registration_number = r;
year = y;
}
void print();
};
“<<registration_number; NOTES
cout<<endl<<“year is: “<<year;
}
int main()
{
Vehicle obj1;
obj1.print();
class Vehicle
{
private:
int registration_number;
int year;
Self-Instructional
public: Material 247
NOTES Vehicle()
{
cout<<endl<<“I am in default constructor
Vehicle”;
registration_number = 1234;
year = 2000;
}
Vehicle(int r, int y)
{
cout<<endl<<“I am in parametrized constructor
Vehicle”;
registration_number = r;
year = y;
}
void print();
};
Vehicle(r,y); NOTES
}
void print();
};
void Vehicle:: print()
{
cout<<endl<<“Registration Number is:
“<<registration_number;
cout<<endl<<“year is: “<<year;
}
int main()
{
Car obj1;
obj1.print();
Explanation
Car obj1;
obj1.print();
With this line, when obj1 is created, first default constructor of base class that is
vehicle class is called then constructor of derived class car is called. Also in derived
class, Vehicle constructor is called, so “I am in default constructor Vehicle” is printed
again
obj1.print();
Car class overrides print function of vehicle base class. So it will be called.
Now since we cannot have access to registration number and year as they are private
to vehicle class, so we call base class print by using scope resolution operator ::
Vehicle::print();
Exercise
1. Create base class fruit with number of calories as data member. And print function
as member function. Make another derived class Mangoes from fruit class.
Add vitamin and colour as data member. Also override print function.
Self-Instructional
250 Material
2. Create base class account with money and interest rate as data member. And NOTES
print function as member function. Make another derived class current_account
and savings_account. Add appropriately other data member. Also override print
function.
In-Text Questions
1. What is a class in C++?
a) A collection of functions that perform specific tasks.
b) A user-defined data type that represents a blueprint for creating objects.
c) A built-in data structure for storing multiple values of the same type.
d) A function that is used to initialize objects.
2. How do you define a class in C++?
a) class MyClass { } b) class { }
c) define class MyClass: d) define MyClass:
3. Which access specifier is used when you want to make class members
accessible from outside the class?
a) public b) private
c) protected d) friend
4. What is the default access specifier in a class in C++ if none is specified?
a) public b) private
c) protected d) friend
5. What is the keyword used to create an instance of a class (object) in C++?
a) create b) instance
c) new d) object
6. Can a class contain both member functions and member variables?
a) Yes, but it is not recommended.
b) No, a class can only have member functions or member variables.
c) Yes, a class can have both member functions and member variables.
d) It depends on the access specifier used.
Self-Instructional
Material 251
8.13 SUMMARY
Classes and objects are fundamental concepts in C++ that facilitate the organization
and implementation of object-oriented programming (OOP) principles. In C++, a
class is a blueprint or template that defines a structure for creating objects. It
encapsulates data members (attributes) and member functions (methods) that define
the behavior of the objects created from the class. These objects are instances of the
class, and they can have their own unique data while sharing the same set of behaviors
Self-Instructional
defined in the class. Classes provide a way to model real-world entities and their
252 Material
8.14 GLOSSARY
Class: A blueprint or template for creating objects. It defines the structure and
behavior of objects, including data members and member functions.
Object: An instance of a class, representing a real-world entity or concept.
Objects encapsulate data and methods defined in the class.
Instance Variable: A data member (or attribute) of a class that holds the state
or characteristics of an object, with each object having its own set of instance
variables.
Member Function: A function defined within a class, used to perform actions
and operations on the class’s data members and provide behavior to objects.
Encapsulation: The concept of bundling data and the methods that operate on
that data within a class, while controlling access to the data through access
specifiers like private, protected, and public.
Inheritance: A mechanism in C++ that allows a new class (derived class) to
inherit properties and behaviors from an existing class (base class), facilitating
code reuse and hierarchy in object-oriented programming. Self-Instructional
Material 253
NOTES
8.15 ANSWERS TO IN-TEXT QUESTIONS
8.17 REFERENCES
NOTES
8.18 SUGGESTED READINGS
Self-Instructional
Material 255
DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION
UNIVERSITY OF DELHI UNIVERSITY OF DELHI