0% found this document useful (0 votes)
7 views276 pages

CPP Notes

Uploaded by

cultoonmovic4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
7 views276 pages

CPP Notes

Uploaded by

cultoonmovic4
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 276

C++ Programming

Mohammed Shoukat Ali

Mohammed Shoukat Ali 4/15/22 CPP Part-I


Quote

“I can't change the direction of the wind,


but I can adjust my sails to always reach
my destination.”
Jimmy Dean
C++ PROGRAMMING

What is C++
C++ is a general purpose, case-sensitive, free-form programming language that
supports object-oriented, procedural and generic programming.

C++, is an extension to C language. C++ programming language was developed in


1980 by Bjarne Stroustrup at Bell laboratories of AT&T (American Telephone &
Telegraph), in Murray Hill, New Jersey, U.S.A.

Bjarne Stroustrup

Bjarne Stroustrup is known as the founder of C++ language. C++ is a middle-


level language, as it encapsulates both high and low-level language features.

C++ is a superset of C; it means any valid C program is also a valid C++ program.

1
Since the class was a major addition to the original C language, Stroustrup initially
called the new language 'C with classes'. However, later in 1983, the name was
changed to C++.

Object-Oriented Programming (OOPs)

C++ supports the object-oriented programming, the four major pillar of object-
oriented programming (OOPs) used in C++ are:

1. Inheritance

2. Polymorphism

3. Encapsulation

4. Abstraction

Usage of C++

By the help of C++ programming language, we can develop different types of secured
and robust applications:

1. Window application
2. Client-Server application
3. Device drivers
4. Embedded firmware etc

Benefits of C++ over C Language


The major difference being OOPS concept, C++ is an object-oriented language
whereas C is a procedural language. Apart from this there are many other features of
C++ which gives this language an upper hand on C language.

Following features of C++ makes it a stronger language than C,

1. There is Stronger Type Checking in C++.

2
Note: The C++ compiler produces errors in some cases, but in others, it
converts data to the correct type.

2. All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc
makes it more worthy and useful for programmers.

3. C++ supports and allows user defined operators (i.e., Operator Overloading)
and function overloading is also supported in it.

4. Exception Handling is there in C++.

5. The Concept of Virtual functions and also Constructors and Destructors for
Objects.

6. Inline Functions in C++ instead of Macros in C language. Inline functions make


complete function body act like Macro, safely.

7. Variables can be declared anywhere in the program in C++, but must be


declared before they are used.

8. C contains 32 keywords, and C++ supports 52 keywords.

9. A namespace is a feature that groups the entities like classes, objects, and
functions under some specific name. C does not contain the namespace feature,
while C++ supports the namespace feature that avoids the name collisions.

10. In C, scanf and printf functions are used for input and output operations,
respectively, while in C++, cin and cout are used for input and output operations,
respectively.

11. C program uses <stdio.h> header file while C++ program


uses <iostream.h> header file.

Differences in a tabular form.

No C C++
.

1) C follows the procedural style C++ is multi-paradigm. It supports


programming. both procedural and object oriented.

2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for

3
outside users.

3) C follows the top-down C++ follows the bottom-up approach.


approach.

4) C does not support function C++ supports function overloading.


overloading.

5) In C, you can't use functions in In C++, you can use functions in


structure. structure.

6) C does not support reference C++ supports reference variables.


variables.

7) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations.

8) Operator overloading is not Operator overloading is possible in C++.


possible in C.

9) C programs are divided C++ programs are divided


into procedures and modules into functions and classes.

10) C does not provide the feature of C++ supports the feature of
namespace. namespace.

11) Exception handling is not easy in C. C++ provides exception handling using
It has to perform using other Try and Catch block.
functions.

12) C does not support the inheritance. C++ supports inheritance.

Differences between Procedural and Object-Oriented Programming


Procedural Programming:
Procedural Programming can be defined as a programming model which is derived
from structured programming, based upon the concept of calling procedure.
Procedures, also known as routines, subroutines or functions, simply consist of a
series of computational steps to be carried out. During a program’s execution, any
given procedure might be called at any point, including by other procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.

Object Oriented Programming:

4
Object oriented programming can be defined as a programming model which is
based upon the concept of objects. Objects contain data in the form of attributes and
code in the form of methods. In object-oriented programming, computer programs
are designed using the concept of objects that interact with real world. Object
oriented programming languages are various but the most popular ones are class-
based, meaning that objects are instances of classes, which also determine their
types.
Languages used in Object Oriented Programming:
Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart, Swift, Scala.

Difference between Procedural Programming and Object-Oriented Programming:

Procedural Oriented Programming Object Oriented Programming

In procedural programming, program is In object-oriented programming,


divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows top Object oriented programming


down approach. follows bottom up approach.

Object oriented programming have


There is no access specifier in access specifiers like private, public,
procedural programming. protected etc.

Adding new data and function is not Adding new data and function is
easy. easy.

Procedural programming does not have Object oriented programming


any proper way for hiding data so it provides data hiding so it is more
is less secure. secure.

In procedural programming, overloading Overloading is possible in object-


is not possible. oriented programming.

In object-oriented programming,
In procedural programming, function is data is more important than
more important than data. function.

Procedural programming is based Object oriented programming is


on unreal world. based on real world.

5
Procedural Oriented Programming Object Oriented Programming

Examples: C, FORTRAN, Pascal, Basic Examples: C++, Java, Python, C#


etc. etc.

Object Oriented programming is a programming style that is associated with the


concept of Class, Objects and various other concepts revolving around these two,
like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

Let us try to understand a little about all these, through a simple example. Human
Beings are living forms, broadly categorized into two types, Male and Female. Right?
Its true. Every Human being (Male or Female) has two legs, two hands, two eyes, one
nose, one heart etc. There are body parts that are common for Male and Female, but
then there are some specific body parts, present in a Male which are not present in a
Female, and some body parts present in Female but not in Males.

All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female,
performs some common functions, but there are some specifics to both, which is not
valid for the other. For example: A Female can give birth, while a Male cannot, so this
is only for the Female.

Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and
OOPS. Here we will try to explain all the OOPS concepts through this example and
later we will have the technical definitions for all this.

6
Class
Here we can take Human Being as a class. A class is a blueprint for any functional
entity which defines its properties and its functions. Like Human Being, having body
parts, and performing various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and
functions like walk, talk, eat, see etc. Male and Female are also classes, but most of
the properties and functions are included in HumanBeing, hence they can inherit
everything from class HumanBeing using the concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say,
Human Being, Male or Female, we just mean a kind, you, your friend, me we are the
forms of these classes. We have a physical existence while a class is just a logical
definition. We are the objects.

Abstraction
Abstraction means, showcasing only the required things to the outside world while
hiding the details. Continuing our example, Human Being's can talk, walk, hear, eat,
but the details are hidden from the outside world. We can take our skin as the
Abstraction factor in our case, hiding the inside mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are bended to help
us walk. Our hands, help us hold things. This binding of the properties to functions is
called Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by
either changing how it is done or by changing the parts using which it is done. Both
the ways have different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to
perform something. Hence this is called Overloading.

7
And if there is a defined way of walking, but I wish to walk differently, but using my
legs, like everyone else. Then I can walk like I want; this will be called as Overriding.

OOPS Concept Definitions


Now, let us discuss some of the main features of Object-Oriented Programming which
you will be using in C++(technically).

1. Objects

2. Classes

3. Abstraction

4. Encapsulation

5. Inheritance

6. Overloading

7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data
members and uses various member functions to perform tasks.

Objects are the basic run-time entities in an object-oriented system.

Class
It is similar to structures in C language. Class can also be defined as user defined data
type but it also contains functions in it. So, class is basically a blueprint for object. It
declare & defines what data variables the object will have and what operations can be
performed on the class's object.

Abstraction
Abstraction refers to showing only the essential features of the application and hiding
the details. In C++, classes can provide methods to the outside world to access & use
the data variables, keeping the variables hidden from direct access, or classes can
even declare everything accessible to everyone, or maybe just to the classes
inheriting it. This can be done using access specifiers.

8
Since the classes use the concept of data abstraction, they are known as Abstract
Data Types (ADT).

Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables
and functions together in class.

The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it. These functions provide the
interface between the object's data and the program. This insulation of the data from
direct access by the program is called data hiding or information hiding.

Inheritance
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.

Inheritance is a way to reuse once written code again and again. The class which is
inherited is called the Base class & the class which inherits is called
the Derived class. They are also called parent and child class.

So, when, a derived class inherits a base class, the derived class can use all the
functions which are defined in base class, hence making code reusable.

9
Inheritance
Polymorphism
It is a feature, which lets us create functions with same name but different arguments,
which will perform different actions. That means, functions with same name, but
functioning in different ways. Or, it also allows us to redefine a function to provide it
with a completely new definition.

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means


the ability to take more than one form. An operation may exhibit different behaviours
in different instances. The behaviour depends upon the types of data used in the
operation. For example, consider the operation of addition. For two numbers, the
operation will generate a sum. If the operands are strings, then the operation would
produce a third string by concatenation. The process of making an operator to exhibit
different behaviours in different instances is known as operator overloading.

10
Polymorphism
The figure above illustrates that a single function name can be used to handle
different number and different types of arguments. This is something similar to a
particular word having several different meanings depending on the context. Using a
single function name to perform different types of tasks is known as function
overloading.

Polymorphism is extensively used in implementing inheritance.

Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors
produced at runtime.

11
Concepts of OOP are:

 Objects: These are the fundamental run-time sections that trade data
once the program is sent off.
 Classes: Similar kinds of items are called classes.
 Inheritance: This is the precondition of reusability in OOP in light of the
fact that legacy permits a particular sort of object to procure the qualities
of an article having a place with an alternate class.
 Polymorphism: It’s a component that addresses an item’s inclination to
play out numerous tasks.
 Data encapsulation and abstraction: This empowers the framework to
uncover basic elements without the need to give any extra subtleties.

C++ What is OOP?

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating objects
that contain both data and functions.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and 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.

Note: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You should extract out the codes that are common for the application, and place
them at a single place and reuse them instead of repeating it.

C++ What are Classes and Objects?

Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:
12
So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and functions
from the class.

C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the
class. These are often referred to as "class members".

A class is a user-defined data type that we can use in our program, and it works as an
object constructor, or a "blueprint" for creating objects.

Benefits of OOP
 We can build the programs from standard working modules that
communicate with one another, rather than having to start writing the code
from scratch which leads to saving of development time and higher
productivity,
13
 OOP language allows to break the program into the bit-sized problems that
can be solved easily (one object at a time).
 The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any
interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs
which cannot be invaded by the code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use
of existing classes.
 Message passing techniques is used for communication between objects
which makes the interface descriptions with external systems much simpler.
 The data-centered design approach enables us to capture more details of
model in an implementable form.
While it is possible to incorporate all these features in an OOP, their importance
depends upon the type of project and preference of the programmer. This
technology is still developing and current products may be superseded quickly.

Developing a software is easy to use makes it hard to build.

Disadvantages of OOP
 The length of the programmes developed using OOP language is much
larger than the procedural approach. Since the programme becomes larger
in size, it requires more time to be executed that leads to slower execution
of the programme.
 We can not apply OOP everywhere as it is not a universal language. It is
applied only when it is required. It is not suitable for all types of problems.
 Programmers need to have brilliant designing skill and programming skill
along with proper planning because using OOP is little bit tricky.
 OOPs take time to get used to it. The thought process involved in object-
oriented programming may not be natural for some people.
 Everything is treated as object in OOP so before applying it we need to have
excellent thinking in terms of objects.

14
Comparison Table for Advantages and Disadvantages Of OOP

Advantages Disadvantages

We can reuse the code multiple times using


Size is larger than other programs
class

Inherit the class to subclass for data


It required a lot of effort to create
redundancy

It is easy to maintain and modify It is slower than other programs

It is not suitable for some sorts of


It maintains the security of data
problems

Low-cost development It takes time to get used to it.

Applications of Object-Oriented Programming


Main application areas of OOP are:

1. User interface design such as windows, menu.


2. Real Time Systems
3. Simulation and Modelling
4. Object oriented databases
5. AI and Expert System
6. Neural Networks and parallel programming
7. Decision support and office automation systems etc.

C++ Features

C++ is a widely used programming language.

It provides a lot of features that are given below.

1. Simple
2. Abstract Data types
3. Machine Independent or Portable
4. Mid-level programming language

15
5. Structured programming language
6. Rich Library
7. Memory Management
8. Quicker Compilation
9. Pointers
10. Recursion
11. Extensible
12. Object-Oriented
13. Compiler based
14. Reusability
15. National Standards
16. Errors are easily detected
17. Power and Flexibility
18. Strongly typed language
19. Redefine Existing Operators
20. Modelling Real-World Problems
21. Clarity

1) Simple

C++ is a simple language because it provides a structured approach (to break the
problem into parts), a rich set of library functions, data types, etc.

2) Abstract Data types

In C++, complex data types called Abstract Data Types (ADT) can be created using
classes.

3) Portable

C++ is a portable language and programs made in it can be run on different


machines.

16
4) Mid-level / Intermediate programming language

C++ includes both low-level programming and high-level language so it is known as a


mid-level and intermediate programming language. It is used to develop system
applications such as kernel, driver, etc.

5) Structured programming language

C++ is a structured programming language. In this we can divide the program into
several parts using functions.

6) Rich Library

C++ provides a lot of inbuilt functions that make the development fast. Following are
the libraries used in C++ programming are:

1. <iostream>
2. <cmath>
3. <cstdlib>
4. <fstream>
7) Memory Management

C++ provides very efficient management techniques. The various memory


management operators help save the memory and improve the program's efficiency.
These operators allocate and deallocate memory at run time. Some common memory
management operators available C++ are new, delete etc.

8) Quicker Compilation

C++ programs tend to be compact and run quickly. Hence the compilation and
execution time of the C++ language is fast.

9) Pointer

C++ provides the feature of pointers. We can use pointers for memory, structures,
functions, array, etc. We can directly interact with the memory by using the pointers.

17
10) Recursion

In C++, we can call the function within the function. It provides code reusability for
every function.

11) Extensible

C++ programs can easily be extended as it is very easy to add new features into the
existing program.

12) Object-Oriented

In C++, object-oriented concepts like data hiding, encapsulation, and data abstraction
can easily be implemented using keyword class, private, public, and protected access
specifiers. Object-oriented makes development and maintenance easier.

13) Compiler based

C++ is a compiler-based programming language, which means no C++ program can


be executed without compilation. C++ compiler is easily available, and it requires
very little space for storage. First, we need to compile our program using a compiler,
and then we can execute our program.

14) Reusability

With the use of inheritance of functions programs written in C++ can be reused in any
other program of C++. You can save program parts into library files and invoke them
in your next programming projects simply by including the library files. New programs
can be developed in lesser time as the existing code can be reused. It is also possible
to define several functions with same name that perform different task. For Example:
abs () is used to calculate the absolute value of integer, float and long integer.

15) National Standards

C++ has national standards such as ANSI.

18
16) Errors are easily detected

It is easier to maintain a C++ programs as errors can be easily located and rectified.
It also provides a feature called exception handling to support error handling in your
program.

17) Power and Flexibility

C++ is a powerful and flexible language because of most of the powerful flexible and
modern UNIX operating system is written in C++. Many compilers and interpreters for
other languages such as FORTRAN, PERL, Python, PASCAL, BASIC, LISP, etc., have
been written in C++. C++ programs have been used for solving physics and
engineering problems and even for animated special effects for movies.

18) Strongly typed language

The list of arguments of every function call is typed checked during compilation. If
there is a type mismatch between actual and formal arguments, implicit conversion is
applied if possible. A compile-time occurs if an implicit conversion is not possible or if
the number of arguments is incorrect.

19) Redefine Existing Operators

C++ allows the programmer to redefine the meaning of existing operators such as +,
-. For Example, The "+" operator can be used for adding two numbers and
concatenating two strings.

20) Modelling real-world problems

The programs written in C++ are well suited for real-world modeling problems as
close as possible to the user perspective.

21) Clarity

The keywords and library functions used in C++ resemble common English words.

How to Download and Install C++ IDE on Windows

What is Dev-C++?
19
Dev-C++, developed by Bloodshed Software, is a fully-featured graphical IDE
(Integrated Development Environment) for C and C++ programming. It is distributed
under the GNU General Public License for programming in C and C++.

How to Download and Install Dev C++ on Windows


There are many compilers available for C++ programming. You can download
anyone. Here, we are going to use Dev C++. It will work for both C++ and C
programming languages.
To install Dev C++ software, you need to follow the following steps.

Step 1) First you must download the Dev C++ on your Windows machine. Visit to
Download Dev C++: http://www.bloodshed.net/

Step 2) There are packages for different Operating Systems.

Step 3) Under package Dev-C++ 5.0 (4.9.9.2) with Mingw/GCC 3.4.2 compiler and
GDB 5.2.1 debugger (9.0 MB) Click on the link “Download from SourceForge”.

14.1Mhat is Java - Java Programming Tutorial

20
Step 4) This package will download C++ .exe file for Windows that can be used to
install on Windows 7/8/XP/Vista/10.

Step 5) You will direct to SourceForge website, and your C++ download will start
automatically.

 Click on save button to save. By default, it is saved in “Downloads” folder.


 After the download completes, go to the saved .exe file and click on it to Run.
 The installer will ask you a language to select. Select “English” and click on
“OK”.

 Then screen for license agreement will appear. Click on “I agree” to proceed
further.

21
Step 6) In this step,

1. You can see different components of Dev C++ that will be installed with this
package.
2. Just click on “next” button.

Step 7) In this step,


22
1. By default, the destination folder is in C drive. You are free to change this
destination folder but make sure you have enough memory.
2. Click on “Install” button.

In the next screen, installation begins

23
Now, Dev C++ is installed successfully on your Windows. Select” Run Dev C++” to
run it and click on ” Finish” button.

That’s it! Now you are ready to compile your C or C++ programs with Dev C++
compiler.

Features Of Dev-C++ IDE


Here are some important features of Dev-C++ IDE:

 Dev-C++ IDE allows us to use integrated debugging using GDB.


 Localization feature that provides support for multiple languages.
 Offers editing and compiling the resource files.
 It has a inbuilt find and replace facility.
 Helps you to create your own project templates to create project types.
 It offers support for class browser as well as debug variable browser.
 Provides project manager feature that helps you to manage various projects.
 Provides CVS support for source code management.

24
Syntax and Structure of C++ program

File: main.cpp

#include <iostream>
int main() {
std::cout << "Hello C++ Programming";
return 0;
}
Header files are included at the beginning just like in C program. Here iostream is a
header file which provides us with input & output streams. Header files contained
predeclared function libraries, which can be used by users for their ease.

Using namespace std, tells the compiler to use standard namespace. Namespace
collects identifiers used for class, object and variables. Namespace can be used by
two ways in a program, either by the use of using statement at the beginning, like we
did in above mentioned program or by using name of namespace as prefix before the
identifier with scope resolution (::) operator.

Example: std::cout << "A";

main(), is the function which holds the executing part of program its return type
is int.

cout <<, is used to print anything on screen, same as printf in C


language. cin and cout are same as scanf and printf, only difference is that you do
not need to mention format specifiers like, %d for int etc, in cout & cin.

Comments in C++ Program


For single line comments, use // before mentioning comment, like

cout<<"single line"; // This is single line comment

For multiple line comment, enclose the comment between /* and */


/*this is
a multiple line
comment */

25
C++ Basic Input/Output

C++ I/O operation is using the stream concept. Stream is the sequence of bytes or
flow of data. It makes the performance fast.

If bytes flow from main memory to device like printer, display screen, or a network
connection, etc, this is called as output operation.

If bytes flow from device like printer, display screen, or a network connection, etc to
main memory, this is called as input operation.

I/O Library Header Files

Let us see the common header files used in C++ programming are:

Header Function and Description


File

<iostream It is used to define the cout, cin and cerr objects, which correspond
> to standard output stream, standard input stream and standard error
stream, respectively.

<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.

<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)

The cout is a predefined object of ostream class. It is connected with the standard
output device, which is usually a display screen. The cout is used in conjunction with
stream insertion operator (<<) to display the output on a console

Let's see the simple example of standard output stream (cout):

#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}

Output:

Value of ary is: Welcome to C++ tutorial


26
Standard input stream (cin)

The cin is a predefined object of istream class. It is connected with the standard
input device, which is usually a keyboard. The cin is used in conjunction with stream
extraction operator (>>) to read the input from a console.

Let's see the simple example of standard input stream (cin):

#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}

Output:

Enter your age: 22


Your age is: 22

Standard end line (endl)

The endl is a predefined object of ostream class. It is used to insert a new line
character and flushes the stream.

#include <iostream>
using namespace std;
int main( ) {
cout << "Welcome";
cout << "C++ Programming"<<endl;
cout << "End of line"<<endl;
}

Example 1:

//program demo : Single Line Comment

27
/* My : Multi Line Comment
first
program
in
C++ */
#include<iostream>
using namespace std;
namespace saipali
{
int n=10;
void fun()
{
cout << "This is fun() of n1"<< endl;
}
}
namespace sitm
{
int n=25;
}
int main()
{
std::cout<<"Welcome to C++ Programming..."<<endl;
using namespace saipali;
// cout<<saipali::n<<endl;
cout<<n<<endl;
saipali::fun();
cout<<sitm::n<<endl;
return 0;
}
Example 2:

// C++ program to illustrate the use


// of namespace with same name of
// function and variables
#include <iostream>
using namespace std;

28
// Namespace n1
namespace n1 {
int x = 2;

// Function to display the message


// for namespace n1
void fun()
{
cout << "This is fun() of n1"
<< endl;
}
}

// Namespace n2
namespace n2 {

int x = 5;

// Function to display the message


// for namespace n2
void fun()
{
cout << "This is fun() of n2"
<< endl;
}
}

// Driver Code
int main()
{
// The methods and variables called
// using scope resolution(::)
cout << n1::x << endl;

// Function call
n1::fun();

cout << n2::x << endl;

// Function ca;;
n2::fun();

return 0;
}

Output:
2
This is fun() of n1
5
29
This is fun() of n2

Explanation:
 In the above example program, both n1 and n2 have a variable and
function of the same name x and fun() respectively.
 The namespace is used to decrease or limit the scope of any variable or
function.
 As in the above code variable x and method fun() were limited to
namespaces n1 and n2. Thus, their scope was not outside the n1 or n2.
 Every time using the scope resolution operator (::) in a variable or a
function defined is not required, it can be solved with “using” directive.
 The using directive means to include the whole code written in the
namespace in the closing scope.

Example 3:

// C++ program to demonstrate the use


// of "using" directive
#include <iostream>
using namespace std;

// Namespace n1
namespace n1 {
int x = 2;
void fun()
{
cout << "This is fun() of n1"
<< endl;
}
}

// Namespace is included
using namespace n1;

// Driver Code
int main()
{
cout << x << endl;

// Function Call
fun();

30
return 0;
}

Output:
2
This is fun() of n1

Explanation:
 In the above program, after writing “using namespace n1“, there is no need

to use the scope resolution for utilizing the members of n1.


 It can be interpreted as “using” copies of the code written in the namespace
to the scope in which it has been written.

Scope Resolution Operator:

In C, the global version of a variable cannot be accessed from within the inner block.
C++ resolves this problem by introducing a new operator :: called the scope
resolution operator. This can be used to uncover a hidden variable. It takes the
following form:

:: variable-name

This operator allows access to the global version of a variable. For example, ::count
means the global version of the variable count.

Example:

#include<iostream>

using namespace std;

int m=10; //global m

int main()

int m=20; //m is redeclared, local to main

cout<<"m = "<<m<<endl;

cout<<"::m = "<<::m<<endl;

return 0;

31
}

Output:

m=20

::m=10

Example:

#include<iostream>
using namespace std;
int m=10; //global m
int main()
{
int m=20; //m is redeclared, local to main
{
int m=30;
cout<<"We are in inner block"<<endl;
cout<<"m = "<<m<<endl;
cout<<"::m = "<<::m<<endl;
}
cout<<"We are in outer block"<<endl;
cout<<"m = "<<m<<endl;
cout<<"::m = "<<::m<<endl;
return 0;
}

Output:
We are in inner block
m = 30
::m = 10
We are in outer block
m = 20
::m = 10

C++ Manipulators - endl, setw, setprecision, setf


Formatting output using manipulators

32
Formatted output is very important in development field for easily read and
understand.

C++ offers the several input/output manipulators for formatting; commonly used
manipulators are given below.

Manipulator Declaration in

endl iostream.h

setw iomanip.h

setprecision iomanip.h

setf iomanip.h

endl

endl manipulator is used to terminate a line and flushes the buffer.

Difference b/w '\n' and endl

When writing output in C++, you can use either std::endl or '\n' to produce a newline,
but each has a different effect.

 std::endl sends a newline character '\n' and flushes the output buffer.
 '\n' sends the newline character, but does not flush the output buffer.

The distinction is very important if you're writing debugging messages that you really
need to see immediately, you should always use std::endl rather than '\n' to force the
flush to take place immediately.

The following is an example of how to use both versions, although you cannot see the
flushing occuring in this example.

#include <iostream.h>
int main()
{
cout<<"USING '\\n' ...\n";
cout<<"Line 1 \nLine 2 \nLine 3 \n";
cout<<"USING end ..."<< endl;

33
cout<< "Line 1" << endl << "Line 2" << endl << "Line 3" << endl;
return 0;
}

Output

USING '\n' ...


Line 1
Line 2
Line 3
USING end ...
Line 1
Line 2
Line 3

setw() and setfill() manipulators

setw manipulator sets the width of the filed assigned for the output.

The field width determines the minimum number of characters to be written in some
output representations. If the standard width of the representation is shorter than the
field width, the representation is padded with fill characters (using setfill).

setfill character is used in output insertion operations to fill spaces when results have
to be padded to the field width.

Syntax

setw([number_of_characters]);

setfill([character]);

Consider the example

#include <iostream.h>
#include <iomanip.h>
int main()

34
{
cout<<"USING setw() ..............\n";
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type- I]...\n";


cout<< setfill('0');
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type-II]...\n";


cout<< setfill('-')<< setw(10) <<11<<"\n";
cout<< setfill('*')<< setw(10) <<2222<<"\n";
cout<< setfill('@')<< setw(10) <<33333<<"\n";
cout<< setfill('#')<< setw(10) <<4<<"\n";
return 0;
}

Output

USING setw() ..............


11
2222
33333
4
USING setw() & setfill() [type- I]...
0000000011
0000002222
0000033333
0000000004
USING setw() & setfill() [type-II]...

35
--------11
******2222
@@@@@33333
#########4

setf() and setprecision() manipulator

setprecision manipulator sets the total number of digits to be displayed, when


floating point numbers are printed.

Syntax

setprecision([number_of_digits]);

cout<<setprecision(5)<<1234.537;

// output will be : 1234.5

On the default floating-point notation, the precision field specifies the maximum
number of meaningful digits to display in total counting both those before and those
after the decimal point. Notice that it is not a minimum and therefore it does not pad
the displayed number with trailing zeros if the number can be displayed with less
digits than the precision.

In both the fixed and scientific notations, the precision field specifies exactly how
many digits to display after the decimal point, even if this includes trailing decimal
zeros. The number of digits before the decimal point does not matter in this case.

Syntax

setf([flag_value],[field bitmask]);

field bitmask flag values

adjustfield left, right or internal

basefield dec, oct or hex

floatfield scientific or fixed

36
Consider the example

#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"USING fixed .......................\n";
cout.setf(ios::floatfield,ios::fixed);
cout<< setprecision(5)<<1234.537<< endl;

cout<<"USING scientific ..................\n";


cout.setf(ios::floatfield,ios::scientific);
cout<< setprecision(5)<<1234.537<< endl;
return 0;
}

Output

USING fixed .......................


1234.53700
USING scientific ..................
1234.5

Consider the example to illustrate base fields

#include <iostream.h>
#include <iomanip.h>
int main()
{
int num=10;

cout<<"Decimal value is :"<< num << endl;

cout.setf(ios::basefield,ios::oct);
cout<<"Octal value is :"<< num << endl;

37
cout.setf(ios::basefield,ios::hex);
cout<<"Hex value is :"<< num << endl;
return 0;
}

38
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

Keywords

Keywords are reserved words which have fixed meaning, and its meaning cannot be
changed. The meaning and working of these keywords are already known to the
compiler. C++ has more numbers of keyword than C, and those extra ones have
special working capabilities.

Examples:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Additional

bool catch class delete


export false friend inline
namespace new this throw
private public protected true
try virtual using etc.

39
Identifiers:

Identifiers are names given to different entries such as variables, structures, and
functions. Also, identifier names should have to be unique because these entities are
used in the execution of the program.

Rules for defining variables

1. A variable can have alphabets, digits and underscore.


2. A variable name can start with alphabet and underscore only. It can't start with
digit.
3. No white space is allowed within variable name.
4. A variable name must not be any reserved word or keyword e.g., char, float etc.

Valid variable names:

int a;
int _ab;
int a30;

Invalid variable names:

int 4;
int x y;
int double;

Constants:

Constants are like a variable, except that their value never changes during execution
once defined.

Examples:

1. Integer constants – Example: 0, 1, 1218, 12482


2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 ) 8 =
(11)10, Hexadecimal: (013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “C++ Programming”

40
Strings:

Strings are objects that signify sequences of characters. Strings are nothing but an
array of characters ended with a null character (‘\0’). This null character indicates
the end of the string. Strings are always enclosed in double-quotes. Whereas, a
character is enclosed in single quotes in C and C++.

Special Symbols:
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. [] () {}, ; * = #

 Brackets[]: Opening and closing brackets are used as array element


reference. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls
and function parameters.
 Braces{}: These opening and ending curly braces mark the start and end
of a block of code containing more than one executable statement.
 Comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
 Colon(:): It is an operator that essentially invokes something called an
initialization list.
 Semicolon(;): It is known as a statement terminator. It indicates the end
of one logical entity. That’s why each individual statement must be ended
with a semicolon.
 Asterisk (*): It is used to create a pointer variable and for the
multiplication of variables.
 Assignment operator(=): It is used to assign values and for the logical
operation validation.
 Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
Operators:

Operators are symbols that trigger an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.

41
Depending on the number of operands that an operator can act upon, operators can
be classified as follows:

 Unary Operators: Those operators that require only a single operand to


act upon are known as unary operators. For Example, increment and
decrement operators
 Binary Operators: Those operators that require two operands to act upon
are called binary operators. Binary operators are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that require three operands to act upon
are called ternary operator. Conditional Operator(?) is also called ternary
operator.
Syntax: (Expression1)? expression2: expression3;

DATA TYPES:

Data types in any of the language mean that what are the various type of data the
variables can have in that particular language. Information is stored in computer
memory with different data types. Whenever a variable is declared it becomes
necessary to define a data type that what will be the type of data that variable can
hold.

Data Types available in C++:

1. Primary (Built-in) Data Types:


o character
o integer
o floating point
o boolean
o double floating point
o void

42
o wide character
2. User Defined Data Types:
o Structure
o Union
o Class
o Enumeration
3. Derived Data Types:
o Array
o Function
o Pointer
o Reference
Both C and C++ compilers support the fundamental, i.e., the built-in data types.
Taking void as an exception the basic data type may have several modifiers, and
these modifiers are used to serve the data types in various situations.

The lists of modifiers used in C++ are:

 signed
 unsigned
 long
 short

Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:

Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1


43
unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4

double 8

long double 12

wchar_t 2 or 4 1 wide character

Example:

#include <iostream>
using namespace std;

int main() {
cout << "Size of char is " << sizeof(char) << endl;
cout << "Size of int is " << sizeof(int) << endl;
cout << "Size of float is " << sizeof(float) << endl;
cout << "Size of short int is " << sizeof(short int) << endl;
cout << "Size of long int is " << sizeof(long int) << endl;
cout << "Size of double is " << sizeof(double) << endl;
cout << "Size of wchar_t is " << sizeof(wchar_t) << endl;
return 0;
}

Typedef:

It is used to create a new data type. But it is commonly used to change the existing
data type with another name.

Syntax:

typedef [data_type] synonym;


44
or
typedef [data_type] new_data_type;

Example:
typedef int integer;
integer rollno;

Example:

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
typedef int integer;
integer rollno, age, mobile;
cout<<"Enter your rollno: ";
cin>>rollno;
cout<<"Enter your age: ";
cin>>age;
cout<<"Enter mobile no: ";
cin>>mobile;
cout<<"Roll No: "<<rollno<<" Age: "<<age<<" Mobile No: "<<mobile<<endl;

return 0;
}

C++ Expression

C++ expression consists of operators, constants, and variables which are arranged
according to the rules of the language. It can also contain function calls which return
values. An expression can consist of one or more operands, zero or more operators to
compute a value. Every expression produces some value which is assigned to the
variable with the help of an assignment operator.

45
Examples of C++ expression:

1. (a+b) - c
2. (x/y) -z
3. 4a2 - 5b +c
4. (a+b) * (x+y)

46
Example:

#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration.
x=(3/2) + 2; // constant expression
cout<<"Value of x is : "<<x; // displaying the value of x.
return 0;
}

47
C++ Operators:

An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C


language.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operator

6. Unary operator

7. Ternary or Conditional Operator

8. Misc Operator

48
49
C++ Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data.
For example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly, there are various
other arithmetic operators in C++.

Operato
Operation
r

+ Addition

- Subtraction

* Multiplication

/ Division

Modulo Operation (Remainder after


%
division)

Example 1: Arithmetic Operators

#include <iostream>
using namespace std;

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

// printing the sum of a and b

50
cout << "a + b = " << (a + b) << endl;

// printing the difference of a and b


cout << "a - b = " << (a - b) << endl;

// printing the product of a and b


cout << "a * b = " << (a * b) << endl;

// printing the division of a by b


cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b


cout << "a % b = " << (a % b) << endl;

return 0;
}

Output

a +b=9
a -b=5
a * b = 14
a /b=3
a %b=1

Here, the operators +, - and * compute addition, subtraction, and multiplication


respectively as we might have expected.

/ Division Operator

Note the operation (a / b) in our program. The / operator is the division operator.
As we can see from the above example, if an integer is divided by another integer, we
will get the quotient. However, if either divisor or dividend is a floating-point number,
we will get the result in decimals.

In C++,

7/2 is 3

7.0 / 2 is 3.5

51
7 / 2.0 is 3.5

7.0 / 2.0 is 3.5

% Modulo Operator

The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the


remainder is 1.

Note: The % operator can only be used with integers.

Increment and Decrement Operators

C++ also provides increment and decrement operators: ++ and -- respectively.


 ++ increases the value of the operand by 1
 -- decreases it by 1
For example,

int num = 5;

// increment operator
++num; // 6

Here, the code ++num; increases the value of num by 1.

Example 2: Increment and Decrement Operators

Output

result_a = 11
result_b = 99

In the above program, we have used the ++ and -- operators as prefixes (++a and
--b). However, we can also use these operators as postfix (a++ and b--).

52
C++ Assignment Operators

In C++, assignment operators are used to assign values to variables. For example,

// assign 5 to a
a = 5;

Here, we have assigned a value of 5 to the variable a.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example 3: Assignment Operators

#include <iostream>
using namespace std;

int main() {
int a, b;

// 2 is assigned to a
a = 2;

// 7 is assigned to b

53
b = 7;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a


a += b; // a = a + b
cout << "a = " << a << endl;

return 0;
}

Output

a=2
b=7

After a += b;
a=9

C++ Relational Operators

A relational operator is used to check the relationship between two operands. For
example,

// checks if a is greater than b


a > b;

Here, > is a relational operator. It checks if a is greater than b or not.

If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

Operator Meaning Example

54
== Is Equal To 3 == 5 gives us false

!= Not Equal To 3!= 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true

Example 4: Relational Operators

#include <iostream>
using namespace std;

int main() {
int a, b;
a = 3;
b = 5;
bool result;

result = (a == b); // false


cout << "3 == 5 is " << result << endl;

result = (a != b); // true


cout << "3 != 5 is " << result << endl;

result = a > b; // false


cout << "3 > 5 is " << result << endl;

result = a < b; // true


cout << "3 < 5 is " << result << endl;

result = a >= b; // false


cout << "3 >= 5 is " << result << endl;

result = a <= b; // true


cout << "3 <= 5 is " << result << endl;

55
return 0;
}

Output

3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

Note: Relational operators are used in decision-making and loops.

C++ Logical Operators


Logical operators are used to check whether an expression is true or false. If the
expression is true, it returns 1 whereas if the expression is false, it returns 0.

Operato
Example Meaning
r

Logical AND.
expression1 &&
&& True only if all the operands
expression2
are true.

Logical OR.
expression1 ||
|| True if at least one of the
expression2
operands is true.

Logical NOT.
! !expression True only if the operand is
false.

In C++, logical operators are commonly used in decision making. To further


understand the logical operators, let's see the following examples,

Suppose,

56
a=5
b=8

Then,

(a > 3) && (b > 5) evaluates to true


(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true


(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true


!(a > 3) evaluates to false

Example 5: Logical Operators

#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5); // true


cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false


cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false


cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true


cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true


cout << "(3 != 5) || (3 > 5) is " << result << endl;

57
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true


cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false


cout << "!(5 == 5) is " << result << endl;

return 0;
}

Output

(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Explanation of logical operator program


1. (3 != 5) && (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 <
5) are 1 (true).
2. (3 == 5) && (3 < 5) evaluates to 0 because the operand (3 == 5) is 0 (false).
3. (3 == 5) && (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 >
5) are 0 (false).
4. (3 != 5) || (3 < 5) evaluates to 1 because both operands (3 != 5) and (3 <
5) are 1 (true).
5. (3 != 5) || (3 > 5) evaluates to 1 because the operand (3 != 5) is 1 (true).

58
6. (3 == 5) || (3 > 5) evaluates to 0 because both operands (3 == 5) and (3 >
5) are 0 (false).
7. !(5 == 2) evaluates to 1 because the operand (5 == 2) is 0 (false).
8. !(5 == 5) evaluates to 0 because the operand (5 == 5) is 1 (true).

C++ Bitwise Operators


In C++, bitwise operators are used to perform operations on individual bits. They can
only be used alongside char and int data types.

Operator Description

& Binary AND

| Binary OR

^ Binary XOR

~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

C++ Bitwise Operators


In C++, bitwise operators perform operations on integer data at the individual bit-
level. These operations include testing, setting, or shifting the actual bits. For
example,

a & b;
a | b;

Here is a list of 6 bitwise operators included in C++.


59
Operator Description

& Bitwise AND Operator

| Bitwise OR Operator

^ Bitwise XOR Operator

~ Bitwise Complement Operator

<< Bitwise Shift Left Operator

>> Bitwise Shift Right Operator

These operators are necessary because the Arithmetic-Logic Unit (ALU) present in the
computer's CPU carries out arithmetic operations at the bit-level.

Note: Bitwise operators can only be used alongside char and int data types.

C++ Bitwise AND Operator

The bitwise AND & operator returns 1 if and only if both the operands are 1.
Otherwise, it returns 0.
The following table demonstrates the working of the bitwise AND operator.
Let a and b be two operands that can only take binary values i.e. 1 and 0.

a b a&b

0 0 0

0 1 0

1 0 0

60
1 1 1

Note: The table above is known as the "Truth Table" for the bitwise AND operator.

Let's take a look at the bitwise AND operation of two integers 12 and 25:

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

//Bitwise AND Operation of 12 and 25

00001100

& 00011001

_________

00001000 = 8 (In decimal)

Example 1: Bitwise AND

#include <iostream>
using namespace std;

int main() {
// declare variables
int a = 12, b = 25;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a & b) << endl;

return 0;
}

Output

61
a = 12
b = 25
a&b=8

In the above example, we have declared two variables a and b. Here, notice the line,

cout << "a & b = " << (a & b) << endl;

Here, we are performing bitwise AND between variables a and b.

Example 2:

4: 100
5: 101
-----------
100 : The result is 4

#include <iostream>
using namespace std;

int main() {
// declare variables
int a = 4, b = 5;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a & b) << endl;

return 0;
}
Output:
a=4
b=5
a&b=4

C++ Bitwise OR Operator


62
The bitwise OR | operator returns 1 if at least one of the operands is 1. Otherwise, it
returns 0.
The following truth table demonstrates the working of the bitwise OR operator.
Let a and b be two operands that can only take binary values i.e., 1 or 0.

a b a|b

0 0 0

0 1 1

1 0 1

1 1 1

Let us look at the bitwise OR operation of two integers 12 and 25:

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25

00001100

| 00011001

_________

00011101 = 29 (In decimal)

Example 2: Bitwise OR

#include <iostream>

int main() {
int a = 12, b = 25;

63
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a | b = " << (a | b) << endl;

return 0;
}

Output

a = 12
b = 25
a | b = 29

The bitwise OR of a = 12 and b = 25 gives 29.

Example:
4: 100
5: 101
---------

101 : The result is 5


#include <iostream>
using namespace std;

int main() {
// declare variables
int a = 4, b = 5;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a|b) << endl;

return 0;
}
a=4
b=5
a&b=5

64
C++ Bitwise XOR Operator
The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1.
However, if both the operands are 0, or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator.
Let a and b be two operands that can only take binary values i.e. 1 or 0.

a b a^b

0 0 0

0 1 1

1 0 1

1 1 0

Let us look at the bitwise XOR operation of two integers 12 and 25:

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25

00001100

^ 00011001

_________

00010101 = 21 (In decimal)

Example 3: Bitwise XOR

#include <iostream>

int main() {
int a = 12, b = 25;

65
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a ^ b = " << (a ^ b) << endl;

return 0;
}

Output

a = 12
b = 25
a ^ b = 21

The bitwise XOR of a = 12 and b = 25 gives 21.

Example:
4: 100
5: 101
-------
001: The result is 1

#include <iostream>
using namespace std;

int main() {
// declare variables
int a = 4, b = 5;

cout << "a = " << a << endl;


cout << "b = " << b << endl;
cout << "a & b = " << (a^b) << endl;

return 0;
}

C++ Bitwise Complement Operator

66
The bitwise complement operator is a unary operator (works on only one operand). It
is denoted by ~ that changes binary digits 1 to 0 and 0 to 1.

It is important to note that the bitwise complement of any integer N is equal to -(N
+ 1). For example,
Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35
+ 1) = -36. Now, let's see if we get the correct answer or not.

35 = 00100011 (In Binary)

// Using bitwise complement operator

~ 00100011

__________

11011100

In the above example, we get that the bitwise complement of 00100011 (35)
is 11011100. Here, if we convert the result into decimal, we get 220.
However, it is important to note that we cannot directly convert the result into
decimal and get the desired output. This is because the binary result 11011100 is
also equivalent to -36.
To understand this we first need to calculate the binary output of -36. We use 2's
complement to calculate the binary of negative integers.

67
2's Complement

The 2's complement of a number N gives -N.


In binary arithmetic, 1's complement changes 0 to 1 and 1 to 0.
And, if we add 1 to the result of the 1's complement, we get the 2's complement of
the original number.

For example,

36 = 00100100 (In Binary)

1's Complement = 11011011

2's Complement :

11011011

+ 1

_________

11011100

Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is
equivalent to the bitwise complement of 35 that we have calculated in the
previous section.
Hence, we can say that the bitwise complement of 35 = -36.

Example 4: Bitwise Complement

#include <iostream>

int main() {
int num1 = 35;

68
int num2 = -150;
cout << "~(" << num1 << ") = " << (~num1) << endl;
cout << "~(" << num2 << ") = " << (~num2) << endl;

return 0;
}

Output

~(35) = -36
~(-150) = 149

In the above example, we declared two integer variables num1 and num2, and
initialized them with the values of 35 and -150 respectively.
We then computed their bitwise complement with the
codes (~num1) and (~num2) respectively and displayed them on the screen.

The bitwise complement of 35 = - (35 + 1) = -36

i.e. ~35 = -36

The bitwise complement of -150 = - (-150 + 1) = - (-149) = 149

i.e. ~(-150) = 149

This is exactly what we got in the output.

C++ Shift Operators


There are two shift operators in C++ programming:

 Right shift operator >>


 Left shift operator <<

5. C++ Right Shift Operator

The right shift operator shifts all bits towards the right by a certain number
of specified bits. It is denoted by >>.

69
When we shift any number to the right, the least significant bits are discarded,
while the most significant bits are replaced by zeroes.

As we can see from the image above, we have a 4-bit number. When we perform
a one-bit right shift operation on it, each individual bit is shifted to the right by 1 bit.
As a result, the right-most bit is discarded, while the left-most bit remains vacant. This
vacancy is replaced by a 0.

C++ Left Shift Operator

The left shift operator shifts all bits towards the left by a certain number
of specified bits. It is denoted by <<.

70
As we can see from the image above, we have a 4-bit number. When we perform a 1
bit left shift operation on it, each individual bit is shifted to the left by 1 bit.
As a result, the left-most bit is discarded, while the right-most bit remains vacant. This
vacancy is replaced by a 0.

Example 5: Shift Operators

#include <iostream>

int main() {

// declaring two integer variables


int num = 212, i;

// Shift Right Operation


cout << "Shift Right:" << endl;

// Using for loop for shifting num right from 0 bit to 3 bits
for (i = 0; i < 4; i++) {
cout << "212 >> " << i << " = " << (212 >> i) << endl;
}

// Shift Left Operation


cout << "\nShift Left:" << endl;

// Using for loop for shifting num left from 0 bit to 3 bits
for (i = 0; i < 4; i++) {
cout << "212 << " << i << " = " << (212 << i) << endl;
}

return 0;
}

Output

Shift Right:
212 >> 0 = 212
212 >> 1 = 106
212 >> 2 = 53
212 >> 3 = 26

Shift Left:
212 << 0 = 212
212 << 1 = 424
212 << 2 = 848
212 << 3 = 1696

71
From the output of the program above, we can infer that, for any number N, the
results of the shift right operator are:

N >> 0 = N

N >> 1 = (N >> 0) / 2

N >> 2 = (N >> 1) / 2

N >> 3 = (N >> 2) / 2

and so on.

Similarly, the results of the shift left operator are:

N << 0 = N

N << 1 = (N << 0) * 2

N << 2 = (N << 1) * 2

N << 3 = (N << 2) * 2

and so on.

Hence we can conclude that,

N >> m = [ N >> (m-1) ] / 2

N << m = [ N << (m-1) ] * 2

In the above example, note that the int data type stores numbers in 32-bits i.e.
an int value is represented by 32 binary digits.
However, our explanation for the bitwise shift operators used numbers represented
in 4-bits.
For example, the base-10 number 13 can be represented in 4-bit and 32-bit as:

4-bit Representation of 13 = 1101

72
32-bit Representation of 13 = 00000000 00000000 00000000 00001101

As a result, the bitwise left-shift operation for 13 (and any other number) can be
different depending on the number of bits they are represented by.
Because in 32-bit representation, there are many more bits that can be shifted left
when compared to 4-bit representation.

Precedence of Operators in C++

The precedence of operator species that which operator will be evaluated first and
next. The associativity specifies the operator’s direction to be evaluated, it may be
left to right or right to left.

Let's understand the precedence by the example given below:

int data=5+10*10;

The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Right to left

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == !=/td> Right to left

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Right to left

73
Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

C++ operator is a symbol that is used to perform mathematical or logical


manipulations. C++ language is rich with built-in operators.

Arithmetic Operators
Operato
Description
r

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

Increment and Decrement Operators

Operato
Description
r

++ Increment

−− Decrement

Relational Operators:

Operator Description
== Is equal to
!= Is not equal to
> Greater than
< Less than

74
>= Greater than or equal to
<= Less than or equal to

Logical Operators:

Operato
Description
r
&& And operator. Performs a logical conjunction of two expressions.
(if both expressions evaluate to True, result is True. If either
expression evaluates to False, result is False)

|| Or operator. Performs a logical disjunction on two expressions.


(if either or both expressions evaluate to True, result is True)

! Not operator. Performs logical negation on an expression.

Bitwise Operators:
Operato
Description
r
<< Binary Left Shift Operator
>> Binary Right Shift Operator
~ Binary One's Complement Operator
& Binary AND Operator
^ Binary XOR Operator
| Binary OR Operator

Assignment Operators:
Operator Description
= Assign
+= Increments, then assigns
-= Decrements, then assigns
*= Multiplies, then assigns
/= Divides, then assigns
%= Modulus, then assigns
<<= Left shift and assigns
>>= Right shift and assigns

75
&= Bitwise AND assigns
^= Bitwise exclusive OR and assigns
|= Bitwise inclusive OR and assigns

Misc. Operators
Operato
Description
r
, Comma operator

sizeof() Returns the size of a memory location.

& Returns the address of a memory location.

* Pointer to a variable.

?: Conditional Expression

76
C++ Control Structure:
Decision Making & Branching:

A C++ program is a set of statements, which are normally executed sequentially in


the order in which they appear. This happens when options or repetitions of certain
calculations are not necessary. However, in practice, we have a number of situations,
where we may have to change the order of execution of statements based on certain
conditions, or repeat a group of statements until certain specified conditions are met.
This involves a kind of decision making to see whether a particular condition has
occurred or not and then direct the computer to execute certain statements
accordingly.

When a program breaks the sequential flow and jumps to another part of the
code, it is called branching. When the branching is based on a particular condition, it
is known as conditional branching. If branching takes place without any decision, it is
known as unconditional branching.

C++ language possesses such decision-making capabilities and supports the following
statements known as control or decision-making statements.

1. If statement
2. switch statement
3. conditional operator statement

IF Statement:

77
In C++ programming, if statement is used to test the condition. There are various
types of if statements in C++.

1. if statement
2. if-else statement
3. nested if statement
4. if-else-if ladder

Simple IF Statement:

The C++ if statement tests the condition. It is executed if condition is true.

if(condition){
//code to be executed
}

How if Statement Works

78
#include <iostream>
using namespace std;

int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

Output:

It is even number

Example

// Program to print positive number entered by the user


// If the user enters a negative number, it is skipped

79
#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

// checks if the number is positive


if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}

cout << "This statement is always executed.";

return 0;
}

Output

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

When the user enters 5, the condition number > 0 is evaluated to true and the
statement inside the body of if is executed.
Output 2

Enter a number: -5
This statement is always executed.

When the user enters -5, the condition number > 0 is evaluated to false and the
statement inside the body of if is not executed.
80
#include< iostream.h>
int main( )
{
int x,y;
x=15;
y=13;
if (x > y )
{
cout << "x is greater than y";
}
}

x is greater than y

C++ if...else
The if statement can have an optional else clause. Its syntax is:

if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}

The if..else statement evaluates the condition inside the parenthesis.

81
How if...else Statement Works

If the condition evaluates true,


 the code inside the body of if is executed
 the code inside the body of else is skipped from execution
If the condition evaluates false,
 the code inside the body of else is executed
 the code inside the body of if is skipped from execution

82
Example:

#include <iostream>
using namespace std;
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

Output:

It is odd number

#include <iostream>
using namespace std;
int main () {
int num;

83
cout<<"Enter a Number: ";
cin>>num;
if (num % 2 == 0)
{
cout<<"It is even number"<<endl;
}
else
{
cout<<"It is odd number"<<endl;
}
return 0;
}

Output:

Enter a number:11
It is odd number

Output:

Enter a number:12
It is even number

// Program to check whether an integer is positive or negative


// This program considers 0 as a positive number

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number;

if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {

84
cout << "You entered a negative integer: " << number << endl;
}

cout << "This line is always printed.";

return 0;
}

Output 1

Enter an integer: 4
You entered a positive integer: 4.
This line is always printed.

In the above program, we have the condition number >= 0. If we enter the number
greater or equal to 0, then the condition evaluates true.
Here, we enter 4. So, the condition is true. Hence, the statement inside the body
of if is executed.
Output 2

Enter an integer: -4
You entered a negative integer: -4.
This line is always printed.

Here, we enter -4. So, the condition is false. Hence, the statement inside the body
of else is executed.

void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
cout << "x is greater than y";
}
else
{
cout << "y is greater than x";
}

85
}
Output
y is greater than x

Nested if.... else statement


Sometimes, we need to use an if statement inside another if statement. This is known
as nested if statement.

The general form of a nested if...else statement is,

if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}

if 'expression' is false or returns false, then the 'statement-block3' will be executed,


otherwise execution will enter the if condition and check for 'expression 1'. Then if the
'expression 1' is true or returns true, then the 'statement-block1' will be executed
otherwise 'statement-block2' will be executed.

Flowchart:

86
void main( )
{
int a,b,c;
cout << "enter 3 number";
cin >> a >> b >> c;
if(a > b)
{
if( a > c)
{
cout << "a is greatest";
}
else
{
cout << "c is greatest";
}
}
else
{
if( b> c)
{
cout << "b is greatest";
}

87
else
{
cout << "c is greatest";
}
}
}
The above code will print different statements based on the values
of a, b and c variables.

// C++ program to find if an integer is positive, negative or zero


// using nested if statements

#include <iostream>
using namespace std;

int main() {

int num;

cout << "Enter an integer: ";


cin >> num;

// outer if condition
if (num != 0) {

// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}

cout << "This line is always printed." << endl;

return 0;
}

88
Output 1

Enter an integer: 35
The number is positive.
This line is always printed.

Output 2

Enter an integer: -35


The number is negative.
This line is always printed.

Output 3

Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.

In the above example,

 We take an integer as an input from the user and store it in the variable num.
 We then use an if...else statement to check whether num is not equal to 0.
o If true, then the inner if...else statement is executed.
o If false, the code inside the outer else condition is executed, which
prints "The number is 0 and it is neither positive nor negative."
 The inner if...else statement checks whether the input number is positive i.e.
if num is greater than 0.
o If true, then we print a statement saying that the number is positive.
o If false, we print that the number is negative.

Note: As you can see, nested if...else makes your logic complicated. If possible, you
should always try to avoid nested if...else.

else-if Ladder
The general form of else-if ladder is,

if(expression 1)
{

89
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{
statement-block3;
}
else
default-statement;

The expression is tested from the top (of the ladder) downwards. As soon as the true
condition is found, the statement associated with it is executed.

90
Example:

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
91
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Output:

Enter a number to check grade:66


C Grade

Output:

Enter a number to check grade:-2


wrong number

void main( )
{
int a;
cout << "enter a number";
cin >> a;
if( a%5==0 && a%8==0)
{

92
cout << "divisible by both 5 and 8";
}
else if( a%8==0 )
{
cout << "divisible by 8";
}
else if(a%5==0)
{
cout << "divisible by 5";
}
else
{
cout << "divisible by none";
}
}

If you enter value 40 for the variable a, then the output will be:

divisible by both 5 and 8

C++ switch

The C++ switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement in C++.

switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;

93
break;
}

Flowchart:

#include <iostream>
using namespace std;
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
94
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}

Output:

Enter a number:
10
It is 10

Output:

Enter a number:
55
Not 10, 20 or 30

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement


#include <iostream>
using namespace std;

int main() {
char oper;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> oper;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;

switch (oper) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':

95
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! The operator is not correct";
break;
}

return 0;
}

Output 1

Enter an operator (+, -, *, /): +


Enter two numbers:
2.3
4.5
2.3 + 4.5 = 6.8

Output 2

Enter an operator (+, -, *, /): -


Enter two numbers:
2.3
4.5
2.3 - 4.5 = -2.2

Output 3

Enter an operator (+, -, *, /): *

96
Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35

Output 4

Enter an operator (+, -, *, /): /


Enter two numbers:
2.3
4.5
2.3 / 4.5 = 0.511111

Output 5

Enter an operator (+, -, *, /): ?


Enter two numbers:
2.3
4.5
Error! The operator is not correct.

In the above program, we are using the switch...case statement to perform addition,
subtraction, multiplication, and division.
How This Program Works
1. We first prompt the user to enter the desired operator. This input is then stored
in the char variable named oper.
2. We then prompt the user to enter two numbers, which are stored in the float
variables num1 and num2.
3. The switch statement is then used to check the operator entered by the user:
o If the user enters +, addition is performed on the numbers.
o If the user enters -, subtraction is performed on the numbers.
o If the user enters *, multiplication is performed on the numbers.
o If the user enters /, division is performed on the numbers.
o If the user enters any other character, the default code is printed.

Notice that the break statement is used inside each case block. This terminates
the switch statement.
If the break statement is not used, all cases after the correct case are executed.

97
Example:
/**
* C++ program to print day of week name
*/

#include <iostream>
using namespace std;

int main()
{
/* Declare integer variable to store week number */
int week;

/* Input week number from user */


cout<<"Enter week number (1-7): ";
cin>>week;

switch(week)
{
case 1:
/* If week == 1 */
cout<<"Its Monday."<<endl;
cout<<"Its a busy day."<<endl;
break;
case 2:
/* If week == 2 */
cout<<"Its Tuesday."<<endl;
break;
case 3:
/* If week == 3 */
cout<<"Its Wednesday."<<endl;
break;
case 4:
/* If week == 4 */
cout<<"Its Thursday."<<endl;

98
cout<<"Feeling bit relaxed."<<endl;
break;
case 5:
/* If week == 5 */
cout<<"Its Friday."<<endl;
break;
case 6:
/* If week == 6 */
cout<<"Its Saturday."<<endl;
cout<<"It is weekend."<<endl;
break;
case 7:
/* If week == 7 */
cout<<"Its Sunday."<<endl;
cout<<"Hurray! Its holiday."<<endl;
break;
default:
/* If week < 1 or week > 7 */
cout<<"Um! Please enter week number between 1-7."<<endl;
}
return 0;
}

Conditional Operator ? :
The conditional operator is useful for making two-way decisions. This operator is a
combination of ? and : , and takes three operands. This operator is popularly known as
the conditional operator. The general form of use of the conditional operator is as
follow:

conditional expression? expression1: expression2

The conditional expression is evaluated first. If the result is true, expression1 is


evaluated and is returned as the value of the conditional expression. Otherwise,
expression2 is evaluated and its value is returned.

99
Decision Making & Looping:
The process of repeatedly executing a block of statements is known as looping. The
statements in the block may be executed any number of times, from zero to infinite
number. If a loop continues forever, it is called an infinite loop.
In looping, a sequence of statements is executed until some conditions for the
termination of the loop is satisfied. A program loop therefore consists of two
segments, one known as the body of the loop and the other known as the control
statement. The control statement tests certain conditions and then directs the
repeated execution of the statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control
structures may be classified either as the entry-controlled loop or as exit-controlled
loop.
In the entry-controlled loop, the control conditions are tested before the start of
the loop execution. If the conditions are not satisfied, then the body of the loop will
not be executed.
In the case of an exit-controlled loop, the test is performed at the end of the body
of the loop and therefore the body is executed unconditionally for the first time.

There are 3 types of loops in C++.


100
 for loop
 while loop
 do...while loop

C++ For Loop

The C++ for loop is used to iterate a part of the program several times. If the number
of iterations is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.

for(initialization; condition; incr/decr){


//code to be executed
}
Here,
 initialization - initializes variables and is executed only once
 condition - if true, the body of for loop is executed if false, the for loop is
terminated.
 incr/decr – updates the value of initialized variables and again checks the
condition

Flowchart:

101
102
Example 1: Printing Numbers From 1 to 5

#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}

Output

103
12345

Here is how this program works

Iteration Variable i <= 5 Action

1st i=1 true 1 is printed. i is increased to 2.

2nd i=2 true 2 is printed. i is increased to 3.

3rd i=3 true 3 is printed. i is increased to 4.

4th i=4 true 4 is printed. i is increased to 5.

5th i=5 true 5 is printed. i is increased to 6.

6th i=6 false The loop is terminated

Example 2: Display a text 5 times

// C++ Program to display a text 5 times

#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}

Output

Hello World!
Hello World!
Hello World!
Hello World!

104
Hello World!

Here is how this program works

Variabl
Iteration i <= 5 Action
e

Hello World! is printed and i is


1st i=1 true
increased to 2.

Hello World! is printed and i is


2nd i=2 true
increased to 3.

Hello World! is printed and i is


3rd i=3 true
increased to 4.

Hello World! is printed and i is


4th i=4 true
increased to 5.

Hello World! is printed and i is


5th i=5 true
increased to 6.

6th i=6 false The loop is terminated

Example 3: Find the sum of first n Natural Numbers

// C++ program to find the sum of first n natural numbers


// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>

using namespace std;

int main() {
int num, sum;

105
sum = 0;

cout << "Enter a positive integer: ";


cin >> num;

for (int i = 1; i <= num; ++i) {


sum += i;
}

cout << "Sum = " << sum << endl;

return 0;
}

Output

Enter a positive integer: 10


Sum = 55

In the above example, we have two variables num and sum. The sum variable is
assigned with 0 and the num variable is assigned with the value provided by the user.

Note that we have used a for loop.

for(int i = 1; i <= num; ++i)

Here,

 int i = 1: initializes the i variable


 i <= num: runs the loop as long as i is less than or equal to num
 ++i: increases the i variable by 1 in each iteration
When i becomes 11, the condition is false and sum will be equal to 0 + 1 + 2 + ... +
10.

106
Ranged Based for Loop
In C++11, a new range-based for loop was introduced to work with collections such
as arrays and vectors. Its syntax is:

for (variable : collection) {


// body of loop
}

Here, for every value in the collection, the for loop is executed and the value is
assigned to the variable.

Example 4: Range Based for Loop

#include <iostream>

using namespace std;

int main() {

int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int n : num_array) {


cout << n << " ";
}

return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

In the above program, we have declared and initialized an int array


named num_array. It has 10 items.
Here, we have used a range-based for loop to access all the items in the array.

107
Nested For Loop:
We can also have nested for loop, i.e one for loop inside another for loop. Basic
syntax is,

for(initialization; condition; increment/decrement)


{
for(initialization; condition; increment/decrement)
{
statement;
}
}

C++ Nested For Loop Example

Let's see a simple example of nested for loop in C++.

#include <iostream>
using namespace std;

int main () {
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
cout<<i<<" "<<j<<"\n";
}
}
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinite for Loop

108
If we use double semicolon in for loop, it will be executed infinite times. Let's see a
simple example of infinite for loop in C++.

#include <iostream>
using namespace std;

int main () {
for (; ;)
{
cout<<"Infinitive For Loop";
}
}

Output:

Infinitive For Loop


Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c

C++ Infinite for loop


If the condition in a for loop is always true, it runs forever (until memory is full). For
example,

// infinite for loop


for(int i = 1; i > 0; i++) {
// block of code
}

In the above program, the condition is always true which will then run the code for
infinite times.

C++ while Loop

The syntax of the while loop is:

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

109
Here,
 A while loop evaluates the condition
 If the condition evaluates to true, the code inside the while loop is executed.
 The condition is evaluated again.
 This process continues until the condition is false.
 When the condition evaluates to false, the loop terminates.

Flowchart:

Example 1: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
int i = 1;

// while loop from 1 to 5


while (i <= 5) {
cout << i << " ";
++i;

110
}

return 0;
}

Output

12345

Here is how the program works.

Variabl
Iteration i <= 5 Action
e

1st i=1 true 1 is printed and i is increased to 2.

2nd i=2 true 2 is printed and i is increased to 3.

3rd i=3 true 3 is printed and i is increased to 4

4th i=4 true 4 is printed and i is increased to 5.

5th i=5 true 5 is printed and i is increased to 6.

6th i=6 false The loop is terminated

Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers


// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

111
// take input from the user
cout << "Enter a number: ";
cin >> number;

while (number >= 0) {


// add all positive numbers
sum += number;

// take input again if the number is positive


cout << "Enter a number: ";
cin >> number;
}

// display the sum


cout << "\nThe sum is " << sum << endl;

return 0;
}

Output

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

The sum is 25

In this program, the user is prompted to enter a number, which is stored in the
variable number.
In order to store the sum of the numbers, we declare a variable sum and initialize it to
the value of 0.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total sum is
displayed.

#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
112
{
cout<<i <<"\n";
i++;
}
}

C++ Nested While Loop Example

In C++, we can use while loop inside another while loop, it is known as nested while
loop. The nested while loop is executed fully when outer loop is executed once.

Let's see a simple example of nested while loop in C++ programming language.

#include <iostream>
using namespace std;
int main () {
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
cout<<i<<" "<<j<<"\n";
j++;
}
i++;
}
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinitive While Loop Example:

113
We can also create infinite while loop by passing true as the test condition.

#include <iostream>
using namespace std;
int main () {
while(true)
{
cout<<"Infinitive While Loop";
}
}

Output:

Infinitive While Loop


Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c

C++ do...while Loop


The do...while loop is a variant of the while loop with one important difference: the
body of do...while loop is executed once before the condition is checked.
Its syntax is:

do {
// body of loop;
}
while (condition);

Here,

 The body of the loop is executed at first. Then the condition is evaluated.
 If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
 The condition is evaluated once again.
 If the condition evaluates to true, the body of the loop inside the do statement
is executed again.
114
 This process continues until the condition evaluates to false. Then the loop
stops.
Flowchart of do...while Loop

Example 3: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
int i = 1;

// do...while loop from 1 to 5


do {
cout << i << " ";
++i;
}
while (i <= 5);

return 0;
}

Output

12345

Here is how the program works.

115
Variabl
Iteration i <= 5 Action
e

not
i=1 checke 1 is printed and i is increased to 2
d

1st i=2 true 2 is printed and i is increased to 3

2nd i=3 true 3 is printed and i is increased to 4

3rd i=4 true 4 is printed and i is increased to 5

4th i=5 true 5 is printed and i is increased to 6

5th i=6 false The loop is terminated

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
}

Output:

1
2
3
4
5
6
7
8
9
10

116
Example 4: Sum of Positive Numbers Only

// program to find the sum of positive numbers


// If the user enters a negative number, the loop ends
// the negative number entered is not added to the sum

#include <iostream>
using namespace std;

int main() {
int number = 0;
int sum = 0;

do {
sum += number;

// take input from the user


cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);

// display the sum


cout << "\nThe sum is " << sum << endl;

return 0;
}

Output 1

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

The sum is 25

Here, the do...while loop continues until the user enters a negative number. When the
number is negative, the loop terminates; the negative number is not added to
the sum variable.
Output 2

Enter a number: -6
The sum is 0.

117
The body of the do...while loop runs only once if the user enters a negative number.

Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the
memory is full). For example,

// infinite while loop


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

Here is an example of an infinite do...while loop.

// infinite do...while loop

int count = 1;

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

In the above programs, the condition is always true. Hence, the loop body will run for
infinite times.

for vs while loops

A for loop is usually used when the number of iterations is known. For example,

// This loop is iterated 5 times


for (int i = 1; i <=5; ++i) {
// body of the loop
}

Here, we know that the for-loop will be executed 5 times.

However, while and do...while loops are usually used when the number of iterations is
unknown. For example,

while (condition) {
// body of the loop

118
}

C++ Nested do-while Loop

In C++, if you use do-while loop inside another do-while loop, it is known as nested
do-while loop. The nested do-while loop is executed fully for each outer do-while loop.

Let's see a simple example of nested do-while loop in C++.

#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
int j = 1;
do{
cout<<i<<"\n";
j++;
} while (j <= 3) ;
i++;
} while (i <= 3) ;
}

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

C++ Infinitive do-while Loop

In C++, if you pass true in the do-while loop, it will be infinitive do-while loop.

do{
//code to be executed
}while(true);

119
C++ Infinitive do-while Loop Example

#include <iostream>
using namespace std;
int main() {
do{
cout<<"Infinitive do-while Loop";
} while(true);
}

Output:

Infinitive do-while Loop


Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c

break statement:
When break statement is encountered inside a loop, the loop is immediately exited
and the program continues with the statement immediately following the loop.

Syntax of break statement


break;

120
Working of C++ break Statement

121
Example 1: break with for loop

// program to print the value of i

#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}

return 0;
}

Output

1
2

122
In the above program, the for loop is used to print the value of i in each iteration.
Here, notice the code:

if (i == 3) {
break;
}

This means, when i is equal to 3, the break statement terminates the loop. Hence,
the output doesn't include values greater than or equal to 3.

Note: The break statement is usually used with decision-making statements.

Example 2: break with while loop

// program to find the sum of positive numbers


// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;

// break condition
if (number < 0) {
break;
}

// add all positive numbers

123
sum += number;
}

// display the sum


cout << "The sum is " << sum << endl;

return 0;
}

Output

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.

In the above program, the user enters a number. The while loop is used to print the
total sum of numbers entered by the user. Here, notice the code,

if(number < 0) {
break;
}

This means, when the user enters a negative number, the break statement
terminates the loop and codes outside the loop are executed.
The while loop continues until the user enters a negative number.

break with Nested loop

When break is used with nested loops, break terminates the inner loop. For example,

// using break statement inside


// nested for loop

#include <iostream>

124
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}

return 0;
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In the above program, the break statement is executed when i == 2. It terminates


the inner loop, and the control flow of the program moves to the outer loop.
Hence, the value of i = 2 is never displayed in the output.

The break statement is also used with the switch statement.

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
125
break;
}
cout<<i<<"\n";
}
}

C++ Break Statement with Inner Loop

The C++ break statement breaks inner loop only if you use break statement inside
the inner loop.

Let's see the example code:

#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
cout<<i<<" "<<j<<"\n";
}
}
}

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Continue Statement:
The continue statement is used to skip the current iteration of the loop and the
control of the program goes to the next iteration.
The syntax of the continue statement is:

126
continue;

Working of C++ continue Statement

Flowchart:

127
Example 1: continue with for loop

In a for loop, continue skips the current iteration and the control flow jumps to
the update expression.

// program to print the value of i

#include <iostream>
using namespace std;

128
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}

cout << i << endl;


}

return 0;
}

Output

1
2
4
5

In the above program, we have used the the for loop to print the value of i in each
iteration. Here, notice the code,

if (i == 3) {
continue;
}

This means

 When i is equal to 3, the continue statement skips the current iteration and
starts the next iteration
 Then, i becomes 4, and the condition is evaluated again.
 Hence, 4 and 5 are printed in the next two iterations.

Note: The continue statement is almost always used with decision-making


statements.

Example 2: continue with while loop

In a while loop, continue skips the current iteration and control flow of the program
jumps back to the while condition.

129
// program to calculate positive numbers till 50 only
// if the user enters a negative number,
// that number is skipped from the calculation

// negative number -> loop terminate


// numbers above 50 -> skip iteration

#include <iostream>
using namespace std;

int main() {
int sum = 0;
int number = 0;

while (number >= 0) {


// add all positive numbers
sum += number;

// take input from the user


cout << "Enter a number: ";
cin >> number;

// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated." <<
endl;
number = 0; // the value of number is made 0 again
continue;
}
}

// display the sum


cout << "The sum is " << sum << endl;

130
return 0;
}

Output

Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99

In the above program, the user enters a number. The while loop is used to print the
total sum of positive numbers entered by the user, as long as the numbers entered
are not greater than 50.
Notice the use of the continue statement.

if (number > 50){


continue;
}

 When the user enters a number greater than 50, the continue statement skips
the current iteration. Then the control flow of the program goes to
the condition of while loop.
 When the user enters a number less than 0, the loop terminates.

Note: The continue statement works in the same way for the do...while loops.

continue with Nested loop

131
When continue is used with nested loops, it skips the current iteration of the inner
loop. For example,

// using continue statement inside


// nested for loop

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

// nested for loops

// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
cout << "i = " << i << ", j = " << j << endl;
}
}

return 0;
}

Output

i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1

132
i = 3, j = 3

In the above program, when the continue statement executes, it skips the current
iteration in the inner loop. And the control of the program moves to the update
expression of the inner loop.
Hence, the value of j = 2 is never displayed in the output.

Note: The break statement terminates the loop entirely. However,


the continue statement only skips the current iteration.

C++ goto Statement


In C++ programming, the goto statement is used for altering the normal sequence of
program execution by transferring control to some other part of the program.

Syntax of goto Statement

goto label;

... .. ...

... .. ...

... .. ...

label:

statement;

... .. ...

In the syntax above, label is an identifier. When goto label; is encountered, the
control of program jumps to label: and executes the code below it.

133
Flowchart:

Example:

// This program calculates the average of numbers entered by the user.


// If the user enters a negative number, it ignores the number and
// calculates the average number entered before it.

# include <iostream>
using namespace std;

int main()
{
float num, average, sum = 0.0;
int i, n;

134
cout << "Maximum number of inputs: ";
cin >> n;

for(i = 1; i <= n; ++i)


{
cout << "Enter n" << i << ": ";
cin >> num;

if(num < 0.0)


{
// Control of the program move to jump:
goto jump;
}
sum += num;
}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}

Output

Maximum number of inputs: 10


Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6

Average = 3.95

#include <iostream>
using namespace std;
int main()
{
135
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18){
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
}

Output:

You are not eligible to vote!


Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

Reason to avoid goto Statement:


The goto statement gives the power to jump to any part of a program but, makes the
logic of the program complex and tangled.

In modern programming, the goto statement is considered a harmful construct and a


bad programming practice.

goto makes program less readable, error-prone and hard to find bugs. Due to the
unconditional control transfer from one part to other part of a function. At one point,
you as a programmer cannot tell how program control came to a certain point in your
code. Therefore, most of the programmers avoid the usage of goto.

136
Important note: You should avoid usage of goto as much as possible. Try to
replace goto statements with a combination of if...else, switch...case and loopping
statements.

137
Storage Classes in C++
Storage classes are used to specify the lifetime and scope of variables. How storage is
allocated for variables and how variable is treated by complier depends on these
storage classes.

These are basically divided into 5 different types:

1. Global variables
2. Local variables
3. Register variables
4. Static variables
5. Extern variables

Global Variables
These are defined at the starting, before all function bodies and are available
throughout the program.

If a variable is defined outside all functions, then it is called a global variable.

The scope of a global variable is the whole program. This means, It can be used and
changed at any part of the program after its declaration.

Likewise, its life ends only when the program ends.

using namespace std;


int globe; // Global variable
void func();
int main()
{
.....
}

138
#include <iostream>
using namespace std;

// Global variable declaration


int c = 12;

void test();

int main()
{
++c;

// Outputs 13
cout << c <<endl;
test();

return 0;
}

void test()
{
++c;

// Outputs 14
cout << c;
}

Output

13
14

In the above program, c is a global variable.


This variable is visible to both functions main() and test() in the above program.

Local variables
They are defined and are available within a particular scope. They are also
called Automatic variable because they come into being when scope is entered and
automatically go away when the scope ends.

The keyword auto is used, but by default all local variables are auto, so we don't have
to explicitly add keyword auto before variable declaration. Default value of such
variable is garbage.

139
#include <iostream>
using namespace std;

void test();

int main()
{
// local variable to main()
int var = 5;

test();

// illegal: var1 not declared inside main()


var1 = 9;
}

void test()
{
// local variable to test()
int var1;
var1 = 6;

// illegal: var not declared inside test()


cout << var;
}

The variable var cannot be used inside test() and var1 cannot be used
inside main() function.

Keyword auto was also used for defining local variables before as: auto int var;

But, after C++11 auto has a different meaning and should not be used for defining
local variables.

Register variables (Deprecated in C++11)

140
This is also a type of local variable. The register keyword is used to tell the compiler to
make access to this variable as fast as possible. Variables are stored in registers to
increase the access speed.

But you can never use or compute address of register variable and also, a register
variable can be declared only within a block, that means, you cannot
have global or static register variables.

Static Variables
Static variables are the variables which are initialized & allocated storage only once at
the beginning of program execution, no matter how many times they are used and
called in the program. A static variable retains its value until the end of program.

void fun()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
}

As, i is static, hence it will retain its value through function calls, and is initialized only
once at the beginning.

Static specifiers are also used in classes, but that we will learn later.

#include <iostream>
using namespace std;

void test()
{

141
// var is a static variable
static int var = 0;
++var;

cout << var << endl;


}

int main()
{

test();
test();

return 0;
}

Output

1
2

In the above program, test() function is invoked 2 times.


During the first call, variable var is declared as static variable and initialized to 0.
Then 1 is added to var which is displayed in the screen.
When the function test() returns, variable var still exists because it is a static variable.
During second function call, no new variable var is created. The same var is increased
by 1 and then displayed to the screen.
Output of above program if var was not specified as static variable

1
1

Extern Variables

142
This keyword is used to access variable in a file which is declared & defined in some
other file, that is the existence of a global variable in one file is declared using extern
keyword in another file.

#include <iostream>
using namespace std;

void autoStorageClass()
{

cout << "Demonstrating auto class\n";

// Declaring an auto variable


// No data-type declaration needed
auto a = 32;
auto b = 3.2;
auto c = "SaiPali";
auto d = 'G';

// printing the auto variables


cout << a << " \n";
cout << b << " \n";
cout << c << " \n";
cout << d << " \n";
}

int main()
{

143
// To demonstrate auto Storage Class
autoStorageClass();

return 0;
}

Output:
Demonstrating auto class
32
3.2
SaiPali
G

Storage class is used to define the lifetime and visibility of a variable and/or function
within a C++ program.

Lifetime refers to the period during which the variable remains active and visibility
refers to the module of a program in which the variable is accessible.

There are five types of storage classes, which can be used in a C++ program

1. Automatic
2. Register
3. Static
4. External
5. Mutable

Storage Class Keyword Lifetime Visibility Initial Value

Automatic auto Function Block Local Garbage

Register register Function Block Local Garbage

Mutable mutable Class Local Garbage

External extern Whole Program Global Zero

Static static Whole Program Local Zero

Automatic Storage Class

It is the default storage class for all local variables. The auto keyword is applied to all
local variables automatically.

144
{
auto int y;
float y = 3.45;
}

The above example defines two variables with a same storage class, auto can only be
used within functions.

Register Storage Class

The register variable allocates memory in register than RAM. Its size is same of
register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

register int counter=0;

Static Storage Class

The static variable is initialized only once and exists till the end of a program. It
retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

#include <iostream>
using namespace std;
void func() {
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();

145
}

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

External Storage Class

The extern variable is visible to all the programs. It is used if two or more files are
sharing same variable or function.

extern int counter=0;

The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.

First File: main.cpp


#include <iostream>
int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}

Second File: support.cpp


#include <iostream>

extern int count;

void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}

Working Example:
myFile.h

146
extern int x=20;

m2.cpp
#include "myfile.h"
#include<iostream>
using namespace std;
void printValue();
int main()
{
cout<<"External Variable : "<<x<<endl;
printValue();
return 0;
}
void printValue()
{
cout<<"External variable : "<<x<<endl;
}

The mutable Storage Class


The mutable specifier applies only to class objects, which are discussed later. It
allows a member of an object to override const member function. That is, a mutable
member can be modified by a const member function.

147
C++ Functions

The function in C++ language is also known as procedure or subroutine in other


programming languages.

To perform any task, we can create function. A function can be called many times. It
provides modularity and code reusability.

Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C++, you can call it many times. So, we don't need to write
the same code again and again. We can declare them once and use them multiple
times.

2) Code optimization

It makes the code optimized; we don't need to write much code.

Suppose, you have to check 3 numbers (531, 883 and 781) whether it is prime
number or not. Without using function, you need to write the prime number logic 3
times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it
several times.

148
Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C++ header files
such as ceil(x), cos(x), exp(x), etc.

2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a big
program and optimizes the code.

C++ Library Functions


Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't
need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header file in which
these library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we
need to include the header file cmath.

Example: C++ Program to Find the Square Root of a Number

#include <iostream>
#include <cmath>
using namespace std;

149
int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}

Output

Square root of 25 = 5

//program demo using C++ Library functions

#include<iostream>

#include<math.h>

using namespace std;

int main()

cout<<"sin(90): "<<sin(90)<<endl;

cout<<"cos(180): "<<cos(180)<<endl;

cout<<"tan(45): "<<tan(45)<<endl;

cout<<"sqrt(256): "<<sqrt(256)<<endl;

cout<<"max(20,10): "<<max(20,10)<<endl;

cout<<"min(50,11): "<<min(50,11)<<endl;

cout<<"pow(2,3): "<<pow(2,3)<<endl;

return 0;

150
C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code
is given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes
defined in the body of the function.

Basic Syntax for using Functions in C++


Here is how you define a function in C++,

return-type function-name(parameter1, parameter2, ...)

// function-body

 return-type: suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions which does not return
anything, they are mentioned with void.

 Function Name: is the name of the function, using the function name it is
called.

 Parameters: are variables to hold values of arguments passed while function is


called. A function may or may not contain parameter list.

Example:

// function declaration
void greet() {
cout << "Hello World";
}

Here,

151
 the name of the function is greet()
 the return type of the function is void
 the empty parentheses mean it doesn't have any parameters

 the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function
In the above program, we have declared a function named greet(). To use
the greet() function, we need to call it.

Here's how we can call the above greet() function.

int main() {

// calling a function
greet();

How Function works in C++

Example 1: Display a Text

152
#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;
}

Output

Hello there!

Example:
// function for adding two values
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}

int main()
{
int a = 10;
int b = 20;
// calling the function with name 'sum'
sum (a, b);
}

Here, a and b are two variables which are sent as arguments to the function sum,
and x and y are parameters which will hold values of a and b to perform the required
operation inside the function.
153
 Function body: is the part where the code statements are written.

Example:
#include < iostream>
using namespace std;

//declaring the function or function prototype


int sum (int x, int y);

int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}

//defining the function


int sum (int x, int y)
{
return (x + y);
}

Return Statement
In the above programs, we have used void in the function declaration. For example,

void displayNumber() {
// code
}

This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,

154
int add (int a, int b) {
return (a + b);
}

Here, we have the data type int instead of void. This means that the function returns
an int value.

The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code
after return inside the function is not executed.

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

// function prototype
void add(int, int);

int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b) {
cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its
parameters. That's why we can use the code to call a function before the function has
been defined.

The syntax of a function prototype is:


155
returnType functionName(dataType1, dataType2, ...);

Example : C++ Function Prototype

// using function definition after main() function


// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}

// function definition
int add(int a, int b) {
return (a + b);
}

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here,
the function is defined after the function call.

156
C++ User-defined Function Types

For better understanding of arguments and return in functions, user-defined functions


can be categorised as:

1. Function with no argument and no return value


2. Function with no argument but return value
3. Function with argument but no return value
4. Function with argument and return value

Example 1: No arguments passed and no return value

# include <iostream>
using namespace std;

void prime();

int main()
{
// No argument is passed to prime()
prime();
return 0;
}

// Return type of function is void because value is not returned.


void prime()
{

int num, i, flag = 0;

cout << "Enter a positive integer enter to check: ";


cin >> num;

for(i = 2; i <= num/2; ++i)


{
if(num % i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{

157
cout << num << " is not a prime number.";
}
else
{
cout << num << " is a prime number.";
}
}

In the above program, prime() is called from the main() with no arguments.
prime() takes the positive number from the user and checks whether the number is a
prime number or not.
Since, return type of prime() is void, no value is returned from the function.

Example 2: No arguments passed but a return value

#include <iostream>
using namespace std;

int prime();

int main()
{
int num, i, flag = 0;

// No argument is passed to prime()


num = prime();
for (i = 2; i <= num/2; ++i)
{
if (num%i == 0)
{
flag = 1;
break;
}
}

158
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}

// Return type of function is int


int prime()
{
int n;

printf("Enter a positive integer to check: ");


cin >> n;

return n;
}

In the above program, prime() function is called from the main() with no arguments.

prime() takes a positive integer from the user. Since, return type of the function is
an int, it returns the inputted number from the user back to the
calling main() function.

Then, whether the number is prime or not is checked in the main() itself and printed
onto the screen.

Example 3: Arguments passed but no return value

#include <iostream>
using namespace std;

159
void prime(int n);

int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;

// Argument num is passed to the function prime()


prime(num);
return 0;
}

// There is no return value to calling function. Hence, return type of function is


void. */
void prime(int n)
{
int i, flag = 0;
for (i = 2; i <= n/2; ++i)
{
if (n%i == 0)
{
flag = 1;
break;
}
}

if (flag == 1)
{
cout << n << " is not a prime number.";
}
else {
cout << n << " is a prime number.";
}

160
}

In the above program, positive number is first asked from the user which is stored in
the variable num.

Then, num is passed to the prime() function where, whether the number is prime or
not is checked and printed.

Since, the return type of prime() is a void, no value is returned from the function.

Example 4: Arguments passed and a return value.

#include <iostream>
using namespace std;

int prime(int n);

int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;

// Argument num is passed to check() function


flag = prime(num);

if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}

/* This function returns integer value. */


int prime(int n)
{

161
int i;
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0)
return 1;
}

return 0;
}

In the above program, a positive integer is asked from the user and stored in the
variable num.

Then, num is passed to the function prime() where, whether the number is prime or
not is checked.

Since, the return type of prime() is an int, 1 or 0 is returned to the main() calling
function. If the number is a prime number, 1 is returned. If not, 0 is returned.

Back in the main() function, the returned 1 or 0 is stored in the variable flag, and the
corresponding text is printed onto the screen.

Which method is better?


All four programs above gives the same output and all are technically correct
program.

There is no hard and fast rule on which method should be chosen.

The particular method is chosen depending upon the situation and how you want to
solve a problem.

162
Calling a Function
Functions are called by their names. If the function is without argument, it can be
called directly using its name. But for functions with arguments, we have two ways to
call them,

1. Call by Value
2. Call by Reference

Call by Value
In this calling technique we pass the values of arguments which are stored or copied
into the formal parameters of functions. Hence, the original values are unchanged
only the parameters inside function changes. In call by value, original value is not
modified.

//program demo using call by value


#include<iostream>
using namespace std;
void calc(int x); //function prototype
int main()
{
int x = 10;
cout<<"Before calling the function: x = "<<x<<endl;
calc(x);
cout<<"After calling the function: x = "<<x<<endl;
163
}
void calc(int x)
{
x = x + 10 ;
}
10

In this case the actual variable x is not changed, because we pass argument by value,
hence a copy of x is passed, which is changed, and that copied value is destroyed as
the function ends (goes out of scope). So the variable x inside main() still has a value
10.

But we can change this program to modify the original x, by making the
function calc() return a value, and storing that value in x.

//program demo using call by value


#include<iostream>
using namespace std;
int calc(int x);
int main()
{
int x = 10;
x = calc(x);
cout<<"x = "<<x<<endl;
}

int calc(int x)
{
x = x + 10 ;
return x;
}

20

Example:
#include <iostream>
using namespace std;
void change(int data);
int main()
{

164
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}

Output:

Value of the data is: 3

Call by Reference
In this we pass the address of the variable as arguments. In this case the formal
parameter can be taken as a reference or a pointer, in both the case they will change
the values of the original variable.

//program demo using call by reference


#include<iostream>
using namespace std;
void calc(int *p);

int main()
{
int x = 10;
cout<<"Before calling the function x = "<<x<<endl;
calc(&x); // passing address of x as argument
cout<<"After calling the function x = "<<x<<endl;
}
void calc(int *p)
{
*p = *p + 10;
}

Output:
Before calling the function x = 10
After calling the function x = 20

165
#include <iostream>

using namespace std;

void change(int *data);

int main()

int data = 3;

change(&data);

cout << "Value of the data is: " << data<< endl;

return 0;

void change(int *data)

*data = 5;

Example:
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
166
return 0;
}

Output:

Value of x is: 100


Value of y is: 500

Difference between call by value and call by reference in C++

No. Call by value Call by reference

1 A copy of value is passed to the An address of value is passed to the


function function

2 Changes made inside the function is Changes made inside the function is
not reflected on other functions reflected outside the function also

3 Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location

C++ Recursion

When function is called within the same function, it is known as recursion in C++. The
function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is known
as tail recursion. In tail recursion, we generally call the same function with return
statement.

Let's see a simple example of recursion.

recursionfunction(){
recursionfunction(); //calling self function
}

Example:

#include<iostream>
using namespace std;
int main()
{
167
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}

Output:

Enter any number: 5


Factorial of a number is: 120

We can understand the above program of recursive method call by the figure given
below:

168
C++ Function Overloading
In C++, two functions can have the same name if the number and/or type of
arguments passed is different.

These functions having the same name but different arguments are known as
overloaded functions. For example:

// same name different arguments


int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

Here, all 4 functions are overloaded functions.

Notice that the return types of all these 4 functions are not the same. Overloaded
functions may or may not have different return types but they must have different
arguments. For example,

// Error code
int test(int a) { }
double test(int b){ }

Here, both functions have the same name, the same type, and the same number of
arguments. Hence, the compiler will throw an error.

169
Example 1: Overloading Using Different Types of Parameter

// Program to compute absolute value


// Works for both int and float

#include <iostream>
using namespace std;

// function with float type parameter


float absolute(float var){
if (var < 0.0)
var = -var;
return var;
}

// function with int type parameter


int absolute(int var) {
if (var < 0)
var = -var;
return var;
}

int main() {

// call function with int type parameter


cout << "Absolute value of -5 = " << absolute(-5) << endl;

// call function with float type parameter


cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
return 0;
}

Output

Absolute value of -5 = 5
Absolute value of 5.5 = 5.5

170
Working of overloading for the absolute() function
In this program, we overload the absolute() function. Based on the type of parameter
passed during the function call, the corresponding function is called.

Example 2: Overloading Using Different Number of Parameters

#include <iostream>
using namespace std;

// function with 2 parameters


void display(int var1, double var2) {
cout << "Integer number: " << var1;
cout << " and double number: " << var2 << endl;
}

// function with double type single parameter


void display(double var) {
cout << "Double number: " << var << endl;
}

171
// function with int type single parameter
void display(int var) {
cout << "Integer number: " << var << endl;
}

int main() {

int a = 5;
double b = 5.5;

// call function with int type parameter


display(a);

// call function with double type parameter


display(b);

// call function with 2 parameters


display(a, b);

return 0;
}

Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5

Here, the display() function is called three times with different arguments. Depending
on the number and type of arguments passed, the corresponding display() function is
called.

172
Working of overloading for the display() function
The return type of all these functions is the same but that need not be the case for
function overloading.

Note: In C++, many standard library functions are overloaded. For example,
the sqrt() function can take double, float, int, etc. as parameters. This is possible
because the sqrt() function is overloaded in C++.

C++ Programming Default Arguments (Parameters)


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

However, if arguments are passed while calling the function, the default arguments
are ignored.

173
Working of default arguments

How default arguments work in C++

We can understand the working of default arguments from the image above:
 When temp() is called, both the default parameters are used by the function.
 When temp(6) is called, the first argument becomes 6 while the default value is
used for the second parameter.
 When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
 When temp(3.4) is passed, the function behaves in an undesired way because
the second argument cannot be passed without passing the first argument.

Therefore, 3.4 is passed as the first argument. Since the first argument has
been defined as int, the value that is actually passed is 3.

Example:
174
//program demo using Default Arguments
#include <iostream>
using namespace std;

// function with int type single parameter


void display(int var=10) {
cout << "Integer number: " << var << endl;
}

int main() {

// call function with int type parameter


display();

return 0;
}
Example: Default Argument

#include <iostream>
using namespace std;

// defining the default arguments


void display(char = '*', int = 3);

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters
display();

cout << "First argument passed: ";

175
// #, 3 will be parameters
display('#');

cout << "Both arguments passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}

void display(char c, int count) {


for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}

Output

No argument passed: ***


First argument passed: ###
Both arguments passed: $$$$$

Here is how this program works:

1. display() is called without passing any arguments. In this case, display() uses
both the default parameters c = '*' and n = 1.
2. display('#') is called with only one argument. In this case, the first becomes '#'.
The second default parameter n = 1 is retained.
3. display('#', count) is called with both arguments. In this case, default
arguments are not used.
We can also define the default parameters in the function definition itself. The
program below is equivalent to the one above.

176
#include <iostream>
using namespace std;

// defining the default arguments


void display(char c = '*', int count = 3) {
for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters
display();

cout << "First argument passed: ";


// #, 3 will be parameters
display('#');

cout << "Both argument passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}

Things to Remember
1. Once we provide a default value for a parameter, all subsequent parameters
must also have default values. For example,

177
// Invalid
void add(int a, int b = 3, int c, int d);

// Invalid
void add(int a, int b = 3, int c, int d = 4);

// Valid
void add(int a, int c, int b = 3, int d = 4);

2. If we are defining the default arguments in the function definition instead of the
function prototype, then the function must be defined before the function call.

// Invalid code

int main() {
// function call
display();
}

void display(char c = '*', int count = 5) {


// code
}

178
C++ Arrays

Like other programming languages, array in C++ is a group of similar types of


elements that have contiguous memory location.

In programming, arrays are referred to as structured data types. An array is defined


as finite ordered collection of homogenous data, stored in contiguous memory
locations.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array
index starts from 0. We can store only fixed set of elements in C++ array.

Advantages of C++ Array

1. Code Optimization (less code)


2. Random Access
3. Easy to traverse data
4. Easy to manipulate data
5. Easy to sort data etc.

Disadvantages of C++ Array

 Fixed size

C++ Array Types


There are 2 types of arrays in C++ programming:
1. Single Dimensional Array
2. Multidimensional Array

C++ Single Dimensional Array

179
Let's see a simple example of C++ array, where we are going to create, initialize and
traverse array.
#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

Output:

10
0
20
0
30

C++ Array Example: Traversal using foreach loop

We can also traverse the array elements using foreach loop. It returns array element
one by one.

#include <iostream>
using namespace std;
int main()
{
int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array
//traversing array
for (int i: arr)
{
cout<<i<<"\n";
}
}

180
Output:

10
20
30
40
50

Example:
#include <iostream>
using namespace std;

int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to Understand the basics of an Array ===== \n\n";

//i to iterate the outer loop and j for the inner loop
int i, n;

cout << "\n\nEnter the number integers you want in an array: ";
cin >> n;

//Declaring an array containing 'n' integers


int arr[n];

cout << "\n\n Enter " << n << " integers into an array :\n\n";

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


{
cin >> arr[i];
}

cout << "\n\n The Elements of the Array are: \n\n";

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


{
cout << " arr [ " << i << " ] = " << arr[i] << endl;
}

cout << "\n\n";

return 0;
}

Output:

181
C++ How to Delete an Array element
Logic:
Once the element gets removed, move all the elements following it, towards the front
by 1 position. This way, the remaining elements will still be stored in a continuous
form. The below code will help you understand this logic.

#include <iostream>
using namespace std;

int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate Deletion of an element from an Array
===== \n\n";

int n;

cout << " Enter the size of the array: ";


182
cin >> n;

int arr[n], i, pos;

cout << "\n\n Enter the " << n << " elements of the array: \n\n";
for(i=0; i<n; i++)
{
cin >> arr[i];
}

//Printing the original array before deletion


cout << "\n\n The " << n << " elements of the array, before deletion are : \n\n";
for(i=0; i<n; i++)
{
cout << arr[i] << " ";
}

cout << "\n\n Enter the position, between 1 and " << n << " , of the element to be
deleted : ";
cin >> pos;

//Performing the deletion logic


--pos;//as index of the element to be deleted is 1 less than it's position
for (i = pos; i <= 9; i++)
{
arr[i] = arr[i + 1];
}

cout << " \n\nThe " << n-1 << " elements of the array, after deletion are : \n\n";
for(i=0; i<n-1; i++)
{
cout << arr[i] << " ";
}

cout << "\n\n";

183
return 0;
}

Output:

Find Sum and Average of the Array Elements in C++


#include <iostream>
using namespace std;

int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to find the Sum and Average of the Array elements
===== \n\n";

//i to iterate the outer loop and j for the inner loop
184
int i, n;

//declaring sum and average as double because average can be a fractional value
double sum=0, average=0;

cout << "\n\nEnter the number integers you want in an array: ";
cin >> n;

//Declaring an array containing 'n' integers


int arr[n];

cout << "\n\n Enter " << n << " integers into an array :\n\n";

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


{
cout << " Enter arr [ " << i << " ] : ";
cin >> arr[i];
}

cout << "\n\n The Elements of the Array are: \n\n";

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


{
cout << " arr [ " << i << " ] = " << arr[i] << endl;
sum += arr[i];
}

average = sum/n;

cout << "\n\n The Sum of the Elements of the Array is : " << sum << "\n\n";

cout << "\n\n The Average of the Elements of the Array is : " << average << "\n\
n";

cout << "\n\n";

185
return 0;
}
Output:

#include <iostream>

using namespace std;

int main() {
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate Addition of two Matrices ===== \n\
n";

186
//loop variable i to iterate rows and j to iterate columns.
int row, col, i, j;

//Declaring the 3 matrices (2D arrays) m1-first matrix, m2- second matrix and sum-
stores the addition of the two matrices
int m1[10][10], m2[10][10], sum[10][10];

cout << "\n\nEnter the number of Rows and Columns of matrix : ";
cin >> row >> col;

cout << "\nEnter the " << row * col << " elements of first matrix : \n";

for (i = 0; i < row; i++) {


for (j = 0; j < col; j++) {
cin >> m1[i][j];
}
}

cout << "\nEnter the " << row * col << " elements of second matrix : \n";

for (i = 0; i < row; i++) {


for (j = 0; j < col; j++) {
cin >> m2[i][j];
}
}

//calculating the sum matrix


for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
sum[i][j] = m1[i][j] + m2[i][j];
}
}

cout << "\n\nThe first matrix is : \n";

187
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m1[i][j] << " ";
}
cout << endl;
}

cout << "\n\nThe second matrix is : \n";

for (i = 0; i < row; i++) {


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

cout << "\n\nThe Sum matrix is : \n";

for (i = 0; i < row; i++) {


for (j = 0; j < col; j++) {
cout << sum[i][j] << " ";
}

cout << endl;


}

cout << "\n\n";

return 0;
}

Output:

188
C++ Program to Find the Smallest and Largest element in an Array

#include <iostream>
using namespace std;

int findMinimum(int a[], int n)


{
int mn = a[0]; //initializing minimum

for (int i = 0; i < n; i++) // complexity O(n)


{
mn = min(mn, a[i]); //everytime storing the minimum among the current
minimum and the current element
}
return mn;
}

189
int findMaximum(int a[], int n)
{
int mx = a[0]; //initializing maximum

for (int i = 0; i < n; i++) // complexity O(n)


{
mx = max(mx, a[i]); //everytime storing the maximum among the current
maximum and the current element
}
return mx;
}

int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to find the Minimum and Maximum element in an
Array ===== \n\n";

int n;

cout << " Enter the size of the array: ";


cin >> n;

int arr[n], i, pos;

cout << "\n\n Enter the " << n << " elements of the array: \n\n";
for (i = 0; i < n; i++)
{
cin >> arr[i];
}

//Printing the original array before deletion


cout << "\n\n The " << n << " elements of the array are : ";
for (i = 0; i < n; i++)
{
cout << arr[i] << " ";
}

//Calling a method to find the smallest element


int mn = findMinimum(arr, n);

//Calling a method to find the largest element


int mx = findMaximum(arr, n);

cout << "\n\n\nThe Smallest element in the entered array is: " << mn;

cout << "\n\nThe Largest element in the entered array is: " << mx << "\n\n\n";

return 0;
}

Output:
190
C++ Passing Array to Function

In C++, to reuse the array logic, we can create function. To pass array to function in
C++, we need to provide only array name.

functionname(arrayname); //passing array to function

C++ Passing Array to Function Example: print array elements


Let's see an example of C++ function which prints the array elements.
#include <iostream>
using namespace std;
void printArray(int arr[5]);
int main()
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printArray(arr1); //passing array to function
printArray(arr2);
}
191
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}

Output:

Printing array elements:


10
20
30
40
50
Printing array elements:
5
15
25
35
45

C++ Passing Array to Function Example: Print minimum number

Let's see an example of C++ array which prints minimum number in an array using
function.

#include <iostream>
using namespace std;
void printMin(int arr[5]);
int main()
{
int arr1[5] = { 30, 10, 20, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printMin(arr1);//passing array to function
printMin(arr2);
}
void printMin(int arr[5])
{
int min = arr[0];

192
for (int i = 0; i > 5; i++)
{
if (min > arr[i])
{
min = arr[i];
}
}
cout<< "Minimum element is: "<< min <<"\n";
}

Output:

Minimum element is: 10


Minimum element is: 5

C++ Passing Array to Function Example: Print maximum number

Let's see an example of C++ array which prints maximum number in an array using
function.

#include <iostream>

using namespace std;


void printMax(int arr[5]);
int main()
{
int arr1[5] = { 25, 10, 54, 15, 40 };
int arr2[5] = { 12, 23, 44, 67, 54 };
printMax(arr1); //Passing array to function
printMax(arr2);
}
void printMax(int arr[5])
{
int max = arr[0];
for (int i = 0; i < 5; i++)
{
if (max < arr[i])
{
max = arr[i];
}
}
cout<< "Maximum element is: "<< max <<"\n";
193
}

Output:

Maximum element is: 54


Maximum element is: 67

C++ Multidimensional Arrays

The multidimensional array is also known as rectangular arrays in C++. It can be two
dimensional or three dimensional. The data is stored in tabular form (row ∗ column)
which is also known as matrix.

C++ Multidimensional Array Example

Let's see a simple example of multidimensional array in C++ which declares,


initializes and traverse two dimensional arrays.

#include <iostream>
using namespace std;
int main()
{
int test[3][3]; //declaration of 2D array
test[0][0]=5; //initialization
test[0][1]=10;
test[1][1]=15;
test[1][2]=20;
test[2][0]=30;
test[2][2]=10;
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
194
return 0;
}
Output:
5 10 0
0 15 20
30 0 10

C++ Multidimensional Array Example: Declaration and initialization at same time

Let's see a simple example of multidimensional array which initializes array at the
time of declaration.

#include <iostream>
using namespace std;
int main()
{
int test[3][3] =
{
{2, 5, 5},
{4, 0, 3},
{9, 1, 8} }; //declaration and initialization
//traversal
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
cout<< test[i][j]<<" ";
}
cout<<"\n"; //new line at each row
}
return 0;
}
Output:
255
403
918

C++ Strings:

195
In C++, string is an object of std::string class that represents sequence of
characters. We can perform many operations on strings such as concatenation,
comparison, conversion etc.

Program To Print A Full String Input Using Keyboard In C++


String is a collection of characters. There are two types of strings commonly used in
C++ programming language:

 Strings that are objects of string class (The Standard C++ Library string class)
 C-strings (C-style Strings)

#include<iostream>
#include<string>
using namespace std;
int main()
{
char a[20];
int i;

cout<<"\nEnter The String: ";


gets(a);
cout<<"\nYour Entered String is Given Below \n\n";

for(i=0;a[i]!='\0';++i)
{
cout<<a[i];
}
return 0;
}

//program demo using strings


#include<iostream>
#include<string>
using namespace std;
int main()

196
{
char name[50];
cout<<"Enter your text: ";
// Reads string from user
gets(name);
cout<<"Your text is: "<<endl;
// Displays string
puts(name);

return 0;
}

C++ Program To Copy One String To Another


Program To Copy One String To Another
#include <iostream>
using namespace std;

int main()
{
string s1, s2;

cout << "Enter string s1: ";


getline (cin, s1);

s2 = s1;

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

return 0;
}

Enter string s1: C++ Strings


s1 = C++ Strings

197
s2 = C++ Strings

//program demo using strings


#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[100], s2[100];

cout << "Enter string s1: ";


cin.getline(s1, 100);

strcpy(s2, s1);

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

return 0;
}

//program demo using strings concatenation


#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s1[100], s2[100];
cout<<"Enter string s1: ";
cin.getline(s1, 100);

cout<<"Enter string s2: ";


cin.getline(s2,100);

198
strcat(s1, s2);
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;

return 0;
}

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char s1[100], s2[100];

cout << "Enter string s1: ";


cin.getline(s1, 100);

strcpy(s2, s1);

cout << "s1 = "<< s1 << endl;


cout << "s2 = "<< s2;

return 0;
}

Enter string s1: C-Strings


s1 = C-Strings
s2 = C-Strings

#include <iostream>
#include <cstring>
using namespace std;
int main ()

199
{
char key[] = "mango";
char buffer[50];
do {
cout<<"What is my favourite fruit? ";
cin>>buffer;
} while (strcmp (key,buffer) != 0);
cout<<"Answer is correct!!"<<endl;
return 0;
}

Output:

What is my favourite fruit? apple


What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

//Write A C++ Program To Compare String.


#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
// declare strings
const char *str1 = "saipali institute";
const char *str2 = "saipali institute";

cout << " String 1: " << str1 << endl;


cout << " String 2: " << str2 << endl;

// use strcmp() function to validate the strings are equal


if (strcmp (str1, str2) == 0)
{
cout << " \n Both strings are equal. " << endl;
}
else
{

cout << " The strings are not equal. " << endl;
}

return 0;

200
}

Example:
//Write A C++ Program To Compare String.
#include<iostream>
using namespace std;
int main()
{
char str1[50], str2[50];
int i=0, chk=0;
cout<<"Enter the First String: ";
cin>>str1;
cout<<"Enter the Second String: ";
cin>>str2;
while(str1[i]!='\0' || str2[i]!='\0')
{
if(str1[i]!=str2[i])
{
chk = 1;
break;
}
i++;
}
if(chk==0)
cout<<"\nStrings are Equal";
else
cout<<"\nStrings are not Equal";
cout<<endl;
return 0;
}

//Write A C++ Programs To Copy Content Of One File Into Another.


#include <iostream>
#include <fstream>
using namespace std;

int main()
{
201
ifstream fs;
ofstream ft;
string str;
char sourcefile[50], destinationfile[50];

cout << "Enter Source File with Extension: ";

gets(sourcefile);

fs.open(sourcefile);

if (!fs)
{
cout << "Error in Opening Source File...!!!";
exit(1);
}

cout << "Enter Destination File with Extension: ";

gets(destinationfile);

ft.open(destinationfile);

if (!ft)
{
cout << "Error in Opening Destination File...!!!";
fs.close();
exit(2);
}

if (fs && ft)


{
while (getline(fs, str))
{
ft << str << "\n";
}

cout << "\n\n Source File Date Successfully Copied to Destination File...!!!";

}
else
{
cout << "File Cannot Open...!!!";
}

cout << "\n\n Open Destination File and Check!!!\n";

fs.close();
ft.close();
return (0);
}

Output:
202
Enter Source File with Extension: d:\About Us.txt
Enter Destination File with Extension: d:\testing.txt

Source File Date Successfully Copied to Destination File...!!!

Open Destination File and Check!!!

C++ String Concat Example

Let's see the simple example of string concatenation using strcat() function.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char key[25], buffer[25];
cout << "Enter the key string: ";
cin.getline(key, 25);
cout << "Enter the buffer string: ";
cin.getline(buffer, 25);
strcat(key, buffer);
cout << "Key = " << key << endl;
cout << "Buffer = " << buffer<<endl;
return 0;
}

Output:

Enter the key string: Welcome to


Enter the buffer string: C++ Programming.
Key = Welcome to C++ Programming.
Buffer = C++ Programming.

C++ Structures

203
Structure is a collection of variables of different data types under a single name. It is
similar to a class in that, both holds a collection of data of different data types.

C/C++ arrays allow you to define variables that combine several data items of the
same kind, but structure is another user defined data type which allows you to
combine data items of different kinds.

Structures are used to represent a record; suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

For example: You want to store some information about a person: his/her name,
citizenship number and salary. You can easily create different variables name, citNo,
salary to store this information separately.

However, in the future, you would want to store information about multiple persons.
Now, you'd need to create different variables for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2

You can easily visualize how big and messy the code would look. Also, since no
relation between the variables (information) would exist, it's going to be a daunting
task.

A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner,
readable and efficient as well.

This collection of all related information under a single name Person is a structure.

How to declare a structure in C++ programming?


The struct keyword defines a structure type followed by an identifier (name of the
structure).

204
Then inside the curly braces, you can declare one or more members (declare
variables inside curly braces) of that structure.

Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member, for your program. The format
of the struct statement is this:

struct [structure tag]

member definition;

member definition;

...

member definition;

} [one or more structure variables];

For example:

struct Person
{
char name[50];
int age;
float salary;
};

Here a structure person is defined which has three members: name, age and salary
When a structure is created, no memory is allocated.
The structure definition is only the blueprint for the creating of variables. You can
imagine it as a datatype. When you define an integer as below:

int foo;

205
The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is
defined.

Note: Remember to end the declaration with a semicolon (;)

Example:

struct Books
{
char title[50];
char author[50];
char subject[100];TA STRUCTURES
int book_id;
}book;

How to define a structure variable?


Once you declare a structure person as above. You can define a structure variable as:

Person bill;

Here, a structure variable bill is defined which is of type structure Person.

When structure variable is defined, only then the required memory is allocated by the
compiler.

Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.

Hence, 58 bytes of memory is allocated for structure variable bill.

How to access members of a structure?


The members of structure variable is accessed using a dot (.) operator.
Suppose, you want to access age of structure variable bill and assign it 50 to it. You
can perform this task by using following code below:

bill.age = 50;

206
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The
member access operator is coded as a period between the structure variable name
and the structure member that we wish to access. You would use struct keyword to
define variables of structure type. Following is the example to explain usage of
structure:

C++ Program to assign data to members of a structure variable and display it.

#include <iostream>
using namespace std;

struct Person
{
char name[50];
int age;
float salary;
};

int main()
{
Person p1;

cout << "Enter Full name: ";


cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;

cout << "\nDisplaying Information." << endl;


cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;

return 0;
}

Output

Enter Full name: Magdalena Dankova


Enter age: 27
Enter salary: 1024.4

207
Displaying Information.
Name: Magdalena Dankova
Age: 27
Salary: 1024.4

Here a structure Person is declared which has three members name, age and salary.

Inside main() function, a structure variable p1 is defined. Then, the user is asked to
enter information and data entered by user is displayed.

Example:
#include <iostream>
#include <cstring>
using namespace std;

struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Wilson George");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Robert Smith");
strcpy( Book2.subject, "Telecom");

208
Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 Id: " << Book1.book_id <<endl;
cout << "Book 1 Title: " << Book1.title <<endl;
cout << "Book 1 Author: " << Book1.author <<endl;
cout << "Book 1 Subject: " << Book1.subject <<endl<<endl;

// Print Book2 info


cout << "Book 2 Id: " << Book2.book_id <<endl;
cout << "Book 2 Title: " << Book2.title <<endl;
cout << "Book 2 Author: " << Book2.author <<endl;
cout << "Book 2 Subject: " << Book2.subject <<endl<<endl;

return 0;
}

Output:
Book 1 Id: 6495407
Book 1 Title: Learn C++ Programming
Book 1 Author: Wilson George
Book 1 Subject: C++ Programming

Book 2 Id: 6495700


Book 2 Title: Telecom Billing
Book 2 Author: Robert Smith
Book 2 Subject: Telecom

Structure vs class in C++

The C++ class is an extension of the C language structure. Because the only
difference between a structure and a class is that structure members have public
access by default and class members have private access by default, you can
use the keywords class or struct to define equivalent classes.

209
In C++, a structure is the same as a class except for a few differences. The most
important of them is security. A Structure is not secure and cannot hide its
implementation details from the end-user while a class is secure and can hide its
programming and designing details. Following are some differences between a
class and a structure.

Class Structure

Members of a class are private by Members of a structure are public by


default. default.

Memory allocation happens on the


heap. Memory allocation happens on a stack.

It is a reference type data type. It is a value type data type.

It is declared using the class Keyword.


It is declared using the struct keyword.

1) Members of a class are private by default and members of a structure are public
by default.

For example, program 1 fails in compilation but program 2 works fine,


// Program 1
// CPP Program to demonstrate that Members of a class are
// private by default
#include <iostream>
using namespace std;

class Test {
// x is private
int x;
};

// Driver Code
int main()
{
Test t;
t.x = 20;
// compiler error because x is private
getchar();
return 0;
210
}

// Program 2
// CPP Program to demonstrate that members of a structure
// are public by default.
#include <iostream>
using namespace std;

struct Test {
// x is public
int x;
};
int main()
{
Test t;
t.x = 20;
// works fine because x is public
cout << t.x;
getchar();
return 0;
}

Output
20

2) Class is declared using the class keyword, and structure is declared using
the struct keyword.

Syntax:

class ClassName {
private:
member1;
member2;
public:
211
member3;
.
.
memberN;
};

Syntax:

struct structureName{
member1;
member2;
.
.
.
memberN;
};

3) Inheritance is possible in class, and in structures.

// Program 3
// C++ program to demonstrate Inheritance in class
#include <iostream>
using namespace std;

// Base class
class Parent {
public:
int x;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent {
public:

212
int y;
};

// Driver Code
int main()
{

Child obj1;
// An object of class child has all data members
// and member functions of class parent
obj1.y = 7;
obj1.x = 91;
cout << obj1.y << endl;
cout << obj1.x << endl;

return 0;
}

Output
7

91

// Program 4
// C++ program to demonstrate Inheritance in structure
#include <iostream>
using namespace std;

struct Base {
public:
int x;
};

213
struct Derived : Base {
public:
int y;
}; // Is equivalent to struct Derived : public Base {}

int main()
{
Derived d;
d.x = 20; // Works fine because inheritance is public
cout << d.x;
getchar();
return 0;
}

214
C++ OOPs Concepts

The major purpose of C++ programming is to introduce the concept of object


orientation to the C programming language.

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as


truly object-oriented programming language. Smalltalk is considered as the first truly
object-oriented programming language.

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:

o Object

o Class

o Inheritance

o Polymorphism

o Abstraction

o Encapsulation

Object

215
Any entity that has state and behaviour is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical.

In C++, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behaviour. Here, state means
data and behaviour means functionality.

Object is a runtime entity; it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through
object. Let's see an example to create object of student class using s1 as the
reference variable.

Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.

Class

Collection of objects is called class. It is a logical entity. In C++, class is a group of


similar objects. It is a template from which objects are created. It can have fields,
methods, constructors etc.

A class is a blueprint for the object.

Create a Class
A class is defined in C++ using keyword class followed by the name of the class.
216
The body of the class is defined inside the curly brackets and terminated by a
semicolon at the end. The general form of a class declaration is:

class class_name {
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};

The variables declared inside the class are known as data members and the functions are
known as member functions. Only the member functions can have access to the private data
members and private functions. However, the public members (both functions and data) can
be accessed from outside the class. This is shown in fig. below. The binding of data and
functions together into a single class-type variable is referred to as encapsulation.

Data Hiding in classes

217
Example:

class Room {
public:
double length;
double breadth;
double height;

double calculateArea(){
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};

Here, we defined a class named Room.


The variables length, breadth, and height declared inside the class are known
as data members. And, the functions calculateArea() and calculateVolume() are
known as member functions of a class.

Example:
#include<iostream>
using namespace std;
class Room {
218
private:
double length;
double breadth;
double height;
};
int main()
{
Room obj;
obj.length = 10;
obj.breadth = 5;
obj.height = 4;
int area = obj.length * obj.breadth;
cout<<"The area of Room is : " <<area<<endl;
return 0;
}
Output:
[Error] 'double Room::length' is private

Solution: Change private to public access specifier.

#include<iostream>
using namespace std;
class Room {
public:
double length;
double breadth;
double height;
};
int main()
{
Room obj;
obj.length = 10;
obj.breadth = 5;
obj.height = 4;
int area = obj.length * obj.breadth;
cout<<"The area of Room is : " <<area<<endl;
219
return 0;
}

Example:
//program demo using a class
#include<iostream>
using namespace std;
class Room {
private: //access specifier
double length;
double breadth;
double height;
public:
void getData()
{
length = 2;
breadth = 3;
height = 5;
}
void showData()
{
cout<<"Length: "<<length<<endl;
cout<<"Breadth: "<<breadth<<endl;
cout<<"Height: "<<height<<endl;
}
};
int main()
{
double area;
Room obj;
obj.getData();
obj.showData();
return 0;
}

Example:
//program demo using a class
#include<iostream>

220
using namespace std;
class Room {
private: //access specifier
double length;
double breadth;
double height;
public:
void getData();
void showData();
};
void Room::getData()
{
length = 2;
breadth = 3;
height = 5;
}
void Room::showData()
{
cout<<"Length: "<<length<<endl;
cout<<"Breadth: "<<breadth<<endl;
cout<<"Height: "<<height<<endl;
}
int main()
{
double area;
Room obj;
obj.getData();
obj.showData();
return 0;
}

Example:
#include<iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
221
double height;
public:
void getData()
{
length = 10;
breadth = 5;
height = 4;
}
double calculateArea(){
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj;
obj.getData();
cout<<"The area of Room is : " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is : "<<obj.calculateVolume()<<endl;
return 0;
}

Example: Using Scope Resolution Operator


#include<iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:

222
void getData();
double calculateArea();
double calculateVolume();

};
void Room::getData()
{
length = 10;
breadth = 5;
height = 4;
}
double Room::calculateArea()
{
return length * breadth;
}
double Room::calculateVolume()
{
return length * breadth * height;
}
int main()
{
Room obj;
obj.getData();
cout<<"The area of Room is : " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is : "<<obj.calculateVolume()<<endl;
return 0;
}

Example 2:
#include<iostream>
using namespace std;
class Room {
private:
double length;

223
double breadth;
double height;
public:
void getData(double a,double b,double c)
{
length = a;
breadth = b;
height = c;
}
double calculateArea(){
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj;
obj.getData(2,3,4);
cout<<"The area of Room is : " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is : "<<obj.calculateVolume()<<endl;
return 0;
}

Example:
//program demo to compute the area and circumference of a circle.
#include<iostream>
#define PI 3.142
using namespace std;
class Circle {
private:
double radius;

224
public:
void getData(double a)
{
radius = a;
}
double calculateArea(){
return PI * radius * radius;
}

double calculateCircum(){
return 2 * PI * radius;
}

};
int main()
{
Circle obj;
obj.getData(2);
cout<<"The area of Circle is : " <<obj.calculateArea()<<endl;
cout<<"The Circumference of Circle is : "<<obj.calculateCircum()<<endl;
return 0;
}
C++ Objects

When a class is defined, only the specification for the object is defined; no memory or
storage is allocated.

To use the data and access functions defined in the class, we need to create objects.

Syntax to Define Object in C++

className objectVariableName;

We can create objects of Room class (defined in the above example) as follows:

// sample function
void sampleFunction() {
// create objects

225
Room room1, room2;
}

int main(){
// create objects
Room room3, room4;
}

Here, two objects room1 and room2 of the Room class are created
in sampleFunction(). Similarly, the objects room3 and room4 are created in main().
As we can see, we can create objects of a class in any function of the program. We
can also create objects of a class within the class itself, or in other classes.

Also, we can create as many objects as we want from a single class.

C++ Access Data Members and Member Functions

We can access the data members and member functions of a class by using a . (dot)
operator. For example,

room2.calculateArea();

This will call the calculateArea() function inside the Room class for object room2.
Similarly, the data members can be accessed as:

room1.length = 5.5;

In this case, it initializes the length variable of room1 to 5.5.

Example 1: Object and Class in C++ Programming

// Program to illustrate the working of


// objects and class in C++ Programming

#include <iostream>
using namespace std;

// create a class
class Room {

226
public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output

227
Area of Room = 1309
Volume of Room = 25132.8

In this program, we have used the Room class and its object room1 to calculate the
area and volume of a room.
In main(), we assigned the values of length, breadth, and height with the code:

room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

We then called the functions calculateArea() and calculateVolume() to perform the


necessary calculations.
Note the use of the keyword public in the program. This means the members are
public and can be accessed anywhere from the program.
As per our needs, we can also create private members using the private keyword. The
private members of a class can only be accessed from within the class. For example,

class Test {

private:
int a;
void function1() { }

public:
int b;
void function2() { }
}

Here, a and function1() are private. Thus they cannot be accessed from outside the
class.
On the other hand, b and function2() are accessible from everywhere in the program.

Example 2: Using public and private in C++ Class

228
// Program to illustrate the working of
// public and private in C++ Class

#include <iostream>
using namespace std;

class Room {

private:
double length;
double breadth;
double height;

public:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// pass the values of private variables as arguments


room1.initData(42.5, 30.8, 19.2);

cout << "Area of Room = " << room1.calculateArea() << endl;


cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output

229
Area of Room = 1309
Volume of Room = 25132.8

The above example is nearly identical to the first example, except that the class
variables are now private.

Since the variables are now private, we cannot access them directly from main().
Hence, using the following code would be invalid:

// invalid code
obj.length = 42.5;
obj.breadth = 30.8;
obj.height = 19.2;

Instead, we use the public function initData() to initialize the private variables via the
function parameters double len, double brth, and double hgt.

Example:
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Bill Gates";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}

Output:

201
230
Bill Gates

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
e1.insert(201, "Adams",990000);
e2.insert(202, "Wilson", 29000);
e1.display();
e2.display();
return 0;
}

Output:

201 Adams 990000


202 Wilson 29000

Member Functions of Classes in C++


231
Member functions are the functions, which have their declaration inside the class
definition and works on the data members of the class. The definition of member
functions can be inside or outside the definition of class.

If the member function is defined inside the class definition it can be defined directly,
but if its defined outside the class, then we have to use the scope
resolution :: operator along with class name along with function name.

For example:

class Cube
{
public:
int side;
/*
Declaring function getVolume
with no argument and return type int.
*/
int getVolume();
};

If we define the function inside class then we don't not need to declare it first, we can
directly define the function.

class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};

But if we plan to define the member function outside the class definition then we must
declare the function inside class definition and then define it outside.
232
class Cube
{
public:
int side;
int getVolume();
}

// member function defined outside class definition


int Cube :: getVolume()
{
return side*side*side;
}

The main function for both the function definition will be same. Inside main() we will
create object of class, and will call the member function using dot . operator.

Calling Class Member Function in C++


Similar to accessing a data member in the class, we can also access the public
member functions through the class object using the dot operator (.).

Below we have a simple code example, where we are creating an object of the
class Cube and calling the member function getVolume():

int main()
{
Cube C1;
C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
}
Output:
Volume of cube C1 = 16

Example:
//program demo to find the area and perimeter of a circle using class with scope
resolution operator

#include<iostream>
233
using namespace std;
class Circle
{
private: //access specifier
double radius;
const double PI=3.142;
public: //access specifier
void setData(double a);
double calcArea();
double calcPeri();
};
void Circle::setData(double a)
{
radius = a;
}
double Circle::calcArea()
{
return PI * radius * radius;
}
double Circle::calcPeri()
{
return 2 * PI * radius;
}
int main()
{
Circle obj;
int a;
cout<<"Enter the radius: ";
cin>>a;
obj.setData(a);
cout<<"Area of circle is : "<<obj.calcArea()<<endl;
cout<<"Perimeter of circle is : "<<obj.calcPeri()<<endl;

return 0;
}

234
f

C++ Constructors
A constructor is a special type of member function that is called automatically when
an object is created.

In C++, constructor is a special method which is invoked automatically at the time of


object creation. It is used to initialize the data members of new object generally. The
constructor in C++ has the same name as class or structure.

There can be two types of constructors in C++.

1. Default constructor

2. Parameterized constructor

In C++, a constructor has the same name as that of the class and it does not have a
return type. For example,

class Wall {
public:
// create a constructor
Wall() {
// code

235
}
};

Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
 has the same name as the class,
 does not have a return type, and
 is public

C++ Default Constructor


A constructor with no parameters is known as a default constructor.

Example:

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}

Output:

Default Constructor Invoked


Default Constructor Invoked

Example: Program Demo using default constructor


#include<iostream>
using namespace std;
class Room {
236
private:
double length;
double breadth;
double height;
public:
Room()
{
length = 10;
breadth = 5;
height = 4;
}
double calculateArea(){
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj;
cout<<"The area of Room is: " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is: "<<obj.calculateVolume()<<endl;
return 0;
}

Example:
#include<iostream>
using namespace std;
class Room {
public:
double length;
double breadth;
double height;

Room()
{
cout<<"Default Constructor Invoked"<<endl;
}
double calculateArea(){
237
return length * breadth;
}

double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj;
obj.length = 10;
obj.breadth = 5;
obj.height = 4;
cout<<"The area of Room is : " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is : "<<obj.calculateVolume()<<endl;
return 0;
}

In the example above, Wall() is a default constructor.


Example 1: C++ Default Constructor

// C++ program to demonstrate the use of default constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;

public:
// default constructor to initialize variable

238
Wall() {
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};

int main() {
Wall wall1;
return 0;
}

Output

Creating a Wall
Length = 5.5

Here, when the wall1 object is created, the Wall() constructor is called. This sets
the length variable of the object to 5.5.
Note: If we have not defined a constructor in our class, then the C++ compiler will
automatically create a default constructor with an empty code and no parameters.
C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to


provide different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

Example 1:

#include<iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;

239
public:
Room(double a,double b,double c)
{
length = a;
breadth = b;
height = c;
}
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj(2,3,4);
cout<<"The area of Room is : " <<obj.calculateArea()<<endl;
cout<<"The volume of Room is : "<<obj.calculateVolume()<<endl;
return 0;
}

//program demo using constructor to find the area and


//perimeter of a circle
#include<iostream>
using namespace std;
class Circle
{
private: //access specifier
double radius;
const double PI=3.142;
public: //access specifier
Circle(double a); //parameterized constructor
240
double calcArea();
double calcPeri();
};
Circle::Circle(double a)
{
radius = a;
}
double Circle::calcArea()
{
return PI * radius * radius;
}
double Circle::calcPeri()
{
return 2 * PI * radius;
}
int main()
{
int a;
cout<<"Enter the radius: ";
cin>>a;
Circle obj(a);
cout<<"Area of circle is : "<<obj.calcArea()<<endl;
cout<<"Perimeter of circle is : "<<obj.calcPeri()<<endl;

return 0;
}

Example 2:

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
241
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Chris", 890000); //creating an object of Employee
Employee e2=Employee(102, "Mathew", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Chris 890000


102 Mathew 59000

Example : C++ Parameterized Constructor

// C++ program to calculate the area of a wall

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:
// parameterized constructor to initialize variables
Wall(double len, double hgt) {
length = len;
height = hgt;
}

double calculateArea() {
return length * height;
}
};

int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);

242
Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;


cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

Output

Area of Wall 1: 90.3


Area of Wall 2: 53.55

Here, we have created a parameterized constructor Wall() that has 2


parameters: double len and double hgt. The values contained in these parameters
are used to initialize the member variables length and height.
When we create an object of the Wall class, we pass the values for the member
variables as arguments. The code for this is:

Wall wall1(10.5, 8.6);


Wall wall2(8.5, 6.3);

With the member variables thus initialized, we can now calculate the area of the wall
with the calculateArea() function.

C++ Copy Constructor

The copy constructor in C++ is used to copy data of one object to another.

Example:

#include<iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
Room()

243
{
cout<<"Default Constructor Invoked"<<endl;
}
Room(double a,double b,double c)
{
length = a;
breadth = b;
height = c;
}
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}

};
int main()
{
Room obj1(2,4,5);
// copy contents of obj1 to obj2
Room obj2 = obj1;

cout<<"The area of Room is: " <<obj1.calculateArea()<<endl;


cout<<"The volume of Room is: "<<obj1.calculateVolume()<<endl;

cout<<"The area of Room is: " <<obj2.calculateArea()<<endl;


cout<<"The volume of Room is: "<<obj2.calculateVolume()<<endl;

return 0;
}

Output:

The area of Room is : 8


The volume of Room is : 40

244
The area of Room is : 8
The volume of Room is : 40

Example: C++ Copy Constructor

#include <iostream>
using namespace std;

// declare a class
class Wall {
private:
double length;
double height;

public:

// initialize variables with parameterized constructor


Wall(double len, double hgt) {
length = len;
height = hgt;
}

// copy constructor with a Wall object as parameter


// copies data of the obj parameter
Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

double calculateArea() {
return length * height;
}
};

245
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);

// copy contents of wall1 to wall2


Wall wall2 = wall1;

// print areas of wall1 and wall2


cout << "Area of Wall 1: " << wall1.calculateArea() << endl;
cout << "Area of Wall 2: " << wall2.calculateArea();

return 0;
}

Output

Area of Wall 1: 90.3


Area of Wall 2: 90.3

In this program, we have used a copy constructor to copy the contents of one object
of the Wall class to another. The code of the copy constructor is:

Wall(Wall &obj) {
length = obj.length;
height = obj.height;
}

Notice that the parameter of this constructor has the address of an object of
the Wall class.
We then assign the values of the variables of the obj object to the corresponding
variables of the object calling the copy constructor. This is how the contents of the
object are copied.
In main(), we then create two objects wall1 and wall2 and then copy the contents
of wall1 to wall2:

246
// copy contents of wall1 to wall2
Wall wall2 = wall1;

Here, the wall2 object calls its copy constructor by passing the address of
the wall1 object as its argument i.e. &obj = &wall1.

Note: A constructor is primarily used to initialize objects. They are also used to run a
default code when an object is created.

C++ Destructor

A destructor works opposite to constructor; it destructs the objects of classes. It can


be defined only once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be


applied on destructors.

C++ Constructor and Destructor Example

Let's see an example of constructor and destructor in C++ which is called


automatically.

#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
247
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

248
Friend Function in C++

As we already know that in an object-oriented programming language, the members


of the class can only access the data and functions of the class but outside functions
cannot access the data of the class. There might be situation that the outside
functions need to access the private members of the class so in that case, friend
function comes into the picture.

What is a friend function?

A friend function is a function of the class defined outside the class scope but it has
the right to access all the private and protected members of the class.

A friend function in C++ is defined as a function that can access private, protected
and public members of a class.

The friend function is declared using the friend keyword inside the body of the class.

The friend functions appear in the class definition but friends are the member
functions.

Characteristics of a Friend function:

o The function is not in the scope of the class to which it has been declared as a
friend.

o It cannot be called using the object as it is not in the scope of that class.

o It can be invoked like a normal function without using the object.

249
o It cannot access the member names directly and has to use an object name and
dot membership operator with the member name.

o It can be declared either in the private or the public part.

Why do we need a friend function in C++?

o Friend function in C++ is used when the class private data needs to be
accessed directly without using object of that class.

o Friend functions are also used to perform operator overloading. As we already


know about the function overloading, operators can also be overloaded with the
help of operator overloading.

Characteristics of a Friend function


1. The friend function is declared using friend keyword.
2. It is not a member of the class but it is a friend of the class.
3. As it is not a member of the class so it can be defined like a normal function.
4. Friend functions do not access the class data members directly but they pass an
object as an argument.
5. It is like a normal function.
6. If we want to share the multiple class's data in a function then we can use the
friend function.

Syntax for the declaration of a friend function.

class class_name
{
friend data_type function_name(arguments); // syntax of friend function
};

In the above declaration, the friend function is preceded by the keyword friend. The
function can be defined anywhere in the program like a normal C++ function. The
function definition does not use either the keyword friend or scope resolution
operator.

Example:

#include<iostream>
250
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// Room()
// {
// length=0; breadth=0; height=0;
// }
Room (): length (0), breadth(0), height(0) {}
Room(double a,double b,double c)
{
length = a;
breadth = b;
height = c;
}
friend double calculateArea(Room);

};
double calculateArea(Room obj)
{
double area = obj.length * obj.breadth * obj.height;
return area;

}
int main()
{
Room obj(2,3,4);
cout<<"The area is = "<<calculateArea(obj)<<endl;

return 0;
}
Output:

251
The area is = 24

Example:

Write a C++ program using friend function to compute the area and circumference of
a circle.

//program demo using friend function to calculate the area and circumference of a
circle
#include<iostream>
using namespace std;
class Circle {
private:
double radius;
friend double calculateArea(Circle);
friend double calculateCircum(Circle);
public:
Circle (): radius (0) {}
Circle(double a)
{
radius = a;
}
};
double calculateArea(Circle obj)
{
double area = 3.142 * obj.radius * obj.radius;
return area;

}
double calculateCircum(Circle obj)
{
double circum = 2 * 3.142 * obj.radius;
return circum;

}
int main()
252
{
Circle obj(5);
cout<<"The area of circle is = "<<calculateArea(obj)<<endl;
cout<<"The circumference of circle is = "<<calculateCircum(obj)<<endl;
return 0;
}

Output:

The area of circle is = 78.55

The circumference of circle is = 31.42

Let's understand the friend function through an example.

#include <iostream>
using namespace std;
class Distance
{
private:
int meters;
public:
// constructor
Distance()
{
meters = 0;
}
// definition of display_data() method
void display_data()
{
cout << "Meters value : " << meters<<endl;
}

//prototype of a friend function.


friend void addvalue(Distance &d);

};
// Definition of friend function
void addvalue(Distance &d) // argument contain the reference

253
{
d.meters = d.meters+10; // incrementing the value of meters by 10.
}
// main() method
int main()
{
Distance d1; // creating the object of class distance.
d1.display_data(); // meters = 0
addvalue(d1); // calling friend function
d1.display_data(); // meters = 10
return 0;
}

In the above code, Distance is the class that contains private field named as
'meters'. The Distance() is the constructor method that initializes the 'meters' value
with 0. The display_data() is a method that displays the 'meters' value.
The addvalue() is a friend function of Distance class that modifies the value
of 'meters'. Inside the main() method, d1 is an object of a Distance class.

Output

Friend function can also be useful when we are working on objects of two different
classes.

Example:
#include <iostream>
using namespace std;
class Box
{
private:
254
int length;
public:
Box (): length (0) {}
friend int printLength (Box); //friend function
};
int printLength (Box b)
{
b. length +=10;
return b. length;
}
int main ()
{
Box b;
cout <<"Length of box:" <<printLength (b)<<endl;
return 0;
}

Output:
Length of box:10

Types of Class Member Functions in C++

Following are the different types of Member functions:

1. Simple functions

2. Static functions

3. Const functions

4. Inline functions

5. Friend functions

Simple Member functions in C++


These are the basic member function, which dont have any special keyword
like static etc as prefix. All the general member functions, which are of below given
form, are termed as simple and basic member functions.

255
return_type functionName(parameter_list)
{
function body;
}

Static Member functions in C++


Static is something that holds its position. Static is a keyword which can be used
with data members as well as the member functions. We will discuss this in details
later. As of now we will discuss its usage with member functions only.

A function is made static by using static keyword with function name. These functions
work for the class as whole rather than for a particular object of a class.

It can be called using the object and the direct member access . operator. But, its
more typical to call a static member function by itself, using class name and scope
resolution :: operator.

Example:
#include<iostream>
using namespace std;
class X
{
public:
static void f()
{
cout<<"Static Member..."<<endl;
}
};

int main()
{
X::f(); // calling member function directly with class name
}

Output:
Static Member

256
Const Member functions in C++
Const keyword makes variables constant, that means once defined, there values can't
be changed.

When used with member function, such member functions can never modify the
object or its related data members.

Like member functions and member function arguments, the objects of a class can
also be declared as const. an object declared as const cannot be modified and
hence, can invoke only const member functions as these functions ensure not to
modify the object.

A const object can be created by prefixing the const keyword to the object
declaration. Any attempt to change the data member of const objects results in a
compile-time error.

// basic syntax of const Member Function

void fun() const


{
// statement
}

datatype function_name const();

Syntax:
const Class_Name Object_name;

 When a function is declared as const, it can be called on any type of object,


const object as well as non-const objects.
 Whenever an object is declared as const, it needs to be initialized at the
time of declaration. however, the object initialization while declaring is
possible only with the help of constructors.

A function becomes const when the const keyword is used in the function’s
declaration. The idea of const functions is not to allow them to modify the object on
257
which they are called. It is recommended the practice to make as many functions
const as possible so that accidental changes to objects are avoided.

Example:

//This is used to restrict modification of data members inside function.

#include<iostream>
using namespace std;
class Base
{
int x;
public:
Base() { }
Base(int a):x{a} { }
void setX(int a) { x = a;}
int getX() const { return x; }
};
int main()
{
Base b;
b.setX(10);
cout<<b.getX()<<endl;
return 0;
}
Output:

10

Now try to change the value of x in getX() const function:

//This is used to restrict modification of data members inside function.

#include<iostream>

258
using namespace std;
class Base
{
int x;
public:
Base() { }
Base(int a):x{a} { }
void setX(int a) { x = a;}
int getX() const { x=20; return x; }
};
int main()
{
Base b;
b.setX(10);
cout<<b.getX()<<endl;
return 0;
}

Output:
[Error] assignment of member 'Base::x' in read-only object

If you make data member as mutable it says that all the data members are not
allowed to be changed in const function but the mutable is allowed.
Example:
//This is used to restrict modification of data members inside function.

#include<iostream>
using namespace std;
class Base
{
mutable int x;
public:
Base() { }
Base(int a):x{a} { }
void setX(int a) { x = a;}

259
int getX() const { x=20; return x; }
};
int main()
{
Base b;
b.setX(10);
cout<<b.getX()<<endl;
return 0;
}
Output:
20

Example:
//This is used to restrict modification of data members inside function.

#include<iostream>
using namespace std;
class Base
{
mutable int x;
int y;
public:
Base() { }
Base(int a,int b):x{a},y{b} { }
void setX(int a) { x = a;}
int getX() const { x=20; y=30; return x; }
};
int main()
{
Base b;
b.setX(10);
cout<<b.getX()<<endl;
return 0;
}
Output:

260
[Error] assignment of member 'Base::y' in read-only object

Example:
#include <iostream>
using namespace std;

class Test {
int value;

public:
Test(int v = 0) { value = v; }

int getValue() const


{
return value;
}
};

int main()
{
Test t(20);
cout << t.getValue();
return 0;
}

Output:
20

When a function is declared as const, it can be called on any type of object. Non-
const functions can only be called by non-const objects. For example the following
program has compiler errors.

#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) {value = v;}
int getValue() {return value;}

261
};

int main() {
const Test t;
cout << t.getValue();
return 0;
}

Example:

// Demonstration of constant object,


// show that constant object can only
// call const member function
#include<iostream>
using namespace std;
class Demo
{
int value;
public:
Demo(int v = 0) {value = v;}
void showMessage()
{
cout<<"Hello World We are Tushar, "
"Ramswarup, Nilesh and Subhash Inside"
" showMessage() Function"<<endl;
}
void display()const
{
cout<<"Hello world I'm Rancho "
"Baba Inside display() Function"<<endl;
}
};
int main()
{
//Constant object are initialised at the time of declaration using constructor

262
const Demo d1;
//d1.showMessage();Error occurred if uncomment.
d1.display();
return(0);
}

OUTPUT:
Hello world I'm Rancho Baba Inside display() Function

Example:
#include<iostream>
using namespace std;
class Demo {
int val;
public:
Demo(int x = 0) {
val = x;
}
int getValue() const {
return val;
}
};
int main() {
const Demo d(28);
Demo d1(8);
cout << "The value using object d : " << d.getValue();
cout << "\nThe value using object d1 : " << d1.getValue();
return 0;
}
Output
The value using object d : 28
The value using object d1 : 8

263
Inline Function in C++
An inline function in C++ is an optimisation feature that reduces the execution
time of a program, just as we have macros in C. This concept of inline functions is
used while handling Classes in C++. It is used otherwise as well, though. Whenever
such a function is encountered, the compiler replaces it with a copy of that
function’s code (function definition). In other words, one may say that such a
function is expanded in-line, hence named as an inline function.

Syntax for an inline function:

inline return_type function_name(parameters)


{
// function code
}

Example:
#include<iostream>
#include<iomanip>
using namespace std;
inline void printMe(int count,string str)
{
cout<<count<<setw(10)<<str<<endl;
}
int main()
{
for(int i=0;i<100;i++)
{
printMe(i,"Sai Pali");
}
return 0;
}

Example:
#include<iostream>
using namespace std;
264
inline int add(int a, int b) //Inline function definition
{
return a+b;
}
int main()
{
cout<<"The addition of 562 and 451 gives the value:"<<add(562,451)<<"\n";
//Inline function call
return 0;
}

Output: The addition of 562 and 451 gives the value:1013

Why do we need an inline function in C++?

The main use of the inline function in C++ is to save memory space. Whenever the
function is called, then it takes a lot of time to execute the tasks, such as moving to
the calling function. If the length of the function is small, then the substantial amount
of execution time is spent in such overheads, and sometimes time taken required for
moving to the calling function will be greater than the time taken required to execute
that function.

The solution to this problem is to use macro definitions known as macros. The
preprocessor macros are widely used in C, but the major drawback with the macros is
that these are not normal functions which means the error checking process will not
be done during the compilation.

C++ has provided one solution to this problem. In the case of function calling, the
time for calling such small functions is huge, so to overcome such a problem, a new
concept was introduced known as an inline function. When the function is
encountered inside the main() method, it is expanded with its definition thus saving
time.

We cannot provide the inlining to the functions in the following circumstances:

o If a function is recursive.

o If a function contains a loop like for, while, do-while loop.


265
o If a function contains static variables.

o If a function contains a switch or go to statement

When do we require an inline function?

An inline function can be used in the following scenarios:

o An inline function can be used when the performance is required.

o It can be used over the macros.

o We can use the inline function outside the class so that we can hide the internal
implementation of the function.

Advantages of inline function


o In the inline function, we do not need to call a function, so it does not cause any
overhead.

o It also saves the overhead of the return statement from a function.

o It does not require any stack on which we can push or pop the variables as it
does not perform any function calling.

o An inline function is mainly beneficial for the embedded systems as it yields less
code than a normal function.

266
C++ Overloading (Function and Operator)

If we create two or more members having the same name but different in number or
type of parameter, it is known as C++ overloading. In C++, we can overload:

o methods,

o constructors, and

o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:


1. Function overloading

2. Operator overloading

267
C++ Function Overloading

Function Overloading is defined as the process of having two or more function with
the same name, but different in parameters is known as function overloading in C++.
In function overloading, the function is redefined by using either different types of
arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.

The advantage of Function overloading is that it increases the readability of the


program because you don't need to use different names for the same action.

C++ Function Overloading Example

Let's see the simple example of function overloading where we are changing number
of arguments of add() method.

// program of function overloading when number of arguments vary.

#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

Output:

30
268
55

Let's see the simple example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);

int mul(int a,int b)


{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}

Output:

r1 is : 42
r2 is : 0.6

Operator Overloading in C++

269
Operator overloading is an important concept in C++. It is polymorphism in which an
operator is overloaded to give user defined meaning to it. Overloaded operator is used
to perform operation on user-defined data type. For example, '+' operator can be
overloaded to perform addition on various data types, like for Integer,
String(concatenation) etc.

Operator overloading is a compile-time polymorphism.

Almost any operator can be overloaded in C++. However, there are few operators
which cannot be overloaded. Operators that are not overloaded are follows

 scope operator - ::
 sizeof
 member selector - .
 member pointer selector - *
 ternary operator - ?:

Operator Overloading Syntax

Implementing Operator Overloading in C++


Operator overloading can be done by implementing a function which can be :
 Member Function
 Non-Member Function
270
 Friend Function

The advantage of Operators overloading is to perform different operations on the


same operand.

Example:
C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void
operator ++ () operator function is defined (inside Test class).

// program to overload the unary operator ++.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

Output:

The Count is: 10

271
Example: ++ Operator (Unary Operator) Overloading

// Overload ++ when used as prefix

#include <iostream>
using namespace std;

class Count {
private:
int value;

public:

// Constructor to initialize count to 5


Count() : value(5) {}

// Overload ++ when used as prefix


void operator ++ () {
++value;
}

void display() {
cout << "Count: " << value << endl;
}
};

int main() {
Count count1;

// Call the "void operator ++ ()" function


++count1;

count1.display();
return 0;

272
}

Output

Count: 6

Here, when we use ++count1;, the void operator ++ () is called. This increases
the value attribute for the object count1 by 1.
Note: When we overload operators, we can use it to work in any way we like. For
example, we could have used ++ to increase value by 100.

Let's see a simple example of overloading the binary operators.

// program to overload the binary operators.

#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};

void A :: operator+(A a)
{

int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;

273
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}

Output:

The result of the addition of two objects is : 9

274

You might also like