Module-2
Module-2
In C++ programming, if statement is used to test the condition. There are various types of if
statements in C++.
• if statement
• if-else statement
• nested if statement
• if-else-if ladder
C++ IF Statement
if(condition){
//code to be executed
}
C++ If Example
#include <iostream>
using namespace std;
int main () {
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}
Output:/p>
It is even number
The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
If-else 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;
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
The C++ if-else-if ladder statement executes one condition from multiple statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
#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)
{
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:
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;
break;
}
int main () {
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
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
The C++ for loop is used to iterate a part of the program several times. If the number of iteration
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:
Output:
1
2
3
4
5
6
7
8
9
10
#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:
11
12
13
21
22
23
31
32
33
C++ Infinite For Loop
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>
int main () {
for (; ;)
{
cout<<"Infinitive For Loop";
}
}
Output:
Flowchart:
#include <iostream>
using namespace std;
int main() {
int i=1;
while(i<=10)
{
cout<<i <<"\n";
i++;
}
}
Output:
1
2
3
4
5
6
7
8
9
10
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:
11
12
13
21
22
23
31
32
33
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:
The C++ do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
The C++ do-while loop is executed at least once because condition is checked after loop body.
do{
//code to be executed
}while(condition);
Flowchart:
Let's see a simple example of C++ do-while loop to print the table of 1.
#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
C++ Nested do-while Loop
In C++, if you use do-while loop inside another do-while loop, it is known as nested do-while
loop. The nested do-while loop is executed fully for each outer do-while loop.
#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:
11
12
13
21
22
23
31
32
33
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);
#include <iostream>
using namespace std;
int main() {
do{
cout<<"Infinitive do-while Loop";
} while(true);
}
Output:
C++ Functions
The function in C++ language is also known as procedure or subroutine in other programming
languages.
To perform any task, we can create function. A function can be called many times. It provides
modularity and code reusability.
Advantage of functions in C
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.
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.
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.
Declaration of a function
#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();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.
Let's understand call by value and call by reference in C++ language one by one.
In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in C++ language by the example given
below:
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Output:
Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
Let's try to understand the concept of call by reference in C++ language by the example given
below:
#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;
Output:
2 Changes made inside the function is not Changes made inside the function is
reflected on other functions reflected outside the function also
3 Actual and formal arguments will be created Actual and formal arguments will be
in different memory location created in same memory location
INLINE FUNCTIONS
One of the key features of C++ is the inline function. Therefore, let's first examine the
utilization of inline functions and their intended application. If make a function is inline, then
the compiler replaces the function calling location with the definition of the inline function at
compile time.
Any changes made to an inline function will require the inline function to be recompiled again
because the compiler would need to replace all the code with a new code; otherwise, it will
execute the old functionality.
In brief, When the program executes a function call instruction, the CPU copies the function's
arguments to the stack, caches the memory address of the next instruction and then hands
control to the targeted function. The CPU then performs the function's code, saves the return
value in a designated memory address or register, and hands control back to the function that
is called the function. This may become overhead if the function's execution time is shorter
than the time required to move from the calling function to the called function (callee). The
overhead of the function call is typically negligible compared to the length of time required to
run large or complicated functions. The time needed to call a small, frequently used function,
however, is often far longer than the time necessary to run the function's code. Due to the fact
that their execution time is less than switching time, tiny functions experience this overhead.
To minimize the overhead of function calls, C++ offers inline functions. When a function is
invoked, it expands in line and is known as an inline function. When an inline function is
invoked, its entire body of code is added or replaced at the inline function call location. At
compile time, the C++ compiler makes this substitution. Efficiency may be increased by inline
function if it is tiny. To the compiler, inlining is merely a request; it is not a command. The
compiler may reject the inlining request. The compiler may not implement inlining in situations
like these:
return_type function_name(parameters)
{
// function code?
}
Let's understand the difference between the normal function and the inline function.
Inside the main() method, when the function fun1() is called, the control is transferred to the
definition of the called function. The addresses from where the function is called and the
definition of the function are different. This control transfer takes a lot of time and increases
the overhead.
When the inline function is encountered, then the definition of the function is copied to it. In
this case, there is no control transfer which saves a lot of time and also decreases the overhead.
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;
Once the compilation is done, the code would be like as shown as below:
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
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.
• If a function is recursive.
Default arguments
A default argument is a value provided in a function declaration that is automatically
assigned by the compiler if the calling function doesn’t provide a value for the argument. In
case any value is passed, the default value is overridden.
The following is a simple C++ example to demonstrate the use of default arguments. Here,
we don’t have to write 3 sum functions; only one function works by using the default
values for 3rd and 4th arguments.
#include <iostream>
using namespace std;
// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Output
25
50
80
Since C++ is an object-oriented language, program is designed using objects and classes in
C++.
In C++, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behaviour. Here, state means data and
behaviour means functionality. Object is a runtime entity, it is created at runtime. Object is an
instance of a class. All the members of the class can be accessed through object.
Let's see an example to create object of student class using s1 as the reference variable.
In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
#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 = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Output:
201
Sonoo Jaiswal
Let's see another example of C++ class where we are initializing and displaying object through
method.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}
Output:
201 Sonoo
202 Nakul
Let's see another example of C++ class where we are storing and displaying employee
information using method.
#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, "Sonoo",990000);
e2.insert(202, "Nakul", 29000);
e1.display();
e2.display();
return 0;
}
Output:
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in
C++ has the same name as class or structure.
1. <class-name> (list-of-parameters);
Constructors lack a return type since they don't have a return value.
• Default constructor
• Parameterized constructor
A constructor which has no argument is known as default constructor. It is invoked at the time
of creating object.
#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:
#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;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Em
ployee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
2. Default There isn't an input argument for constructors. However, input arguments are
available for copy and parameterized constructors.
3. There is no return type for constructors.
4. An object's constructor is invoked automatically upon creation.
5. It must be shown in the classroom's open area.
6. The C++ compiler creates a default constructor for the object if a constructor is not
initialized.
1. The constructor has the same name as the class it belongs to.
2. Although it is possible, constructors are typically declared in the class's public section.
However, this is not a must.
3. Because constructors don't return values, they lack a return type.
4. When we create a class object, the constructor is immediately invoked.
5. Overloaded constructors are possible.
6. Declaring a constructor virtual is not permitted.
7. One cannot inherit a constructor.
8. Constructor addresses cannot be referenced to.
9. When allocating memory, the constructor makes implicit calls to the new and delete
operators.
A member function known as a copy constructor initializes an item using another object from
the same class-an in-depth discussion on Copy Constructors.
Every time we specify one or more non-default constructors (with parameters) for a class, we
also need to include a default constructor (without parameters), as the compiler won't supply
one in this circumstance. The best practice is to always declare a default constructor, even
though it is not required.
A reference to an object belonging to the same class is required by the copy constructor.
Sample(Sample &t)
{
id=t.id;
}
~ <class-name>()
{
}
<class-name>: : ~ <class-name>(){}
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is prefixed
with a tilde sign (~).
Let's see an example of constructor and destructor in C++ which is called automatically.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
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
In C++ programming, this is a keyword that refers to the current instance of the class. There
can be 3 main usage of this keyword in C++.
Let's see the example of this keyword in C++ that refers to the fields of current class.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
Output:
C++ static
In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not
required to access the static members. In C++, static can be field, method, constructor, class,
properties, operator and event.
Memory efficient: Now we don't need to create instance for accessing the static members, so
it saves memory. Moreover, it belongs to the type, so it will not get memory each time when
instance is created.
A field which is declared as static is called static field. Unlike instance field which gets memory
each time whenever you create object, there is only one copy of static field created in the
memory. It is shared to all the objects.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name; //data member(also instance variable)
static float rateOfInterest;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
}
void display()
{
cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;
}
};
float Account::rateOfInterest=6.5;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Employee
Account a2=Account(202, "Nakul"); //creating an object of Employee
a1.display();
a2.display();
return 0;
}
Output:
Let's see another example of static keyword in C++ which counts the objects.
#include <iostream>
using namespace std;
class Account {
public:
int accno; //data member (also instance variable)
string name;
static int count;
Account(int accno, string name)
{
this->accno = accno;
this->name = name;
count++;
}
void display()
{
cout<<accno<<" "<<name<<endl;
}
};
int Account::count=0;
int main(void) {
Account a1 =Account(201, "Sanjay"); //creating an object of Account
Account a2=Account(202, "Nakul");
Account a3=Account(203, "Ranjana");
a1.display();
a2.display();
a3.display();
cout<<"Total Objects are: "<<Account::count;
return 0;
}
Output:
201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3
If a function is defined as a friend function in C++, then the protected and private data of a
class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend function.
For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend.
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
n 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.
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.
Let's see the simple example of C++ friend function used to print the length of a box.
#include <iostream>
using namespace std;
class Box
{
private:
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
Let’s see a simple example when the function is friendly to two classes.
#include <iostream>
using namespace std;
class B; // forward declarartion.
class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
Output:
10
In the above example, min() function is friendly to two classes, i.e., the min() function can
access the private members of both the classes A and B.
A friend class can access both private and protected members of the class in which it has been
declared as friend.
#include <iostream>
class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
Output:
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is a friend
of class A. Class B can access the private members of class A.