CPP Notes
CPP Notes
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that
supports object-oriented, procedural and generic programming.
Bjarne Stroustrup
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++.
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
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.
5. The Concept of Virtual functions and also Constructors and Destructors for
Objects.
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.
No C C++
.
2) Data is less secured in C. In C++, you can use modifiers for class
members to make it inaccessible for
3
outside users.
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.
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.
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.
Adding new data and function is not Adding new data and function is
easy. easy.
In object-oriented programming,
In procedural programming, function is data is more important than
more important than data. function.
5
Procedural Oriented Programming Object Oriented Programming
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.
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.
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.
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.
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.
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.
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.
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.
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
C++ Features
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.
In C++, complex data types called Abstract Data Types (ADT) can be created using
classes.
3) Portable
16
4) Mid-level / Intermediate 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
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.
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.
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.
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.
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.
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.
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.
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++.
Step 1) First you must download the Dev C++ on your Windows machine. Visit to
Download Dev C++: http://www.bloodshed.net/
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”.
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.
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.
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.
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.
main(), is the function which holds the executing part of program its return type
is int.
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.
Let us see the common header files used in C++ programming are:
<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.
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
#include <iostream>
using namespace std;
int main( ) {
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
}
Output:
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.
#include <iostream>
using namespace std;
int main( ) {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
}
Output:
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:
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:
28
// Namespace n1
namespace n1 {
int x = 2;
// Namespace n2
namespace n2 {
int x = 5;
// Driver Code
int main()
{
// The methods and variables called
// using scope resolution(::)
cout << n1::x << endl;
// Function call
n1::fun();
// 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:
// 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
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>
int 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
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
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
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]);
#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";
Output
35
--------11
******2222
@@@@@33333
#########4
Syntax
setprecision([number_of_digits]);
cout<<setprecision(5)<<1234.537;
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]);
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;
Output
#include <iostream.h>
#include <iomanip.h>
int main()
{
int num=10;
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:
Additional
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.
int a;
int _ab;
int a30;
int 4;
int x y;
int double;
Constants:
Constants are like a variable, except that their value never changes during execution
once defined.
Examples:
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. [] () {}, ; * = #
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:
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.
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.
signed
unsigned
long
short
Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:
float 4
double 8
long double 12
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:
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.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operator
6. Unary 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
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
50
cout << "a + b = " << (a + b) << endl;
return 0;
}
Output
a +b=9
a -b=5
a * b = 14
a /b=3
a %b=1
/ 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
% Modulo Operator
int num = 5;
// increment operator
++num; // 6
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;
= 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;
#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;
return 0;
}
Output
a=2
b=7
After a += b;
a=9
A relational operator is used to check the relationship between two operands. For
example,
54
== Is Equal To 3 == 5 gives us false
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
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
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.
Suppose,
56
a=5
b=8
Then,
#include <iostream>
using namespace std;
int main() {
bool result;
57
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 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
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).
Operator Description
| Binary OR
^ Binary XOR
a & b;
a | b;
| Bitwise OR 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.
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:
00001100
& 00011001
_________
#include <iostream>
using namespace std;
int main() {
// declare variables
int a = 12, b = 25;
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,
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;
return 0;
}
Output:
a=4
b=5
a&b=4
a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
00001100
| 00011001
_________
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
Example:
4: 100
5: 101
---------
int main() {
// declare variables
int a = 4, b = 5;
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:
00001100
^ 00011001
_________
#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
Example:
4: 100
5: 101
-------
001: The result is 1
#include <iostream>
using namespace std;
int main() {
// declare variables
int a = 4, b = 5;
return 0;
}
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.
~ 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
For example,
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.
#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 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.
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.
#include <iostream>
int main() {
// 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;
}
// 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.
N << 0 = N
N << 1 = (N << 0) * 2
N << 2 = (N << 1) * 2
N << 3 = (N << 2) * 2
and so on.
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:
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.
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.
int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated
before + (additive operator).
73
Logical AND && Left to right
Arithmetic Operators
Operato
Description
r
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
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)
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
* Pointer to a variable.
?: Conditional Expression
76
C++ Control Structure:
Decision Making & Branching:
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:
if(condition){
//code to be executed
}
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
79
#include <iostream>
using namespace std;
int main() {
int number;
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
}
81
How if...else Statement Works
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
#include <iostream>
using namespace std;
int main() {
int number;
if (number >= 0) {
cout << "You entered a positive integer: " << number << endl;
}
else {
84
cout << "You entered a negative integer: " << number << endl;
}
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
if(expression)
{
if(expression1)
{
statement-block1;
}
else
{
statement-block2;
}
}
else
{
statement-block3;
}
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.
#include <iostream>
using namespace std;
int main() {
int 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;
}
return 0;
}
88
Output 1
Enter an integer: 35
The number is positive.
This line is always printed.
Output 2
Output 3
Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.
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:
Output:
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:
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
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
Output 2
Output 3
96
Enter two numbers:
2.3
4.5
2.3 * 4.5 = 10.35
Output 4
Output 5
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;
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:
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.
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.
Flowchart:
101
102
Example 1: Printing Numbers From 1 to 5
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output
103
12345
#include <iostream>
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!
Variabl
Iteration i <= 5 Action
e
#include <iostream>
int main() {
int num, sum;
105
sum = 0;
return 0;
}
Output
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.
Here,
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:
Here, for every value in the collection, the for loop is executed and the value is
assigned to the variable.
#include <iostream>
int main() {
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
107
Nested For Loop:
We can also have nested for loop, i.e one for loop inside another for loop. Basic
syntax is,
#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
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:
In the above program, the condition is always true which will then run the code for
infinite times.
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:
#include <iostream>
int main() {
int i = 1;
110
}
return 0;
}
Output
12345
Variabl
Iteration i <= 5 Action
e
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
111
// take input from the user
cout << "Enter a number: ";
cin >> number;
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++;
}
}
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
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:
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
#include <iostream>
int main() {
int i = 1;
return 0;
}
Output
12345
115
Variabl
Iteration i <= 5 Action
e
not
i=1 checke 1 is printed and i is increased to 2
d
#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
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
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.
If the condition of a loop is always true, the loop runs for infinite times (until the
memory is full). For example,
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.
A for loop is usually used when the number of iterations is known. For example,
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
}
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.
#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
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:
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.
120
Working of C++ break Statement
121
Example 1: break with for loop
#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.
#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;
}
123
sum += number;
}
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.
When break is used with nested loops, break terminates the inner loop. For example,
#include <iostream>
124
using namespace std;
int main() {
int number;
int sum = 0;
// 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
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
125
break;
}
cout<<i<<"\n";
}
}
The C++ break statement breaks inner loop only if you use break statement inside
the inner loop.
#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;
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.
#include <iostream>
using namespace std;
128
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
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.
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
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
// 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;
}
}
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.
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.
131
When continue is used with nested loops, it skips the current iteration of the inner
loop. For example,
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// 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.
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:
# include <iostream>
using namespace std;
int main()
{
float num, average, sum = 0.0;
int i, n;
134
cout << "Maximum number of inputs: ";
cin >> n;
jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Output
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:
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.
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.
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.
138
#include <iostream>
using namespace std;
void test();
int main()
{
++c;
// Outputs 13
cout << c <<endl;
test();
return 0;
}
void test()
{
++c;
// Outputs 14
cout << c;
}
Output
13
14
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();
void test()
{
// local variable to test()
int var1;
var1 = 6;
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.
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;
int main()
{
test();
test();
return 0;
}
Output
1
2
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()
{
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
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.
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.
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
The extern variable is visible to all the programs. It is used if two or more files are
sharing same variable or function.
The extern modifier is most commonly used when there are two or more files sharing
the same global variables or functions as explained below.
main() {
count = 5;
write_extern();
}
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;
}
147
C++ Functions
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
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
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
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.
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.
#include <iostream>
#include <cmath>
using namespace std;
149
int main() {
double number, squareRoot;
number = 25.0;
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5
#include<iostream>
#include<math.h>
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
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.
// 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.
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
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.
int main() {
// calling a function
greet();
152
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
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;
int main()
{
int a = 10;
int b = 20;
int c = sum (a, b); //calling the function
cout << c;
}
Return Statement
In the above programs, we have used void in the function declaration. For example,
void displayNumber() {
// code
}
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);
}
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.
#include <iostream>
// function prototype
int add(int, int);
int main() {
int sum;
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
# include <iostream>
using namespace std;
void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}
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.
#include <iostream>
using namespace std;
int prime();
int main()
{
int num, i, flag = 0;
158
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}
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.
#include <iostream>
using namespace std;
159
void prime(int n);
int main()
{
int num;
cout << "Enter a positive integer to check: ";
cin >> num;
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.
#include <iostream>
using namespace std;
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
if(flag == 1)
cout << num << " is not a prime number.";
else
cout<< num << " is a prime number.";
return 0;
}
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.
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.
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.
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:
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.
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>
int main()
int data = 3;
change(&data);
cout << "Value of the data is: " << data<< endl;
return 0;
*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:
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.
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:
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:
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
#include <iostream>
using namespace std;
int main() {
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.
#include <iostream>
using namespace std;
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;
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++.
However, if arguments are passed while calling the function, the default arguments
are ignored.
173
Working of default arguments
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;
int main() {
return 0;
}
Example: Default Argument
#include <iostream>
using namespace std;
int main() {
int count = 5;
175
// #, 3 will be parameters
display('#');
return 0;
}
Output
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;
int main() {
int count = 5;
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();
}
178
C++ Arrays
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.
Fixed size
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
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;
cout << "\n\n Enter " << n << " integers into an array :\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 << "\n\n Enter the " << n << " elements of the array: \n\n";
for(i=0; i<n; i++)
{
cin >> arr[i];
}
cout << "\n\n Enter the position, between 1 and " << n << " , of the element to be
deleted : ";
cin >> pos;
cout << " \n\nThe " << n-1 << " elements of the array, after deletion are : \n\n";
for(i=0; i<n-1; i++)
{
cout << arr[i] << " ";
}
183
return 0;
}
Output:
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;
cout << "\n\n Enter " << n << " integers into an array :\n\n";
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";
185
return 0;
}
Output:
#include <iostream>
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";
cout << "\nEnter the " << row * col << " elements of second matrix : \n";
187
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m1[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
188
C++ Program to Find the Smallest and Largest element in an Array
#include <iostream>
using namespace std;
189
int findMaximum(int a[], int n)
{
int mx = a[0]; //initializing maximum
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 << "\n\n Enter the " << n << " elements of the array: \n\n";
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
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.
Output:
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:
Let's see an example of C++ array which prints maximum number in an array using
function.
#include <iostream>
Output:
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.
#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
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.
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;
for(i=0;a[i]!='\0';++i)
{
cout<<a[i];
}
return 0;
}
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;
}
int main()
{
string s1, s2;
s2 = s1;
return 0;
}
197
s2 = C++ Strings
strcpy(s2, s1);
return 0;
}
198
strcat(s1, s2);
cout << "s1 = "<< s1 << endl;
cout << "s2 = "<< s2;
return 0;
}
#include <iostream>
#include <cstring>
int main()
{
char s1[100], s2[100];
strcpy(s2, s1);
return 0;
}
#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:
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;
}
int main()
{
201
ifstream fs;
ofstream ft;
string str;
char sourcefile[50], destinationfile[50];
gets(sourcefile);
fs.open(sourcefile);
if (!fs)
{
cout << "Error in Opening Source File...!!!";
exit(1);
}
gets(destinationfile);
ft.open(destinationfile);
if (!ft)
{
cout << "Error in Opening Destination File...!!!";
fs.close();
exit(2);
}
cout << "\n\n Source File Date Successfully Copied to Destination File...!!!";
}
else
{
cout << "File Cannot Open...!!!";
}
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
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:
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.
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:
member definition;
member definition;
...
member definition;
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.
Example:
struct Books
{
char title[50];
char author[50];
char subject[100];TA STRUCTURES
int book_id;
}book;
Person bill;
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.
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;
return 0;
}
Output
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;
return 0;
}
Output:
Book 1 Id: 6495407
Book 1 Title: Learn C++ Programming
Book 1 Author: Wilson George
Book 1 Subject: C++ Programming
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
1) Members of a class are private by default and members of a structure are public
by default.
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;
};
// Program 3
// C++ program to demonstrate Inheritance in class
#include <iostream>
using namespace std;
// Base class
class Parent {
public:
int x;
};
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
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 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.
In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.
Class
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.
217
Example:
class Room {
public:
double length;
double breadth;
double height;
double calculateArea(){
return length * breadth;
}
double calculateVolume(){
return length * breadth * height;
}
};
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
#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;
}
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.
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.
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;
#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() {
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;
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.
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:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
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:
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();
}
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.
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.
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
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:
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;
}
#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
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;
}
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:
#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);
return 0;
}
Output
With the member variables thus initialized, we can now calculate the area of the wall
with the calculateArea() function.
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;
return 0;
}
Output:
244
The area of Room is : 8
The volume of Room is : 40
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
double calculateArea() {
return length * height;
}
};
245
int main() {
// create an object of Wall class
Wall wall1(10.5, 8.6);
return 0;
}
Output
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 is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
#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++
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.
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.
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 Friend function in C++ is used when the class private data needs to be
accessed directly without using object of that class.
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:
#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;
}
};
// 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
1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions
255
return_type functionName(parameter_list)
{
function body;
}
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.
Syntax:
const Class_Name Object_name;
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:
#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
#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 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:
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.
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;
}
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.
o If a function is recursive.
o We can use the inline function outside the class so that we can hide the internal
implementation of the 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
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.
Let's see the simple example of function overloading where we are changing number
of arguments of add() method.
#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.
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
Output:
r1 is : 42
r2 is : 0.6
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.
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 - ?:
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).
#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:
271
Example: ++ Operator (Unary Operator) Overloading
#include <iostream>
using namespace std;
class Count {
private:
int value;
public:
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count 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.
#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:
274