0% found this document useful (0 votes)
18 views298 pages

C++ Programming

This document outlines a C++ programming course covering syntax, operators, loops, data structures, and the Standard Template Library (STL). It explains the history of C++, its relationship with C, and its applications in game development and embedded programming. The document also provides instructions for setting up an Integrated Development Environment (IDE) and includes examples of basic C++ programs, variable declarations, and operations.

Uploaded by

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

C++ Programming

This document outlines a C++ programming course covering syntax, operators, loops, data structures, and the Standard Template Library (STL). It explains the history of C++, its relationship with C, and its applications in game development and embedded programming. The document also provides instructions for setting up an Integrated Development Environment (IDE) and includes examples of basic C++ programs, variable declarations, and operations.

Uploaded by

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

C++ Programming

The purpose of this course is to provide you with the working knowledge of c++,we will start with
syntax,operators,loops
We will see how to use data structures,and create your own function,we will see how
We will see the objects and template system,so that you can create useful classes and objects

Finally we will cover the unique powerful template library also called stl,which provides you with most
flexible classes available,c++ is powerful programming language and is also the basics of many another
languages
So this knowledge will serve you well even if you are not using c++,so that

What is C++

-C++ is compiled object-oriented language,so what is compiled object-oriented language,is that when
you write,when you write this program you need to convert this program into the executable code,and
this object-oriented language we will see in another chapter what is object-oriented language and how
to use the object-oriented nature of c++

-C++ is the “successor” to c,a procedural language,c was not the object-oriented programming
language,it was a structural language,but when c++ was written,it was written as the super set of c,and
it has the features of object-oriented programming language

-the “++” is called the successor operator in C++,the ++ was added after the c,it indicates that it is the
successor operator in c,so this++ in front of c indicates that it is the successor operator in c

-C was derived from a language called b which was in turn derived from bcpl

-C was developed in the 1970 by Dennis Ritchie of AT&T Bell Labs

-C++ was developed in the early 1980 Bjarne Stroustrup of AT&T Bell Labs

-most of C is a subset Of C++,this if we know c then we will find some of the keyword being used in c++

So why do we want to learn C++

-video games are one of the most common examples of c++ programming,computer games on pc’s are
guaranteed to have some or all od the code written in c++,so if you want to become game developer
you may want to learn c++

-because of the common connection to c,c++ is also commonly used for embedded programs as,large
databases uses c++ sometimes because of the memory management and compatability aspects of the
language,embedded programs are the Program which are written for microprocessor,part of
machines,so if you want to become embedded program developer you may want to learn c++

Integrated Development Environment

-To edit or write the c++ program,you may want to have the software called IDE,an ide is integrated
development environment,an IDE is a full suite for software development,typically they come bundled
with the text editor,the compiler and the debugger,the text editors are the main components as they
offer functionality like syntax highlighting,project management,source control,text editor is where we
will write the code,the compiler is the tool which will convert the software into the executable file,and
debugger will help find the errors if you have any errors in the code

-the IDE is not the compiler but most IDE’s will come with a compiler,we will download the IDE called
code blocks which comes with a compiler called GCC,so we will see how to download this code blocks
and how to write the first c++ program

Day 1:Installing Code Blocks IDE

Download code blocks by the same steps as seen in c programming

Now to create the new project we go to file-new-project-new from template(console application)-click


next-console application-C++-

(console application)

Project title: TestCpp

Folder to create project in:

C:\Users\Programming Knowledge\Documents\Workspace

Project Filename:TestCpp

-Console Application

Create debug configuration

Create release configuration

- Enter

Projects

Workspace

TestCpp

Sources

main.cpp(click on this)
Program

# include <iostream.h>

using namespace std;

int main()

Cout<<”Hello World!”<<endl;

Return 0;

So we will see how to save this program,how to compile this program and how to run this program,the
go to the project,TestCpp is the project,right click on this

Projects

Workspace

TestCpp(right click)-build

Sources

main.cpp

we will run the program,we get the output as this-hello world !,what this program is doing,the program
structure and how it works

Day 2:Understanding C++ Program Structure

The last chapter we have seen how to download and install code blocks IDE in C++,and we have also
seen how to build your first C++ program,we have seen that code blocks has automatically generated
this code for us,in this chapter we will see what the code does and line by line we will see what is the
functions of these,then we will see why to write these lines of code,we will start with the first line,the
first,line starts with the # include and it includes this file <iostream>,so this hash include in c++ is called
the preprocessor directive,what it does is it includes the predefined header file,so see this <iostream> as
a file which is already present in c++ and this file<iostream> is included by writing # include,and
whenever we need to include some file we include it between the < > sign,so the first line is that
include the preprocessor directive which is this,so # include is the preprocessor directive and this
preprocessor directive includes the file <iostream> which is already present in the c++ program,and
when we include this file <iostream> it will include the header file,this header file will contain some
function which will be useful for us to develop the code,the next line using namespace std; says c++ that
we are going to use the standard library for the work,fo example the cout in this Cout<<”Hello
World!”<<endl; belong to the standard library,so what these lines is that we have # include to include
the file,and this line using namespace std; says there is somewhere std class or std namespace,in this
<iostream> file and that,so include this namespace std from this file <iostream> and we are going to use
some function from this namespace,which is present in this <iostream> file to this to execute the
code,and then in the next line this int main() function is declared,so every c++ program has only 1 main
function,this main function tells c++ that from here we need to start the program,so the main is the
main entry point for the c++ program to execute the code,and we see that there is int written here
before the main() function,so this int shows what kind of return it is going to show,so int main() is the
function and functions start with curly brackets and closing curly bracket,so whenever we write the
function,with the curly brackets c++ knows that it is the function,and the function starts with the main
function,the int before main() function is that it is going to return the integer,so we are returning 0 that
is return 0; which is the integer,so the program is compiled and program is run,when the program
reaches here the then the program has comipled and executed,so at the end of the main function we
return 0;and because we are returning the integer,so this int in this int main() will be the integer,we go
to this line Cout<<”Hello World!”<<endl; this line prints the string which is written after the << sign,so
cout is present or cout is the function or cout is the object in this <iostream> file,and the function of this
cout is to output whatever is written after the << sign,so this << sign are called the insertion operator
function so whatever is written in these “ “ will be printed in the terminal when we run the
program,then we have this insertion operator function << and then we have this endl,so endl is
endline,so this line tells the code that,and this is used with cout,so if you write cout then only we can
write endl,so endl will tell the cout function,that we need to change the line after we see this endl

We run the program we see the output as this

Output:

Hello world!

Now for example we have this

Program

# include <iostream.h>

using namespace std;

int main()

{
Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Return 0;

Output:

Hello world

Hello world

Hello world

Hello world

Hello world

Now suppose we will exclude this endl

Program

# include <iostream.h>

using namespace std;

int main()

Cout<<”Hello World!”;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;
Return 0;

Output:

Hello world Hello world

Hello world

Hello world

Hello world

We see here that the line is not closed and another hello world is displayed on the same line,so that is
the thing of endl,so whatever you n eed to print in the next line you will print it in the next line,you can
also go to the next line by writing this line so we write \n so this is written to change the line,this is new
line,this will work the same as this endl

Program

# include <iostream.h>

using namespace std;

int main()

Cout<<”Hello World! \n “;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Return 0;

Output:

Hello world
Hello world

Hello world

Hello world

Hello world

Now one most important thins we will see is the comments,so whenever we write a program we should
write the comments so that other user can understand your program,so now at the top of this line #
include <iostream> which is a preprocessor,we will give slashes which will tell the code that do not do
this do not execute whatever we write after these slashes,we can write this // Program to Show Hello
World

Program

//Program to Show Hello World

# include <iostream.h>

using namespace std;

int main()

Cout<<”Hello World! \n “;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Cout<<”Hello World!”<<endl;

Return 0;

And this line before the preprocessor in slashes will not be executed because,because this slashes tells
the c++ code not to execute this code,these lines after slashes is called comments,and this line we can
use to explain your code to other user whoever is reading your code,this makes your code readable,so
this is one way to write comments,and the another way to write comments is this first of all /*****/
whatever you write in between this will be taken as not to execute example for comments /* main
function*/ in this way you can make your code more readable

Day 3: Understanding Variables

In this chapter we will see what is variable or what are variables.variables are the place holders for some
data,suppose you want to hold so value inside the variable,so this is the program,so how you can
declare a variable

Program

# include <iostream.h>

using namespace std;

int main()

return 0;

Suppose you want to declare a variable of data type integer,declare the data type of variable,then
declare the name of the variable like int x,

Program

# include <iostream.h>

using namespace std;

int main()

{
Int x;

return 0;

Then give a semi colon so this is the declaration of the variable,and another way is that,to declare a
variable is that to initialize the variable with a value,so the way you can initialize the variable by the
value is this,write the variable x ,initialize this x to some value such as 9,x=9; and then give a semi colon

Program

# include <iostream.h>

using namespace std;

int main()

Int x;

x=9;

return 0;

Or you can initialize your variable at the time of declaration here at the top int x=9; and the give the
value of this as 9 so this declaration x=9 and int x=9 is the same there is no difference

Program

# include <iostream.h>

using namespace std;

int main()

Int x=9;

x=9;
return 0;

So you can initialize your variable by any of the ways or you can initialize multiple variables like x or y

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

y=9;

return 0;

So declaring y separately on another line or declaring in to same int x=8,y=9; separated by a comma,the
variable can be initialized the value of this,so you can declare multiple variables like this

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

return 0;

}
There are types of variables,we can define the variables also this,so first variable data type is int which a
basic type of variable,you can declare char which hold a character,you can declare char variables as it
olds a single character so char ch=’ ‘ give single quotes and it can hold only a single character like a or
b or c example char chr=’ a ‘ or char chr=’ b ‘ or char=’ c ‘

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Char chr=’ a ‘;

return 0;

The third of variable is bool we can give bool variable as true or false

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Char chr=’ a ‘;

bool bl=True;

/****Bool bl=False;*****/

return 0;

}
Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Char chr=’ a ‘;

bool bl=1;

/****bool bl=0;****/

return 0;

So we can declare the variable as true or false and 0 and 1 also this,another variable data type is called
float,it will contain a decimal point values,the integer variable will contain only full numbers not decimal
numbers but float variable will contain decimal values

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Char chr=’ a ‘;

bool bl=true;

/****bool bl=0;****/

Float ft=8.32;
double

return 0;

For holding more decimal numbers we can use float variable,we will see how this variable this

Suppose the integer variables holds some values and we want to show the sum of these variables,we
will declare a third variable as sum

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Int sum;

Sum=x+y;

return 0;

What this sum will do it will see what is the value of x that is 8 and what is the value of y that is 9 and
will sum these values and place it in the new variable called sum,so we will print this in sum,that is the
cout<<”the sum is=”<<sum<<endl;

Program

# include <iostream.h>

using namespace std;

int main()

{
Int x=8,y=9;

Int sum;

sum=x+y;

cout<<”the sum is=”<<sum<<endl;

return 0;

We see the output

The sum is =18

Similarly we can use subtraction to hold the values

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Int sum;

sum=x+y;

int subtract=y-x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

return 0;

Output

The sum is=18

The subtraction is=1


So we need to see this basic concepts of variables ,how this is the

Day 4: Basic Calculator

Last chapter we have see the basics of variables and we have seen how to declare the variables,how to
use the variables,in this chapter we will see how we can use these variables more efficiently,we will
make a simple calculator using these variable concepts,if you have learned in the last chapter you will
have seen that if we have to initialize x and y by 8 and 9 then why do we need to write the values of x
and y there like int x=8,y=9; we could have directly written int sum=8+9;in the next line

Program

# include <iostream.h>

using namespace std;

int main()

Int x=8,y=9;

Int sum=8+9;

sum=x+y;

int subtract=y-x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

return 0;

So why do we need to declare these variables if we can give the values directly in the next line,we will
see the case of the simple calculator so we will come to know why we have declared the variables here
in this Int x=8,y=9; without giving the values directly in the next line,so we will see how the user can
enter the values these values will not be same,the user can enter different values in int x=8,y=9;and can
add or subtract,so in the first line we have declared variables x and y int x,y;

Program
# include <iostream.h>

using namespace std;

int main()

Int x,y;

int subtract=y-x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

return 0;

And then in the second line we will write cout<<”Please enter 1st number=”<<endl; and in another line
we will write cin>>x so whatever value the user will enter will be placed in x,cin will display input and
cout will display output the

Program

# include <iostream.h>

using namespace std;

int main()

Int x,y;

cout<<”Please enter 1st number=”<<endl;

cin>>x;

int subtract=y-x;

cout<<”the sum is=”<<sum<<endl;


cout<<”the subtraction is=”<<subtract<<endl;

return 0;

Program

# include <iostream.h>

using namespace std;

int main()

Int x,y;

cout<<”Please enter 1st number=”<<endl;

cin>>x;

cout<<”Please enter 2nd number=”<<endl;

cin>>y;

int subtract=y-x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

return 0;

Similarly we will declare for 2nd number we will hold the variable in y,once we have te 2 values entered
by the user we can subtract it or add it we can write int sum=x+y;we an also divide the number,if we
divide the number the value can be a decimal value or float value this

Program

# include <iostream.h>

using namespace std;


int main()

Int x,y;

cout<<”Please enter 1st number=”<<endl;

cin>>x;

cout<<”Please enter 2nd number=”<<endl;

cin>>y;

int sum=x+y;

int subtract=y-x;

int product=x*y;

float divide=x/y;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

return 0;

We will write float because it can be a decimal value this,so now we will print the values for product and
divide we will print using cout function

Program

# include <iostream.h>

using namespace std;

int main()

Int x,y;

cout<<”Please enter 1st number=”<<endl;

cin>>x;

cout<<”Please enter 2nd number=”<<endl;


cin>>y;

int sum=x+y;

int subtract=y-x;

int product=x*y;

float divide=y/x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

cout<<”the multiplication is=”<<product<<endl;

cout<<”the division is=”<<divide<<endl;

return 0;

Output

Please enter 1 st number=8

Please enter 2nd number=9

The sum is=18

The subtractionis=1

The multiplication is=72

The division is=1

The division is showing only the multiplication not the remainder of the multiplication that is 1,to get the
remainder

Program

# include <iostream.h>
using namespace std;

int main()

Int x,y;

cout<<”Please enter 1st number=”<<endl;

cin>>x;

cout<<”Please enter 2nd number=”<<endl;

cin>>y;

int sum=x+y;

int subtract=y-x;

int product=x*y;

float divide=y/x;

int remainder=y%x;

cout<<”the sum is=”<<sum<<endl;

cout<<”the subtraction is=”<<subtract<<endl;

cout<<”the multiplication is=”<<product<<endl;

cout<<”the division is=”<<divide<<endl;

cout<<”the remainder is=”<<remainder<<endl;

return 0;

So y%x will show the remainder

We see the output

Output

Please enter 1 st number=8


Please enter 2nd number=9

The sum is=18

The subtractionis=1

The multiplication is=72

The division is=1

Remainder is=1

In this way we can see the basic calculator

Day 5:Understanding Basic Arithmetic

In the last chapter we have seen how to create a c++ calculator and we have done the
addition,subtraction,multiplication,division and modulus operator to find the remainder,now in this
chapter we will see more about the basic arithemetic here this,we have now some complicated
calculation we use the rule of PEMDAS,the sequence of the operations will be first Parenthesis then
exponential,then multiplication,then division,then addition and then subtraction

Program

# include <iostream.h>

using namespace std;

int main()

Int x=((10*20)+30)/(40-50);

Cout<<x;

return 0;

So we should always use parenthesis for doing this type of calculations


Day 6: If and Else Statements

If else statements are also called conditional statements,because we use if elase statements to check a
condition,if we want to check the age of a person we can use if else statements to check the age of a
person,declare a variable called age,then I will output some condition I will say cout<<”Please enter the
age”<<endl;

Then I will ask user to enter the age I will say cin>>age

Now in order to check whether the user has entered the right age I will say if

Program

# include <iostream.h>

using namespace std;

int main()

Int age;

cout<<”Please enter the Age”<<endl;

cin>>age;

if (age>20)

Cout<<”The age entered is correct”<<endl;

Return 0;

return 0;

Output
Please enter the age 31

The age entered is correct

If we enter the age less than 20 then I does not catch the other condition

Output

Please enter the age 8

so we need the else statement to catch the condition

Program

# include <iostream.h>

using namespace std;

int main()

Int age;

cout<<”Please enter the Age”<<endl;

cin>>age;

if (age>20)

cout<<”The age entered is correct”<<endl;

else

cout<<”The age entered is not correct”<<endl;

return 0;

}
We can also give the condition

If(age==20)

We are giving == and not = because when we give = we are assigning the value to this,and when we give
== it is that we are checking the equality

Program

# include <iostream.h>

using namespace std;

int main()

Int age;

cout<<”Please enter the Age”<<endl;

cin>>age;

if (age==20)

cout<<”The age entered is correct”<<endl;

else

cout<<”The age entered is not correct”<<endl;

return 0;

Output

Please enter the age 20

The age entered is correct


Also we can check for age>=20 or <=20

Program

# include <iostream.h>

using namespace std;

int main()

Int age;

cout<<”Please enter the Age”<<endl;

cin>>age;

if (age==20)

cout<<”The age entered is correct”<<endl;

else

cout<<”The age entered is not correct”<<endl;

return 0;

We can also give the condition if age==20 || age>20

Program

# include <iostream.h>

using namespace std;

int main()
{

Int age;

cout<<”Please enter the Age”<<endl;

cin>>age;

if (age==20 || age>20)

cout<<”The age entered is correct”<<endl;

else

cout<<”The age entered is not correct”<<endl;

return 0;

So this will print the age entered is correct if the age entered is==20 or the age entered is >20 because
we are executing the or condition we can check the and condition also we declare another variable
height

Program

# include <iostream.h>

using namespace std;

int main()

Int age;

Int height;
cout<<”Please enter the Age”<<endl;

cin>>age;

cout<<”Please enter the height”<<endl;

cin>>height;

if (age==20 && height==100)

cout<<”The age and height entered is correct”<<endl;

else

cout<<”The age and height entered is not correct”<<endl;

return 0;

So in case of && operator both the conditions must be true in order for the if statement to execute and
if any 1 condition is false then the else statement will execute,if both the conditions are true then the if
statement will be executed

Day 7: Switch Statement

In the previous chapter we have seen the if else conditional statements,in this chapter we will see the
switch conditional statements,first we will take a variable called character and name it grade we will
question the user that please enter the grade

Program

# include <iostream.h>

using namespace std;


int main()

Char grade;

cout<<”Please enter the grade”<<endl;

return 0;

We will print cout enter the grade and then the user will enter the grade for which we declare
cin>>grade and on the basis of what the user has entered the grade we will show some message,so lets
see how can we do this by using switch statement,

so let us see what is the declaration of the switch statement we write

switch ()

Program

# include <iostream.h>

using namespace std;

int main()

Char grade;

cout<<”Please enter the grade”<<endl;

cin>>grade;

switch()

}
return 0;

Inside the switch condition we are going to define some cases,first in the switch parenthesis we provide
the condition the condition here is the grade

So we use switch(grade)

So the grade will form the basis of what message is going to be displayed

Because we are evaluating the character which is a grade,char grade,we can write like this

Switch(grade)

Case ’ A ‘

If the user enters character A then give a colon:,then you can print your message

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

Program

# include <iostream.h>

using namespace std;

int main()

Char grade;

cout<<”Please enter the grade”<<endl;


cin>>grade;

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

return 0;

An in the same way on the basis of the grades entered you can define different cases,

but there is an optional break point in switch conditions like this

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

We will copy these conditions 3 or 4 times like this

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

Case ’ B ‘ : cout<<”Very Good”<<endl;

break;

Case ’ C ‘ : cout<<”You Passed”<<endl;

break;

}
Program

# include <iostream.h>

using namespace std;

int main()

Char grade;

cout<<”Please enter the grade”<<endl;

cin>>grade;

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

Case ’ B ‘ : cout<<”Very Good”<<endl;

break;

Case ’ C ‘ : cout<<”You Passed”<<endl;

break;

return 0;

There is one more condition in switch case that does not fulfill the given condition,

what if the user does not provise grades A,B or C and the user enters any other character we can use
default case

if the case is not there as listed above then we will provide the default case output this

Switch(grade)

{
Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

Case ’ B ‘ : cout<<”Very Good”<<endl;

break;

Case ’ C ‘ : cout<<”You Passed”<<endl;

break;

default:

cout<<”Invalid Entry”<<endl;

break;

Program

# include <iostream.h>

using namespace std;

int main()

Char grade;

cout<<”Please enter the grade”<<endl;

cin>>grade;

Switch(grade)

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

Case ’ B ‘ : cout<<”Very Good”<<endl;

break;

Case ’ C ‘ : cout<<”You Passed”<<endl;

break;
default:

cout<<”Invalid Entry”<<endl;

break;

return 0;

So the switch statement sees on the basis of the condition grade,it sees if the user has entered the
grade as A,B or C.and on the basis of the condition it sees what message to print

Output

Please enter the grade A

Excellent

Please enter the grade B

Very Good

Please enter the grade D

Invalid Entry

There is a unique property in switch cases is that this break is optional this we provide case ‘a’

Switch(grade)

Case ‘ a ‘ :

We are not providing any condition or statements,so what happens in this condition if I do not provide
any break after my case

Switch(grade)
{

Case ‘ a ‘ :

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

Case ’ B ‘ : cout<<”Very Good”<<endl;

break;

Case ’ C ‘ : cout<<”You Passed”<<endl;

break;

default:

cout<<”Invalid Entry”<<endl;:

break;

So here if the user enters a and there is break statements after this then the condition goes out of the
loop to the return statements and executes,otherwise if break is not there in this case or condition then
it goes to the next case and then executes the condition here this cout<<”Excellent”

Switch(grade)

Case ‘ a ‘ :

Case ’ A ‘ : cout<<”Excellent”<<endl;

break;

after executing the statement it see that now it finds the break after Case ‘A ‘ so then it goes out of the
condition here in return and executes the statement,so when the user enters ‘ a ‘this code will be
executed cout<<”Excellent” the next case of the switch statement after the Case ‘ a ‘ we see the output

output

Please enter the grade a


Excellent

This Case ‘ A ‘ will be executed because we have not provided the break after the Case ‘ a ‘,so if you
don’t provide the break statement after the condition or the case,it will go and execute the next
condition,and when it sees that it gets the break it goes out of the condition,so we have to see if we
want to give the break or execute the next condition also,so this is the thing to see in case and if you
catch any other exception other than the cases in default so these are the things in switch cases

Day 8: For Loop

we will see here how we can use for loop

the declaration for for loop is like this

Program

# include <iostream>

using namespaces std;

int main()

/// for( init ; condition ; increment)

/// {

/// statement(s) ;

/// }

return 0;

The for condition takes 3 parameters 1 st is the initialization separated by semi colon the second is
condition and the third is the increment and in the curly braces you provide the code you need to
execute in this {

Statement(s);
}

According to the condition,it then goes in the loop,we will declare the for loop which is like this

Program

# include <iostream>

using namespaces std;

int main()

/// for( init ; condition ; increment)

/// {

/// statement(s) ;

/// }

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

return 0;

We can write the increment operator i++ as i=i+1; it goes to the loop after incrementing the
value of I it sees it is less than 10 ,we will output the value of i by cout

Program

# include <iostream>

using namespaces std;

int main()

/// for( init ; condition ; increment)

/// {
/// statement(s) ;

/// }

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

cout<<i<<endl;

return 0;

Output

10

What it does is it goes to the for loop and initializes the value of I by 1,and it goes to the execution of for
loop in cout and prints 1 and the it goes to the for loop and increments the value of I by 1,so for i=1 it
prints it and then increments the value of i by 1 and then once again goes to the for loop,now it sees if
condition i=2 is 2<10 so the condition is true so it prints the value of i as 2 and again increments the
value of i by 1 so now i is 3 so it goes again to the for loop and checks whether i<=10 that is if 3 is less
than 10 the condition is true so it prints the value of i as 3 and again increments the value of i by 1 now
the value of is 3,it goes to the for loop and checks the condition is i<10,that is is 3<10 the condition is
true so it prints the value of i as 3 and then increments the value the value of i is now 4,so it again goes
to the for loop and checks whether i<10,that is if 4<10,the condition is true so it prints the value of I as 4
it then increments the value the value of i is now 5,it again goes to the for loop and checks whether
i<10,that is if 5<10 the condition is true so it prints the value of i as 5 similarly it prints the value of I till
9,when i=9,it again goes to the for loop and checks the condition is i<10,that is if 9<10,the condition is
true so it prints the value of i as 9 and then increments the value of I now the value of i is 10,now it
prints 10 when the value is incremented now the value of I is more than 10 so the condition is false so it
breaks out of the loop and returns the output statement

similarly you can initialize the value of i by any value,and you can decrement and increment the
value of I by any number,fo example you can see this program

Program

# include <iostream>

using namespaces std;

int main()

/// for( init ; condition ; increment)

/// {

/// statement(s) ;

/// }

for ( int i=8 ; i<=90 ; i+=5)

cout<<i<<endl;

return 0;

for the decrement you can see the example

Program

# include <iostream>

using namespaces std;

int main()

/// for( init ; condition ; increment)


/// {

/// statement(s) ;

/// }

for ( int i=10 ; i>=1 ; i--)

cout<<i<<endl;

return 0;

Output

10

In this case it first i=10 so it prints the value of i as 10 then it decrements the value of i by 1,so the value
of i is 9 now so it again checks the condition if i>=1 that is if 9>=1,the condition is true so it prints the
value of i as 9,and decrements the value of I by 1 so the value of I is now 8 now it again goes to the for
loop and checks the condition,it i>=1,that is if 8>=1,the condition is true so it prints the value of i as 8
and then decrements the value of I by 1 so the value of i is now 7 so it goes to the for loop and checks
whether i is less than 7 that is if 7>=1,the condition is true so it prints the value of i as 7,and then
decrements the value of I by 1 so the value of I is now 6,so it goes to the for loop and checks the
condition whether i>=1,that is if 6>=1,the condition is true so it prints the value of i as 6,and decrements
the value of I by 1 so now the value of i is 5,so it goes to the for loop and checks the condition if
i>=1,that is if 5>=1,the condition is true,so it prints the value of I as 5 similarly it prints the value of I till
1,when i=1 it goes to the for loop and checks the condition whether i>=1,that is if 1>=1 the condition is
true so it prints the value of I as 1 and then decrements the value of I by 1,in this case now the condition
is not fullfilled so it breaks out of the loop and returns the output statement

Day 9:Increment,Decrement and Assignment Operators/Functions

We will first see how assignment operator works,we will take an integer x and assign it a value this

Program

#include<iostream>

Using namespace standard;

Int main()

Int x=40;

x=x+5;

cout<<x<<endl;

return 0;

so what this will do is that it will take the value of x as 40 and add 5 to it and then place the value of
added value in x,we see the output

output

x=45

now instead of adding using this x 2 times we can write x+=5 which is the same as x=x+5;

Program

#include<iostream>

using namespace std;


Int main()

Int x=40;

x+=5;

cout<<x<<endl;

return 0;

it will add 5 to the variable x and then place it in the added value of the variable x

now in place of x+=5; we can use other assignment operators as this

x-=5; x*=5; x/=5 and x%=5 and see the results suppose you have int x=80 and you want to add 1 to it
you can write x++; after the int x=80; declaration so it will show result 81,now let us see how we can use
it in 2 different ways,we will see increment operator in this program

Program

#include<iostream>

using namespace std;

Int main()

Int x=80;

cout<<x++<<endl;

cout<<x<<endl

return 0;

Output

80

81

We get the value of 80 first even though we have incremented the value of x by 1 is because in the first
cout statement we have written x++ ,this ++ is after the x so it prints the value of x first for the
statement without incrementing that is 80 and then increments the value of x by 1 and prints it for the
second cout statement that is value of x for second c out statement is 81,if we need to print the
incremented value of x then we have to use ++x,so that it increments the value of x first and then it
prints the value of x,we can see this example in this program

Program

#include<iostream>

using namespace std;

Int main()

Int x=80;

cout<<++x<<endl;

cout<<x<<endl

return 0;

Output

81

81

We can see example for the decrement operator program

Program

#include<iostream>

using namespace std;

Int main()

Int x=80;

cout<<x--<<endl;

cout<<x<<endl

return 0;
}

Output

80

79

Program

#include<iostream>

using namespace std;

Int main()

Int x=80;

cout<<--x<<endl;

cout<<x<<endl

return 0;

Output

79

79

So these are the basics about assignment operators functions

Day 10: While Loops

While loop is another type of loop other than for loop which we have seen in previous chapters
Program

#include<iostream>

using namespace std;

Int main()

while()

return 0;

The syntax of while loop is seen from this program,what the while loop does is it loops for conditions
until and until and unless the conditions are fulfilled,we will take this int x=1 and while(x<=5)

Program

#include<iostream>

using namespace std;

Int main()

Int x=1;

while(x<=5)

cout<<x<<endl;

return 0;

We see that it will print 1 for the condition x<=5,let us give conditions to the program
Program

#include<iostream>

using namespace std;

Int main()

Int x=1;

while(x<=5)

x++;

cout<<x<<endl;

return 0;

Output

So what is happening here is that first the value of x is 1 it goes to the while loop and checks the
condition whether x<=5,that is if 1<=5,the condition is true so it goes to the increment operator x++ and
increments the value of x by 1 so now the value of x is 2 and then goes to the next statement of cout
and prints the value of x so it prints the value of x as 2,now it again goes to the while loop and checks
the condition whether x<=5 that is if 2<=5,the contition is true so it goes to the increment operator x++
and increments the value of x by 1,so now the value of x is 3 and then it goes to the next statement of
cout and prints the value of x so it prints the value of x as 3,similarly it prints the value of 4 and 5,when
the value of x is 5 it again goes to the while loop and checks the condition whether x<=5,that is if
5<=5,the condition is true so it goes to the increment operator and increments the value of x by 1 and
then it goes to the next statement of cout and prints the value of x now the value of x is more than 5 so
the condition is not fulfilled so it break out of the while loop and returs the output statement
Program

#include<iostream>

using namespace std;

Int main()

Int x=1;

Int number=0;

Int sum=0;

while(x<=5)

cout<<”input any value”<<endl;

cin>>number;

sum=sum+number;

return 0;

Here we will take input from the user by cin and store the number in int number=0, and then we will
sum the numbers,it will make the sum until it fulfills the condition in the while loop while x<=5

Program

#include<iostream>

using namespace std;

Int main()

Int x=1;

Int number=0;

Int sum=0;
while(x<=5)

cout<<”input any value”<<endl;

cin>>number;

sum=sum+number;

x++

cout<<”The sum is=”<<sum<<endl;

return 0;

Output

Input any value 10

Input any value 20

Input any value 30

Input any value 40

Input any value 50

The sum=150

Day 12:Do While Loops

In while loop if the condition is false it will not execute,but the do while loop will execute at least once
even if the condition is true,this program we have seen in the last chapter

Program

#include<iostream>
using namespace std;

Int main()

Int x=1;

Int number=0;

Int sum=0;

while(x<=5)

cout<<”input any value”<<endl;

cin>>number;

sum=sum+number;

x++

cout<<”The sum is=”<<sum<<endl;

return 0;

In the program we have initialized x by 1 number by 0 and sum by 0 and put the condition for the while
loop if x<=5,if x is <=5 ask the user to enter any number,and once the condition is fulfilled that is user
has entered the value 5 times the we wil print the sum

If we put the condition for the while loop as this while(x<1) the condition is not true,so I will not execute

Program

#include<iostream>

using namespace std;

Int main()
{

Int x=1;

Int number=0;

Int sum=0;

while(x<1)

cout<<”input any value”<<endl;

cin>>number;

sum=sum+number;

x++

cout<<”The sum is=”<<sum<<endl;

return 0;

Output

The sum=0

The program for do while loop is this

Program

#include<iostream>

using namespace std;

Int main()

Int x=1;

Int number=0;
Int sum=0;

do

cout<<”input any value”<<endl;

cin>>number;

sum=sum+number;

x++

} while(x<1);

cout<<”The sum is=”<<sum<<endl;

return 0;

Output

Input any value 31

The sum=31

So even if the condition if false we have initialized x as 1 but in the while loop we give the condition x<1
so the condition is false ,and even though the condition is false do while loop will execute atleast once
this,now you may see that where is the do while loop used ,and if the condition is false why do we need
to execute the statement,we will see this by an example

Program

#include<iostream>
#include<cmath>

using namespace std;

int main()
{
//-------defining variables and initializing them-------------
double num1,num2;
char operation,redo;
//--------Printing my name on screen----------------
cout<<"Welcome to the calculater program v.1.0 written by Your Name"<<endl;
cout<<"***************************************************************"<<endl;
cout<<endl<<endl<<endl;
//--here do loop is used so that the program can be used more then one time
//without exiting the run screen---------------------------
do
{
//----receiving the variables from input--------------
cout<<" Please enter an operation which you like to calculate (+,-,*,/,s)";
cout<<"[s stands for swap]:";
cin>>operation ;
cout<<endl<<endl;
cout<<" Please enter two numbers to apply your requested operation(";
cout<<operation<<"):"<<endl<<"1st num:";
cin>>num1;
cout<<"2nd num:" ;
cin>>num2;
cout<<endl;
//---used switch function so thet the operater can be decided------------
switch (operation)
{
//------calculating the requested equation for inputs-------------
//-------at the same time printing the results on screen-----------
case'+':
cout<<"The addition of two numbers ("<<num1<<","<<num2<<"):";
cout<<num1+num2<<endl;
break;
case'-':
cout<<"The substraction of two numbers ("<<num1<<","<<num2<<"):";
cout<<num1-num2<<endl;
break;
case'*':
cout<<"The multiplication of two numbers ("<<num1<<","<<num2<<"):";
cout<<num1*num2<<endl;
break;
case'/':
cout<<"The division of two numbers ("<<num1<<","<<num2<<"):";
if(num2==0)
{
cout<<"not valid"<<endl;
}
cout<<(num1/num2)<<endl;
break;
case's':
cout<<"The swap of two numbers ("<<num1<<","<<num2<<"):";
swap(num1,num2);
cout<<"1stnumber="<<num1<<"and 2nd number="<<num2<<endl<<endl;
break;
default:
cout<<"unknown command"<<endl;

}
//----now once again the program will ask the user if want to continue or not
cout<<"enter y or Y to continue:";
cin>>redo;
cout<<endl<<endl;
}
while(redo=='y'||redo=='Y');

system("pause");
return 0;

Output

Welcome to the calculater program v.1.0 written by Your Name

***************************************************************"

Please enter an operation which you like to calculate (+,-,*,/,s) <<"[s stands for swap]

Please enter two numbers to apply your requested operation

1st num:2344

2nd num:2345

The addition of two numbers(2344+2345):4789

Enter y or Y to continue:y
When you enter y or Y do while loop comes into action,it will again ask to enter the operation and two
numbers after entering and getting the output when it asks for y or Y give any other character d,the it
will come out of the loop

Day 12: Functions in C++

Function is a block of code which executes something,a function should perform a specific task that is
assigned to it,and normally when you write a code it is made up of too many lines of code,so when other
programmer when try to read your program,I becomes difficult for the other person to understand the
program,so functions reduce the size of your program so that the program becomes understandable,so
what the convention generally is that,whatever code is writing repeating more than once in your
program,just wrap it in the function,so whatever code is happening again and again that is,so we will see
how to declare a function,we have seen in the first chapters,that main is also a function,we can define
user defined function,so what we can do is that we can either go above the main function and declare
the function so when you define a function,you have to give a return type,we will give void,void is that
we are not returning anything,we see the program

Program

# include<iostream>

using namespace std;

void

int main()

Return 0;

Here we have written integer main() which is returning 0 which is an integer so int main();

Program

# include<iostream>

using namespace std;

void myFirst Function()

{
}

int main()

Return 0;

Void is the return type,myFirstFunction is the name of the function and after that we give the
parenthesis,and whetever you write in this function will be executed,when you use this function inside
your main function,fo example we want to print the statement,we want to print this function in the
main function,so what we will do is that we will copy this function like this,you don’t need to copy the
return type,copy the name of the function myFirstFunction inside the main function

Program

# include<iostream>

using namespace std;

void myFirstFunction()

cout<<We are in a function”<<endl;

int main()

myFirstFunction();

return 0;

Give the semi colon after the function,So this is how you can a function inside a main function

Output
We are in a function

This statement we are in a function is written inside this function void myFirstFunction(),and we are
calling this function myFirstFunction(); inside the main function,so main goes to this function
myFirstFunction which is there in this function above that is void myFirstFunction() and the cout
statement for this is we are in a function so it prints the statement,so whenever you need to execute a
similar kind of program you can use a function,so any number of statements you need to execute,you
need to call the function name inside the main function and then it will go to that function outside the
main and execute the statements any number of times,as many times you call the function inside the
main()

Program

# include<iostream>

using namespace std;

void myFirstFunction()

cout<<We are in a function”<<endl;

int main()

myFirstFunction();

myFirstFunction();

myFirstFunction();

myFirstFunction();

return 0;

Output

We are in a function

We are in a function
We are in a function

We are in a function

This is one kind of declaration of function or uses of function

There are other kinds of function declaration,you can give your declaration of function below the main
function

Program

# include<iostream>

using namespace std;

int main()

myFirstFunction();

return 0;

void myFirstFunction()

cout<<We are in a function”<<endl;

But when we see the output I gives the error,that is when it executes the program it executes from top
to below,but the function we have declared with cout statements after the main function,so it does not
find the function at the top while executing the program,so you need to prototype the function above
the main function,that is taking the return type and taking the function name and copy it to above the
main function separated by a semi colon,and this type of declaration of the function above the main
function is called prototyping the function

Program

# include<iostream>

using namespace std;


void myFirstFunction();

int main()

myFirstFunction();

return 0;

void myFirstFunction()

cout<<We are in a function”<<endl;

So when the compiling is done the compiler knows that iostream is included,namespace std is
included ,the void myFirstFunction(); is prototyped above the main function and it need to be included
from the function declaration with cout statements declared after the main function, so when I comes
here this

int main()

myFirstFunction();

return 0;

I see that it knows thyis function and this function is to be executed so this is prototyping of a
function,you can give the definition of the function with the cout statements after the main function and
the declaration of the function above the main function,so this is basics of functions,there are other
type of functions that takes parameters or returns parameters

Day 13:Passing Parameters and Arguments in Functions

In this chapter we will see how to pass parameters to a function,whatever variables you have will pass it
to the function,for example we need a function to add 2 values,whatever the user gives,so I will declare
a function here this as we have seen in the last chapter,we will give a return type that is void,we will give
the name of the function we need the the addition of numbers so we will give the function name as sum
Program

# include<iostream>

using namespace std;

void sum()

int main()

return 0;

Will pass the parameters in the parenthesis of the function void sum(),for this we can give the data type
of the variable or you need to declare the data type of the variable,suppose we want to pass the data
type as integer,

void sum( int )

and then we will give the name of the variable

void sum( int firstNumber , )

and we will pass the second parameter as this,the data type and name of the variable

void sum( int firstNumber , int secondNumber )

in this way you can pass two parameters to the function,inside this sum function

Program

# include<iostream>

using namespace std;

void sum( int firstNumber , int secondNumber )

}
int main()

return 0;

We see here that the first variable is firstNumber and the second variable is secondNumber and the data
type for both the variables is int,this data type can be other thing like char,float,double etc,so in this
function we need to make the sum of these numbers what we need to do is that,we need to print the
sum of these numbers so we will give

Program

# include<iostream>

using namespace std;

void sum( int firstNumber , int secondNumber )

Cout<<”The sum of the given numbers is=”<<(first number+second number)<<endl;

int main()

return 0;

So what it will do is that it will take the sum of the two numbers and print the sum,if you want to declare
the function inside the main function,then you need to call the name of the function sum we don’t need
the return type only the name of the function and then the parenthesis and inside the parenthesis we
pass two numbers,this function void sum( int firstNumber , int secondNumber ) can take two
parameters firstNumber and secondNumber,we will give two numbers as parameters in the sum
function

Program

# include<iostream>
using namespace std;

void sum( int firstNumber , int secondNumber )

Cout<<”The sum of the given numbers is=”<<(first number+second number)<<endl;

int main()

Sum(476,587);

return 0;

What this function does when it comes to main is that it sees that it has this function

Sum(476,587);

These two numbers will be passed here in the firstNumber and secondNumber in the, void sum( int
firstNumber , int secondNumber )

And in this first number+second number in this cout<<”The sum of the given numbers is=”<<(first
number+second number)<<endl; and will print out the sum from cout statement

Program

# include<iostream>

using namespace std;

void sum( int firstNumber , int secondNumber )

Cout<<”The sum of the given numbers is=”<<(first number+second number)<<endl;

int main()

{
Int a,b;

Cout<<”Please enter two numbers”<<endl;

Cin>>a;

Cin>>b;

Sum(a,b);

return 0;

Output

Please enter two numbers

13

Sum=16

What this function does when it comes to main then it asks for the two numbers

Sum(a,b); and then stores the numbers in a and b

These two numbers will be passed here in the firstNumber and secondNumber in the, void sum( int
firstNumber , int secondNumber )

And in this first number+second number in this cout<<”The sum of the given numbers is=”<<(first
number+second number)<<endl; and will print out the sum from cout statement the sum is 16

Suppose you want to declare the functions multiple times after the main you can do this and it will print
the statements from the function above the main again and again for different two values entered

We see the program

Program

# include<iostream>

using namespace std;

void sum( int firstNumber , int secondNumber )

Cout<<”The sum of the given numbers is=”<<(first number+second number)<<endl;

}
int main()

Int a,b;

Cout<<”Please enter two numbers”<<endl;

Cin>>a;

Cin>>b;

Sum(a,b);

Int x,y;

Cout<<”Please enter two numbers”<<endl;

Cin>x;

Cin>>y;

Sum(x,y);

return 0;

Please enter two numbers

13

Sum=16

Please enter two numbers

80

Sum 81
So this is function so any number of functions can declared inside main.any program you want to
execute program repetedly make it a function above the main function with c out statements and
declare the function the number of times you want to display declaring after the main function

Day 14: Return Values in Functions

We will see how to declare and use a function which returns a value,by now we have seen how to
declare a function,this time we are going to make the sum of two numbers,we will take a function that
adds two numbers and returns the sum in the main,in this first we have to see what we have to return,in
the last chapter we were returning void,but this time we want to return a value,it is not void not null
value but a number,there will be a value whatever data type you want to return,write in the declaration
then write the name of the declaration,and once when you want

Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

return

Int main()

return 0;

So this function has to return a value in order to execute the function int sum( int firstNumber , int
secondNumber) so we will return a value to execute this function, since this function is returning a value
that is int in this case so instead of void we will write return for whatever we want to return,so what we
will do is we will take the sum of these numbers firstNumber and secondNumber and return the sum
here this in int of int sum function so for that we will declare a third variable int result=0,this is
initialized,we have initialized it to 0 so that there is no other value in this variable only the sum which is
needed will be stored in the variable
Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

Return result;

Int main()

return 0;

Here what is this is we will pass two parameters in the function and store the sum of firstNumber and
secondNumber there in the function int sum into result,here result=firstNumber+secondNumber;we
have declared int as result,now because this parameter result hold the result and this function int sum
gives int for return so we will return result,we have declared return result because result is an int and
the function int sum has return type int so it is expecting an integer for return so we write return
result,we are returning result because result is int which is fulfilling int sum function return type,we can
call a function inside the main function,suppose we want to declare one more variable like int multiply;
inside the main function

Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

Return result;

}
Int main()

Int multiply;

return 0;

After declaring multiply I will call this function sum here this after int multiply and I will pass two
parameters first number and second number,for example I pass first intefer 254 and second integer 458

Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

Return result;

Int main()

Int multiply=2;

Sum(254,458)

return 0;

And because we are returning a value here this what we can do is that,so lets initialize the multiple
variable by 2,i will declare 1 more variable called int main result will contain the result,so what I am
going to do is that main result=multiple variable and then we will multiple the multiply variable with
sum(254,458)

Program
# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

Return result;

Int main()

Int multiply=2;

Int mainResult;

/*****mainResult=multiply*sum(254,458);******/

return 0;

We will take a basic example than this what we will do is we will print cout<<”the result
is”<sum(254,458);we will pass the two parameters that is the two numbers in sum as 254 and 458

Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

return result;

}
Int main()

Int multiply=2;

Int mainResult;

/*****mainResult=multiply*sum(254,458);******/

cout<<”the result is”<sum(254,458)<<endl;

return 0;

So what this will do is the this cout will call this function int sum( int firstNumber , int secondNumber) it
will add these two values and then it will return the result here this, in result return result;the return
result is that,so the return result will be printed here this cout<<”the result is”<sum(254,458)<<endl; so
what this function is doing is that it is taking these two values of the first number and the second
number making the sum of the two values and then returning the result,and the result it is returning as
an integer here this int sum( int firstNumber , int secondNumber),this result it holds as an integer,so
whenever you call this function it will return you the sum,so now I want to multiply whatever this
function is returning to my variable multiply so now we can use this
/*****mainResult=multiply*sum(254,458);******/

Program

# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Int main()

Int multiply=2;

Int mainResult;
mainResult=multiply*sum(254,458);

cout<<”the result is”<sum(254,458)<<endl;

return 0;

We write this mainResult=multiply*sum(254,458); and because this function sum(254,458);is returning


an integer we can use it as a variable so this sum(254,458) we can use it as an integer because we
returning this as an integer which is sum of these two values result=first number+second number.we
can multiply this function sum() by another integer and we can store the variable in this mainResult so in
the cout statement we can print this in cout<<”the main result is”<<mainResult<<endl; which is the
product of the sum of the integers and the multiply variable

We see the output

The mainResult is 1418

So what it is doing is first it makes the sum of these integers 254 and 458 and then it multiplies the sum
by 2 multiply variable and then it stores this multiplication in this variable mainResult and we are calling
this variable mainResult here in this cout ,cout<<”the main result is”<<mainResult<<endl;so it will
display the result in this form as shown in the console,so whenever you are returning a variable here this
result

Int result=0;

Result=firstNumber+secondNumber;

return result;

you have to give the data type same as that declared in the function int sum( int firstNumber , int
secondNumber),if the function is declared as double you have to give the data type as double you have
to return double value in the result and whatever this function int sum( int firstNumber , int
secondNumber) is returning you can multiply this function sum(254,458) or add this function to the
another variable because it is returning a value this,in our case it is returning an integer,so that is how
you can return value using functions

Day 15:Default Function Parameter

In the last chapter we have seen that how to declare a variable that can return a value,so the function
takes two parameters and then returns a result,we want to print the sum of variables and then

Program
# include<iostream>

using namespace std;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Int main()

cout<sum(354,654);

return 0;

We are returning the sum(354,654) as an integer here this so the sum is an integer so it prints the
sum,in this chapter we will see more important thing as default arguments or default parameters so
what is this that default arguments or default parameters,you can initialize your function parameters
with a value result=firstNumber+secondNumber suppose we have written function to make the sum of
these two values int sum( int firstNumber , int secondNumber) the first number and second number we
can initialize these parameters by a value like ,int sum( int firstNumber=20 , int secondNumber=10)

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

}
Int main()

cout<sum(354,654);

return 0;

So this is called default argument declaration,what this is that we have initialized the parameter with a
default value here this int firstNumber=20,so now you can call this function this cout<sum(354,654);like
this without passing any parameter cout<<sum();

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Int main()

cout<sum();

return 0;

Because what happens is that when it sees this function cout<sum(); it goes to this function int sum( int
firstNumber=20 , int secondNumber=10) and sees that we already have these parameters or the values
of these two parameters,we see the output

Output

Sum= 30
So it gives the sum as 30 even though we have not given any parameters to the cout<sum(); so this is
how you can initialize your function with default values,now we will see another case how to overwrite
the values of the parameters,suppose the first parameter and second parameters are initialized 20 and
10 in the function and we want to overwrite these values we can do this like this cout<<sum(134);

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Int main()

cout<sum(134);

return 0;

Output

144

So what is happening is first of all we see that in this declaration cout<sum(!34);which parameters it is
overwriting in the above function the first parameter or the second parameter,so in c++ how it executes
is that it goes from first the starting parameter and then the next parameter so in this function int
sum( int firstNumber=20 , int secondNumber=10) we see that the it see that the starting parameter or
first parameter is firstNumber so it assigns the value to the first parameter so cout<<sum(134) in this
134 is assigned to the firstNumber since second parameter is not declared it overwrites the firstnumber
by 134 and takes the previous value of second number as 10 and returns the value of the sum as
144,now you pass the second parameter in this function,cout<<sum(134,234) so now 20 will be
overwritten by 134 for the first number and 10 will be overwritten by 234 fro the second number and it
will return the result as 369,so we see the output,for this program

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Int main()

cout<sum(134,234);

return 0;

Output

369

So this default function parameter,so now if you are prototyping your function,this we have seen in the
previus chapters,if you are using this function

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

}
After your main like this

Program

# include<iostream>

using namespace std;

int main()

cout<sum(134,234);

return 0;

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

Now so you need to prototype your function here above the main,so if you are using function
prototyping,copy this int sum( int firstNumber=20 , int secondNumber=10) above the main a give semi
colon

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10);

int main()

cout<sum(134,234);

return 0;
}

int sum( int firstNumber=20 , int secondNumber=10)

Int result=0;

Result=firstNumber+secondNumber;

return result;

And when you do function declaration you don’t need to initialize the function here this in the function
after the main,so we see the program

Program

# include<iostream>

using namespace std;

int sum( int firstNumber=20 , int secondNumber=10);

int main()

cout<sum(134,234);

return 0;

int sum( int firstNumber , int secondNumber)

Int result=0;

Result=firstNumber+secondNumber;

return result;

}
You need to initialize the default values of the parameters in the function prototype not in the function
declaration,so if you are declaring function after the main then initialize these default values of the
parameters in the function prototype above the main,so the program will work,we see the output

Output

Sum =369

Day 16:Variable Scope and Unary Scope Resolution Operator Function

In the prevous chapters we were seeing how functions work and in this chapter we will see how variable
scope works in c++ and we will see how unary scope resolution operator function works in c++,suppose
you have a function void printMe(),it is a random function we are writing

Program

# include<iostream>

using namespace std;

void printMe()

int main()

return 0;

And what this function does is it prints a thing

Program

# include<iostream>

using namespace std;

void printMe()

Cout<<”Print a thing”<<endl;
}

int main()

return 0;

You can declare a variable which is local to the function and you can declare a variable which is global to
the function,suppose we declare a variable int myVariable=30 in this

Program

# include<iostream>

using namespace std;

void printMe()

int myVariable=30;

cout<<”Print a thing”<<endl;

int main()

return 0;

Suppose we want to print this myVariable in here this also after the main in cout<<myVariable;

Program

# include<iostream>

using namespace std;


void printMe()

int myVariable=30;

cout<<”Print a thing”<<endl;

int main()

cout<<myVariable;

return 0;

Will this work it shows a error,that myVariable was declared in the scope,so what is this is that
whenever you declare a Variable inside a function,which is called a local declaration or local scope of
that variable

void printMe()

int myVariable=30;

cout<<”Print a thing”<<endl;

And whenever you declare a variable inside a function it can be void printMe function or int main()
function,it will be usable inside that function only,so you can not use myVariable outside this function
void printMe(),so this is called local scope or local declaration of the variable,so if you want to use the
same variable in this function and this function you can declare the variable as global

Program

# include<iostream>

using namespace std;

int myVariable=20;
void printMe()

myVariable=30;

cout<<”Print a thing”<<endl;

int main()

cout<<myVariable;

return 0;

Now because we have declared our function outside this function void printMe and outside the main
function,this is called a global declaration which is global to void printMe() function and the main()
function,so this variable myVariable can be used inside this function void printMe() also and int main()
function also this,so you can declare your function as global variable if you want to use the same
function in the main and another functions and if you want to use the function in a function itself then
you can declare the function locally

Now let us see what is unary scope resolution operator function,now let us suppose you have declared
int myVariable=20 globally and also you have declared and initialized int myVariable=10 after the main
function also this

Program

# include<iostream>

using namespace std;

int myVariable=20;

void printMe()

myVariable=30;

cout<<”Print a thing”<<endl;

}
int main()

Int myVariable=10;

cout<<myVariable;

return 0;

Then how the program will know that the myVariable that you are printing is global variable or local
variable

Program

# include<iostream>

using namespace std;

int myVariable=20;

int main()

Int myVariable=10;

cout<<myVariable;

return 0;

We see the output

Output

10

So it is showing the value of myVariable as 10,so whenever you declare a variable with the same name
which will be preffered,so the local variable will be preffered the most recent value in the function that
you have declared will be preffered,this is the most recent value of the local value
int main()

Int myVariable=10;

So local value will be preffered over global variable,so what if you want to print the global variable that
is 20 and not 10 so how you can print this,so in order to print this global variable you need to use this
unary scope resolution operator function,and what is this unary scope resolution operator,you need to
give two colons before the myVariable in cout that is,cout<<: : myVariable; and this two colons are
called unary scope resolution operator function and it tells the c++ program that this myVariable after
the two colons is a global variable

Program

# include<iostream>

using namespace std;

int myVariable=20;

int main()

Int myVariable=10;

cout<< : : myVariable;

return 0;

And not the local variable so in this way you distinguish between a global and a local variable this,so
when you and if you have two colons before myVariable in the cout then this myVariable will be taken
as global variable,and if you don’t have two colons before the myVariable in the cout then this
myVariable will be taken as local variable

Day 17:Function Overloading


In this chapter we will how to use function overloading and what is the logic of using function
overloading,so we will take an example that we have used in our earlier programs,we will make a
function to add two numbers we not return anything we will take a function to add two numbers

Program

# include<iostream>

using namespace std;

void sum()

int main()

return 0;

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

int main()

return 0;

}
We will call this function sum after the main function and then we can add two numbers

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

int main()

Sum(265,675);

return 0;

We see the output

Output

Sum=940

So what happens when you want to add two decimal numbers or two float numbers,we see the
program

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;


}

int main()

Sum(265.758,675.76);

return 0;

We see the output

Output

940

This is not correct because it is not showing the decimal values,so the concept of function overloading
comes here this,so according to function overloading you can define a function with a function name
two times or more that two times but with different arguments or different return type for example this
function void sum(int firstNumber,int secondNumber) is adding two integer,we can copy the function
after this function void sum and change the return type of the parameter to float

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

void sum(float firstNumber,float secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

}
int main()

Sum(265.758,675.76);

return 0;

But now compiling the program shows error,the program does not know whether the function is
initialized by integer values or float values so what you can do is that you can declare two float variables
as float a=265.758 ,b=675.76; and the sum(a,b) the arguments for sum will be a ,b so now we have
implicitely specified that this a and b is a float value

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

void sum(float firstNumber,float secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

int main()

float a=265.758,b=675.76;

sum(265.758,675.76);

return 0;

}
So now the program knows that there are two functions that are passed inside the sum function as a
and b,I will go to these functions and see that which parameter will take the float

Program

# include<iostream>

using namespace std;

void sum(int firstNumber,int secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

void sum(float firstNumber,float secondNumber)

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

int main()

float a=265.758,b=675.76;

sum(a,b);

int x=465, y=465;

sum(x,y)

return 0;

So now we have passed both integer and float values so we have passed the parameters a,b x and y in
the sum functions this will execute accordingly with respect to which function is integer and which
function is float here this

void sum(int firstNumber,int secondNumber)


{

Cout<<”sum of integers is =”<<firstNumber+secondNumber<<endl;

void sum(float firstNumber,float secondNumber)

Cout<<”sum of float is =”<<firstNumber+secondNumber<<endl;

Output

Sum of float is =942.75

Sum of integers is=940

This is how you can use function overloading you can declare a function with the same name more that
two times or more that once,and you can pass different kinds of parameters inside this function and you
can return different kind of parameters with this function,so whenever you pass float it will use the float
function and whenever you pass integer it will use the integer function,so in thsin way you can use
multiple functions with the same name to use them differently

Day 18: Arrays in C++

We will see here what are arrays in c++ and how we can declare arrays in c++,we sill see what is an
array,an array is a variable,which can contain more that 1 values or as the name suggest it can contain
an array of values,now lets see how we can declare an array,the declaration is same as a variable
declaration for example int myArray[ ] then you have to give how many elaments your array will
contain,so in this square bracket you have to define how many elements the array will contain,so then
the c++ program will know that we have assigned of that we have reserved 3 element array in the
memory,we have assigned 3 spaces in the memory,now in order to initialize arrays or initialize arrays
with values what you can do is that,you can initialize array in different forms but the most basic form is
called array initializer list,we will see how you can initialize array with array initializer list we see the
program
Program

# include<iostream>

using namespace std;

int main(){

int myArray[3]

return 0;

Program

# include<iostream>

using namespace std;

int main(){

int myArray[3]={ 38,45,66}

return 0;

Suppose in the curly braces we give the values of the array elements as 38,45,66,this is that the array
contains 3 elements and the values of the arrays are 38,45,66,so these 3 values {38,45,66} are called the
elements of the array and there is a thing called index of an array that is the position of the element in
the array,and the position of the element in the array starts from 0 and not 1 ,so the index of this
element 38 is 0 the index of this element 45 is 1 and the index of this element 66 is 2,now in order to
print array what you can do is that you can print cout so now in ordewr to access the value of the
array,copy the name of the array give the square bracket that is cout<<myArray[ ] and give the indewx
of the value you want to print that is cout<<myArray[ 0 ];

Program

# include<iostream>

using namespace std;

int main(){
int myArray[3]={ 38,45,66}

cout<<myArray[ 0 ];

return 0;

So here we have given index 0 so we want to access the element 0 from the array and from here this
int myArray[3]={ 38,45,66} we know that the 0 th element with index 0 is 36

Output

36

Program

# include<iostream>

using namespace std;

int main(){

int myArray[3]={ 38,45,66}

cout<<myArray[ 2 ];

return 0;

Output

66

so we will compile the program now in order to assign values to array,in a different way what you can do
is that,this way you can also initialize the element of an array

Program

# include<iostream>

using namespace std;


int main(){

int myArray[3];

myArray[ 0 ]=38

cout<<myArray[ 2 ];

return 0;

This is that assign element at index 0 the value 38,in the same way you can assign other values of the
elements of the array

Program

# include<iostream>

using namespace std;

int main(){

int myArray[3];

myArray[ 0 ]=38;

myArray[ 1 ]=45;

myArray[ 2 ]=66;

cout<<myArray[ 2 ];

return 0;

We see the output in will execute the same way

Output

66
Now if your array will contain more elements like 10 elements or 20 elements then you cannot assign
like this,and it will be tedious to initialize your array with array initializer,so you can initialize your arrays
by loops

For(int i=0, )

the limit of the array

Program

# include<iostream>

using namespace std;

int main(){

int myArray[31];

for( int i=0 ; i<=30 , i++)

MyArray[ ]

return 0;

Then we will assign the value of array as this,you can print the i th element of the array like this

Program

# include<iostream>

using namespace std;

int main(){

int myArray[31];

for( int i=0 ; i<=30 , i++)

myArray[ i ]=69;

Cout<<i<<”----------------“<<myArray[ i ]<<endl;

}
return 0;

output

0-----------69

2-----------69

3-----------69

4-----------69

5-----------69

6-----------69

7-----------69

8-----------69

9------------69

10----------69

11-----------69

12-----------69

13-----------69

And similarly upto this

30--------------69

So this has assigned value of 69 to each and all elements of the array,so we have seen how to initialize
values ain the array and how to assign values in the array

Day 19:Getting the Sum of Values in an Array

In the last chapter we have seen how to declare arrays,how to initialize arrays,how to use arrays in c+
+,this chapter we will see an example using arrays,so that you will know the concepts about arrays,we
will see how you can add all the elements of an array in this example,and now we will assign the number
of values it will contain,suppose it will contain 8 values,and then we will initialize the array with array
initializer values

Program

# include<iostream>

using namespace std;

int main()

Int myArray[ 8 ]={ 465,676,458,676,234,458,234,458 };

return 0;

Now lets see how we will get the sum of the array,we will declare a variable sum which will hold the sum
of all the elements in the array,int sum=0,now we will declare a for loop

For(int i=0 ; i<8 ; i++)

Sum+=myArray[ i ]

Return 0;

We have taken i<8 because for 8 elements in the array the maximum value of i will be 7 since the index
of the array starts from 0 and the maximum index of the array goes to this 7,so what this
Sum+=myArray[ i ] will do is it will first take the 0 th element then the 1 st element because it is in the
loop and goes to this 7,when all the addition is done and for loop is complete we are going to print the
sum

Program

# include<iostream>

using namespace std;

int main()
{

Int myArray[ 8 ]={ 465,676,458,676,234,458,234,458 };

Int sum=0;

For(int i=0 ; i<8 ; i++)

Sum+=myArray[ i ]

return 0;

Program

# include<iostream>

using namespace std;

int main()

Int myArray[ 8 ]={ 465,676,458,676,234,458,234,458 };

Int sum=0;

For(int i=0 ; i<8 ; i++)

Sum+=myArray[ i ]

cout<<”sum=”<<sum<<endl;

return 0;

We will print the variable sum,we see the output

Output

Sum= 2983
Day 20:Multidimensional Arrays

In the previous chapters we have seen how to use arrays in this chapter we will see how to use
multidimensional arrays,for array of 2*2 or 2*3 how we can declare this

Program

# include<iostream>

using namespace std;

int main()

/// 1 2 3

/// 4 4 5

Int myArray[ 2 ][ 3 ]={ { 1,2,3} , {4,4,5} };

return 0;

So we will see what this is this is a 2 dimensional array which contains 2 rows and 3 columns,so you can
see this in the comments of the program that it is a 2 dimensional array which contains 2 rows and 3
columns,suppose i want the index of this value 2 in the array so how we can find the index of this value
just like co-ordinates we see that the value of 2 is this we will take the index values for rows and
columns so this value 2 is at row 0 and column 1 so we will print the value cout<<myArray[ 0 ][ 1 ];

Program

# include<iostream>

using namespace std;

int main()

/// 1 2 3

/// 4 4 5

Int myArray[ 2 ][ 3 ]={ { 1,2,3} , {4,4,5} };


cout<myArray[ 0 ][ 1 ];

return 0;

Output

Suppose we want to print 5

Program

# include<iostream>

using namespace std;

int main()

/// 1 2 3

/// 4 4 5

Int myArray[ 2 ][ 3 ]={ { 1,2,3} , {4,4,5} };

cout<myArray[ 1 ][ 2 ];

return 0;

Output

There is a convenient way of printing suppose you have 4*5 array or 13*13 array we have to use a
nested for loop like this

Program

# include<iostream>
using namespace std;

int main()

/// 1 2 3

/// 4 4 5

Int myArray[ 2 ][ 3 ]={ { 1,2,3} , {4,4,5} };

for ()

for()

return 0;

Program

# include<iostream>

using namespace std;

int main()

/// 1 2 3

/// 4 4 5

Int myArray[ 2 ][ 3 ]={ { 1,2,3} , {4,4,5} };

for (int row=0 ; row<2 ; row++)

for(column =0 ; column<3 ; column ++)

{
cout<<myArray[row][column]<<” “;

return 0;

We will give spacing between the arrays by “ “ and then change the line for arrays by cout endl,What
this nested for loop will do is it will loop the rows and then it will loop the columns,and then it will print
all the row elements and then all the column elements,so in the for loop first it will start form row 0 and
column 0 so this cout<<myArray[row][column]<<” “; statement will tell give me the values of row 0
and column 0 so the element [0][0] is 1 then it will take the values of row 0 and column 1 that is [0][1]
that is 2 then [0][2] that is 3 similiarly it will take the values for [1][0] ,[1][1] and [1][2]

Output

1 2 3

4 4 5

So by using nested for loops you can print the elements in the multidimensional arrays

Day 21:Pointers in c++

In this chapter we will see what is pointers and how we can use pointers in c++,we will see what pointer
is a pointer is a variable whose value is the address of another variable

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

return 0;
so whwnever you declare a variable its value its value is stored in the memory somewhere,so how
you ,so when you declare var=0 how you can show the address of this variable,where this variable is
stored

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=0;

return 0;

you can show this by the & sign before the variable and then you will be alble to see the address of the
variable this

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=0;

cout<<&var<<endl;

return 0;

we see the output


output

0*28fefc

This value indicates the memory address of the variable where it is stored,it creates the memory
address of this variable,so a pointer is a variable whole value is the memory address of another
variable,and why we do this is that whenever we assign some value to the variable once again you
assign it to some other variable,its value is not fixed so right now we have this var=0 and you can assign
var=20 also this

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=0;

cout<<&var<<endl;

var=20;

return 0;

So whenever you assign this 20 to this var the address will remain same but the value will change,so a
pointer enables us to point to that address whatever value stored in that address,will be pointed by the
pointer,so we can declare a pointer like this int then name of the pointer that is int *intP;we always
assign the value to the pointer whose value is the address of another variable,so what we can do is that
we can write intP= the address of this variable var this

Int var=0;

cout<<&var<<endl;

so intP=&var

Program

# include<iostream>

using namespace std;


int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=0;

cout<<&var<<endl;

int *intP;

intP=&var;

return 0;

And when we print this pointer it will show the address of this variable &var this so first of all

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=0;

cout<<&var<<endl;

int *intP;

intP=&var;

cout<<intP<<endl;

return 0;

We see the output


Output

0*28fefc

0*28fefc

So this is what a pointer does is that it stores the value at the address of another variable so here the
value is 0*28fefc and the address is 0*28fefc so the values are same so this is what a pointer does,now
suppose we do the var =100

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=100;

cout<<&var<<endl;

int *intP;

intP=&var;

cout<<intP<<endl;

cout<<*intP<<endl;

return 0;

Output

0*28fefc

0*28fefc

100

We want to access this value 100 using the pointer intP so how you can do this

So this *intP will show the value which is stored at this address,so if this *intP is showing the value of
this address 0*28fefc
And once again try to print the value of this pointer intP and the address of this pointer *intP

Program

# include<iostream>

using namespace std;

int main()

///what is a pointer

/// a pointer is a variable whose value is the address of another variable

Int var=100;

cout<<&var<<endl;

int *intP;

intP=&var;

cout<<intP<<endl;

cout<<*intP<<endl;

var=20;

cout<<intP<<endl;

cout<<*intP<<endl;

return 0;

output

0*28fefc

0*28fefc

100

0*28fefc

20

The address remains the same but the value that this pointer *intP is accessing is changed when we
declare this variable as 20,so the pointer intP is accessing the value from this address 0*28fefc so the
address of a variable always remains the same but you can change the value stored at this particular
address,so when we assign a value to the var in the second case when we give var=20 the address
remains same but the value of the variable changes that is stored on this particular address,so this is
basics of pointers in c++,you need to see in details about pointers but this is basics of pointers

Day 22:Pass By Reference/Value in C++

in the previus chapters we have seen what are pointers and how to declare pointers in c++,in the earlier
chapters we have seen how we can pass arguments in functions and that specifically is called pass by
value,we can create a function called pass ByValue

Program

# include<iostream>

using namespace std;

void passByValue(int val)

int main()

Return 0;

You are passing a value called val and you declare val=100 and whenever you declare one more variable
x=20

Program

# include<iostream>

using namespace std;

void passByValue(int val)


{

val=100;

int main()

Int x=20;

Return 0;

And when you call this function passByValue here this and you pass x as a function

Program

# include<iostream>

using namespace std;

void passByValue(int val)

val=100;

int main()

Int x=20;

passByValue(x);

cout<<x<<endl;

Return 0;

So whenever you pass the value of x here this passByValue(x); the value of x is passed here this in(x);not
the address of this variable int x=20;that is you are not passing the variable itself in this
passByValue(x);you are just passing the value contained by this variable int x=20;so whenever you try to
print this x once again so even though we have assigned here this val=100

void passByValue(int val)


{

val=100;

So since we have only passed the value of x in passBy value(x); and not the variable itself or the address
of the variable int x=20 here this,so it just sends the copy of the value of x from int x=20 to
passByValue(x);and prints x and the value of x remains same now for,now if you want to change the
value of x itself and you want to a call it inside a function then you will use pass by reference

Program

# include<iostream>

using namespace std;

void passByValue(int val)

val=100;

void passByReference(int val)

val=100;

int main()

Int x=20;

Int y=20;

passByValue(x);

cout<<x<<endl;

Return 0;

So hwo you pass by reference pass the address of the variable in val, in this function void
passByReference(int *val)
So what is a pointer,a pointer is a variable whose value is the address of another variable,so this *val will
contain the address of another variable whatever variable you will pass here this

Program

# include<iostream>

using namespace std;

void passByValue(int val)

val=100;

void passByReference(int *val)

*val=100;

int main()

Int x=20;

Int y=20;

passByValue(x);

cout<<x<<endl;

passByVReference(&y);

cout<<y<<endl;

Return 0;

Output

20

100
So what is happening is in the first case for x when we passed the value of x before main val=100 the
value did not change and it remained 20,but when we pass by reference,it is that we have passed the
address so this address will not change and we are changing the value inside the same address &y will
be 100 now *val,so whenever you want only the copy of the value of the variable you pass by value,so
whenever you want to change the value of the variable you pass it in the function you use pass by
Reference

Day 23:Data Structures or Struct(C++)

In this chapter we will see how you can use data structures or structures in c++,so first of all wht we
need to use data structures or structures in c++,so in previous chapters we have seen that we can define
the variables in c++ this way

Program

# include<iostream>

# include<cstring>

using namespace std;

int main()

Int a;

char b;

return 0;

We can define the variables like this int name of the variable int a; the these int and char are predefined
data types so we haven’t defines these int or char,suppose you want to define your own data type so
you can use structures to define your own data type,so let us take an example thatwe want to define a
structure for a book,a book can contain a book name, a book author,or book id,and you want to use
these author and id as a data type,or book as a data type then how you can define a structure for a book
so the syntax for structures is struct and the name of the structure so we have this struct Book;

Program

# include<iostream>

# include<cstring>

using namespace std;


struct Books;

};

int main()

return 0;

And then give the semi colon and the colon to complete the structure,and inside the structure you can
define the traits of the book for example,book has a name it can be written by a author and book has a
id,so now you have defined a new data type called book

Struct Books

Char name[50];

Char author[50];

Int id;

};

Now you can use this data type Books to call the members of your structure like name,author and id,so
how you can call this structure in your main,you need to once again you need to call struct Books;

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};
int main()

return 0;

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()

Struct Books

return 0;

After Struct Book written after main()And then you need to give the name of the variable you
want to give to your book data type,book 1 variable

Struct books Book 1

Now I want to assign value to my book 1 variable and the data type of book 1 variable is Books

Program

# include<iostream>
# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()

Struct Books book 1;

book 1.name=”C++ Tutorials”;

strcpy()

return 0;

So I want to assign values to my book 1 variable,when we use dot called as dot separator,when you
enter book 1. You will find three options like this author:char id:int and name:char you can select any
1 of these,so we choose this book 1.name and the name of the book we can give c++ that is
book1.name=”C++ tutorials”;1 more thing we will see that this type of assignment to the character array
is not that,in order to copy a string inside a char efficiently,there is another way to copy this string inside
the character array,you can use string copy strcpy and as the first argument of this strcpy that is
book1.name,we can give the name of the variable in which you want to copy the string,we want to copy
the string in this strcpy(book1.name) and as the second argument in strcpy you can give this string in
which you want to copy this character array variable this

strcpy(book1.name,”C++ Tutorials”);

Avoid this type of assignment

book 1.name=”C++ Tutorials”;

when you want to assign string inside a character array

Program

# include<iostream>
# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()

Struct Books book 1;

book 1.name=”C++ Tutorials”;

strcpy(book1.name,”C++ Tutorials”);

return 0;

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()
{

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

return 0;

Therefore it is a good practice to use strcpy instead of directly assigning the string to the character
array,and 1 more thing is that in order to use strcpy you need to include the cstring library function

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

return 0;

}
Similiarly we will give the author and we will assign an id to the author

We want to access the data that is contained by the book1 variable this

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

cout<<”Book 1 name:”<<book1.name<<endl;

cout<<”Book 1 author:”<<book1.author<<endl;

cout<<”Book 1 id:”<<book1.id<<endl;
return 0;

Now this will show whatever we assigned to out book data type

Output

Book 1 name : C++ Tutorials

Book 1 author: Programming Knowledge

Book 1 id:1

You can access the data contained in the book variable by book1.name,book1,author and book1.id,in
this way structures allows you to define your own data type,in out case we have defined the data type
as Books

Struct Books

Struct Books book 1;

And the books has the traits book name,book author and book id,and then using this data type Books
we have defined a variable book 1,so we have data type Books and the name in the data type is book1
and name and then we can assign values to our variables book1 in this way

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

and when we want to access the values inside the variable book 1

cout<<”Book 1 name:”<<book1.name<<endl;

cout<<”Book 1 author:”<<book1.author<<endl;

cout<<”Book 1 id:”<<book1.id<<endl;

if you want to access name you can write book1.name,if you want to access the author we can write
book1.author and if you want to access the id you can write book1.id,this way you can access the
structures content and you can assign book 2 book 3 and you can access the contents inside these
books,this way you can define your own data type using struct and you can also functions inside
structures this is a more advanced ,for basic it is these are the data types
Day 24:How to Pass a Structure to a Function in C++

In the last chapter we have seen the how to use structures in c++,and we have seen the example how
you can define a structure for a book and how can call your structure inside your main and how you can
assign values to your structure members,in this chapter we will see how we can use structures as an
argument to the function,in a program we can pass the argument like int,char,double or float values
this,we have seen that a structure is a user defined data type these char and int are c++ data type and
this Books is user defined data type which we have created,now in order to access this function Books
inside a structure,you need to pass it like a structure,lets see how we can use structures as an argument
inside a function,

Suppose I need a function to print the content of the books,we will use the program from the last
chapter

Program

# include<iostream>

# include<cstring>

using namespace std;

Struct Books

Char name[50];

Char author[50];

Int id;

};

void printBook()

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);
book1.id=1;

cout<<”Book 1 name:”<<book1.name<<endl;

cout<<”Book 1 author:”<<book1.author<<endl;

cout<<”Book 1 id:”<<book1.id<<endl;

return 0;

We will define a function called void printBook and give the parenthesis,now in order to pass your Books
structure in your function as an argument

void printBook(struct Books)

And then you need to call the structure that is struct and the name of the structure Books which is the
data type

Program

# include<iostream>

# include<cstring>

using namespace std;

struct Books

Char name[50];

Char author[50];

Int id;

};

void printBook(struct Books)

{
}

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

cout<<”Book 1 name:”<<book1.name<<endl;

cout<<”Book 1 author:”<<book1.author<<endl;

cout<<”Book 1 id:”<<book1.id<<endl;

return 0;

The give name to the books structure we will give this as book

void printBook(struct Books book)

Program

# include<iostream>

# include<cstring>

using namespace std;

struct Books

Char name[50];

Char author[50];

Int id;
};

void printBook(struct Books book)

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

cout<<”Book 1 name:”<<book1.name<<endl;

cout<<”Book 1 author:”<<book1.author<<endl;

cout<<”Book 1 id:”<<book1.id<<endl;

return 0;

This book we will use to print the name contained by the book variable this,we have seen how to call the
content of the book by its members,so we will use book.name,book.author and book.id

Program

# include<iostream>

# include<cstring>

using namespace std;

struct Books

Char name[50];

Char author[50];

Int id;
};

void printBook(struct Books book)

cout<<”Book 1 name:”<<book.name<<endl;

cout<<”Book 1 author:”<<book.author<<endl;

cout<<”Book 1 id:”<<book.id<<endl;

int main()

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

printBook(book 1);

return 0;

book is the variable name and then what is the member name of this book structure,struct Books that is
book.name,struct Books have members book,author and id,now we will use the book to print the book
name,book author and book id,so this you need to call

void printBook(struct Books book)

in order to pass the book variable,Books in this

struct Books

inside this parameter struct in this

void printBook(struct Books book)

inside the function as a parameter or an argument,now in order to call this function nameprintBook
after the main function

printBook()
and as a a variable inside this function that is book1

printBook(book1)

this is an integer variable

and this struct in this is an integer variable

void printBook(struct Books book)

so pass the variable which contains number

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

similarly we will pass this variable Books

void printBook(struct Books book)

because we have defined the Books data type here this

struct Books book1;

for this book in this

void printBook(struct Books book)

so this book we can pass it in this function

Struct Books book 1;

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

printBook(book 1);

we see the output

output
Book 1 name : C++ Tutorials

Book 1 author: Programming Knowledge

Book 1 id:1

We have assigned the values this in this

strcpy(book1.name,”C++ Tutorials”);

strcpy(book1.author,”Programming Knowledge”);

book1.id=1;

and then we are calling this function to print the book

printBook(book 1);

and we are printing the books by this

cout<<”Book 1 name:”<<book.name<<endl;

cout<<”Book 1 author:”<<book.author<<endl;

cout<<”Book 1 id:”<<book.id<<endl;

in this way you can pass astructure variable as a parameter to a function

Day 24:Introduction to C++ Classes and Objects

A class is a collection of related data and function under a single name

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name
Int main()

return 0;

For example our c ++ program can contain many function and many variables this,using class we collect
same kind of function,data nad we use this collection in single class,for example you have abook class
you can collect functions related to book,open book closed book and variables related to book class like
you have the author of the book,name of the book and how many number of pages book contain,so this
kind of data which is same or related to one another,we encapsulate this type of functions or this type
of variables this in a single class the second type of example can be a box class which can contain the
height,width and length of the box,or it can contain functions like the volume of the box or the sutface
area of the box this,so using class we collect related data and function in c++,so let us take an example
of how you can declare a class in c++ using the name

Class and then give the name to your class,it is a best practice to start your class name with capital letter

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{

};

int main()

return 0;

So this is a basic definition of class and inside the class you can declare,print variables or different
functions,suppose you want to use variables or functions you declare inside this class,class Books in your
main program so the functions in the Books class you want to use in your main program you use “public
access specifier”,or if you don’t want to use your function inside your class,and you only want to use
your function inside your class itself,then you need to use “private access specifier”,we will see this in
later chapters but right now we will be using public access specifiers,and whatever you write under this
public: will be treated as public or public members of the class
Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{

public:

};

int main()

return 0;

Suppose we declare a variable int and we will declare a book id

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{

public:

int Id=258;

};

int main()

return 0;

}
And also we will declare a function inside this book id to print this

void printBookId()

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{

public:

int Id=258;

void printBookId()

Cout<<”the book Id is=”<<Id<<endl;

};

int main()

return 0;

Now we have declared a variable inside the book class that is this

int Id=258;

and we have declared a functiuon inside the book class that is this

void printBookId()

Cout<<”the book Id is=”<<Id<<endl;

}
};

So you can declare variables and functions inside your book class or your any class,now suppose you
want to use these “members” int Id=258; or these functions void printBookId()

Inside your book class so what you need to do is you need to declare an object of this class,and why do
we need to use objects because there can be many classes inside your program and there can be
functions that can contain the same name that is there can be another class that can contain the same
function printBookId() or class can also contain id ,int Id,there can be “multiple definition of these
functions” and how will you know which class this function belongs ,so for this you need objects so that
you know which class these functions belongs,

So an object is the instance of the class

To declare an object you need to this name of the class-Books

And then you need the variable name or object name to this class

So after main we have this

Books book1;

So this variable book1 is called the object of the class

And we are going to access the variables inside the book class or going to access the functions inside the
book class using this object book1,now to access this printBookId function using an object we can access
like this

Book1.printBookId();

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{

public:

int Id=258;

void printBookId()

Cout<<”the book Id is=”<<Id<<endl;

}
};

int main()

Books book 1;

book 1.printBookId();

return 0;

Output

The book id is=258

In this way you can declare objects of the class and access the members of the class,so these variables

Int Id=258;

And the functions printBookId() in this

void printBookId()

Cout<<”the book Id is=”<<Id<<endl;

};

Are called the members of the class,so the member variable and member functions of the class you can
directly access these,suppose you want to access this variable Id in,int Id=258,and because this is a
public variable,so can access this variable from the cout statement after the main

Program

# include<iostream>

# include<cstring>

using namespace std;

/// A class is a collection of related data and function under a single name

class Books{
public:

int Id=258;

void printBookId()

Cout<<”the book Id is=”<<Id<<endl;

};

int main()

Books book 1;

book 1.printBookId();

cout<<book1.Id<<endl;

return 0;

Output

The book id is 258

258

So this is the basic introduction of objects and classes in c++

Day 26:Setter/Getter Functions in C++

In the last chapter we have seen how to use classes and objects in c++ and we have seen how you can
access the member variables and member function using objects,now in this chapter we see see a best
practice of using member variables and member functions in your main functions,in the last chapter we
have seen that you can use this public access specifier to access your variables or functions in your main
function,it works properly but it is not a best practice to use your member variables and member
functions of the class directly in your main function,because you want to protect these variables and you
don’t want another user to change the contents of this variables or functions,so here we will see the
concept of setters and getters to acess your variables and functions indirectly in your main function
Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

};

int main()

Books book 1;

return 0;

So here you have the basic declaration of book class and book object,we have seen public access
specifier in last chapter,in this chapter we will see private access specifier,so what is this private access
specifier,you declare under this private access specifier all the member variables and member functions
of the class with be private to the class and you can not use the member variables and member
functions outside the class,so we will declare a variable called string variable,so I will declare another
variable called # include<string> so what this string class will do is it will help us to declare string
variables and there is a thing called

private

string name;

this string is like character array,so this string is handled more efficiently,so string,you can give the value
to the string like this

private:

string name=”the book name is”;

Program

# include<iostream>

# include<cstring>
using namespace std;

class Books{

public:

private:

string name=”the book name is”;

};

int main()

Books book 1;

return 0;

This string name is the private member of our book class,and how can we access this memberin my
main function,because the name variable is private and we cannot use this name variable outside the
class,so let us specify the setter and getter functions to access the name variable in the main function
indirectly

Public:

void setName(string)

we will copy this string from the string name;

and we will give the name of the string as x

Public:

void setName(string x)

and we will say name which is the private member of the class

Public:

void setName(string x)

name=x;

so what I am doing is I am indirectly copying


Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

void setName(string x)

name=x;

private:

string name;

};

int main()

Books book 1;

return 0;

So it will copy the content of this variable x in string x to the name,in name=x;and we have getName
which will return the value of the name in string name;

So name data type is string so it will return string

String getName()

We have the setters and gettes here this

void setName(string x)

name=x;

}
String getName()

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

return 0;

So these are called setting and getting your member variable

void setName(string x)

name=x;
}

string getName()

Return name;

So what these two functions does is helps to get the access to the private member name,using these
public functions like set and get name,now we will see how we can use these set and get names in your
main function,we already have this object called book1 which is derived from the Books class

int main()

Books book 1;

return 0;

We can write like this

book1.setName(“C++ Tutorials”);

so whenever we pass this string “C++ Tutorials” to the set name

int main()

Books book 1;

book1.setName(“C++ Tutorials”);

return 0;

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{
public:

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

book1.setName(“C++ Tutorials”);

return 0;

It has this x here in string x

void setName(string x)

name=x;

In copies the value of x to the name v ariable which is the private variable

private:

String name;

And the private is assigned the value C++ tutorials and now in order to get the value we can print get
name
Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

book1.setName(“C++ Tutorials”);

book1.getName();

return 0;

So this cout<<book1.getName()<<endl;

Will return the value of the name that we have assigned here this

book1.setName(“C++ Tutorials”);
Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

book1.setName(“C++ Tutorials”);

cout<<book1.getName()<<endl;

return 0;

Output

C++ Tutorials
So we are accessing the name variable using this cout<<book1.getName() function,so this is a best
practice to access private member variables of a class using set and get functions,so whevber you need
to declare a variable inside a class,try to always declare the member variables as private,and try to
access these using set and get functions

Day 27:Introduction to Constructors in C++

In this chapter we will see how to use constructors in C++,and what is a constructor,so what is a
constructor,a constructor is a special member function of the class that is created when you create the
object of the class and the name of the constructor is alwatys same as the name of the class that is,so let
us see how we can declare constructors in classes,even if you don’t declare a constructor,c++ will create
a constructor for a class automatically,we have seen that the constructor has the same name as the class
name

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

void setName(string x)

name=x;

string getName()

Return name;
}

private:

string name;

};

int main()

Books book 1;

book1.setName(“C++ Tutorials”);

cout<<book1.getName()<<endl;

return 0;

So this is a constructor,we will pass no parameters inside the parenthesis of Books we declare
constructor in the public access specifier

class Books{

public:

Books()

So it has the same name as the class and it is always initialized when you create an object

So let us verify that if it is initialized when you create an object,we will cout somen message in the
constructor

class Books{

public:

Books()

Cout<<”You are in a Constructor:<<endl;

So we have declared a constructor and we are showing a message inside the constructor
Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

Cout<<”You are in a Constructor:<<endl;

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

return 0;

}
So even though we are not calling any variable in Books book 1; after main we are only creating the
object,and we have seen that constructor is called when you create an object,so we see the output

Output

You are in a constructor

Ypu don’t create a constructor to show some message,generally we use constructor to initialize the
values of the variables in a class,so what you want to do is you want to initialize the value of this
name,we have already created set functions and get functions,and private: string name,we need to
initialize this name with some value,or if another user writes cout<<book1.getName()<<endl;

int main()

Books book 1;

Cout<<book1.getName()<<endl;

return 0;

Because we have not initialzed this getName by a value and directly we are calling this getName we
have not initialized a value this,so we don’t see any output

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

{
Cout<<”You are in a Constructor:<<endl;

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

Books book 1;

cout<<book1.getName()<<endl;

return 0;

We generally use constructor to initialize a value,and how we can initialize this variable name,in private:
string name;you can pass a parameter string x because this variable name is a string

class Books{

public:

Books(string x)

setName(x);
}

So whenever you create an object,Books you give the name to the object,string x

Books(string x)

int main()

Books book 1;

cout<<book1.getName()<<endl;

return 0;

Then that object will go here this

void setName(string x)

name=x;

And that object will assign a name

And indirectly you are assigning your value to the name variable in this

private;

String name;

So we have initialized name by initializing this constructor,so whenever you pass an argument in the
constructor,here we have initialized our constructor

Books(string x)

With this string variable then we need to initialize with argument

int main()
{

Books book 1(“ C++ Tutorials”);

cout<<book1.getName()<<endl;

return 0;

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books( string x)

setName(x);

void setName(string x)

name=x;

string getName()

Return name;

private:

string name;

};

int main()

{
Books book 1;

cout<<book1.getName()<<endl;

return 0;

Output

C++ Tutorials

So what we have done is that we have initialized the values with the constructor,so we use constructor
to initialize value and when constructor constructor is created,whenever you create an object to the
function and when you pass an argument to the constructor,you need to apss the same data type
argument to the constructor that is C++ Tutorials,suppose you declare a different object in the main

int main()

Books book 1(“ C++ Tutorials”);

cout<<book1.getName()<<endl;

Books book 2(“ Java Tutorials”);

cout<<book2.getName()<<endl;

return 0;

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:
Books(string x)

setName(x);

void setName(string x)

name=x;

string getName()

return name;

private:

string name;

};

int main()

Books book 1(“ C++ Tutorials”);

cout<<book1.getName()<<endl;

Books book 2(“ Java Tutorials”);

cout<<book2.getName()<<endl;

return 0;

So you may see that when you pass the second object it may overwrite the first object that you have
passed,but it will not happen whatever objects you create will have a set of names an set of functions,so
this first object will have an independent variable name the function name
string getName()

return name;

and this function set name

void setName(string x)

and the second object will also have its own name,get name and set name functions

when you see the output both the statements will print we see the output

output

C++ Tutorials

Java Tutorials

So the object is the instance of the class and are independent or the another

Day 28:Destructors in C++

Destructor is another kind of class member function that is executed when an object of that class is
destroyed

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()
{

};

int main()

Books book 1;

return 0;

So you can say that it is the another part of the constructor,you use constructor to initialize a value,and
we use destructor to destroy an object when it goes out the scope,we have created a class and we have
a constructor here this,that is the same as the class name,so this is the declaration of a constructor,now
lets see how we can declare a destructor first and then we will see how to use this

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

~Books()

};

int main()

Books book 1;
return 0;

~Books()

Is called a destructor

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

cout<<”we are in a constructor”<<endl;

~Books()

cout<<”we are in a destructor”<<endl;

};

int main()

Books book 1;

return 0;

}
In the main function we have defined an object of this class or an instance of the class,so whenever we
call an object of a class in the main function first of all a constructor is called,and once when it goes to
the end of the scope that it goes to the end of the main function

int main()

Books book 1;

return 0;

That is the curly braces after return 0;it is not necessary that it is the end of the function but whenever
your object goes out of the scope

So we see the output

Output

we are in a constructor

we are in a destructor

so what is happening is that when an object of a class is called the constructor is called and then after
executing the constructor when it goes out of the scope curly braces after return 0 the destrutor is
called,and the resources used by the object

Program

# include<iostream>

# include<cstring>

using namespace std;

class Books{

public:

Books()

cout<<”we are in a constructor”<<endl;


}

~Books()

cout<<”we are in a destructor”<<endl;

};

int main()

Books book 1;

cout<<”we are in a 1”<<endl;

cout<<”we are in a 2”<<endl;

cout<<”we are in a 3”<<endl;

return 0;

Output

we are in a constructor

we are in a 1

we are in a 2

we are in a 3

we are in a destructor

so you don’t need to define explicitly the constructor and destructor,when you define the class they are
initialized ,but for constructor if you do a task like initialize a value function and similarly a destructor
and a constructor
Day 29:Placing Classes in Separate Files in C++

We will see here how you can put classes in different files another than the and use those classes from
different files,in your main.cpp and why it is useful and important to define your files in different
files,because whenever programmer write a program and if they write each and every class on the same
file so it becomes difficult for the another user to read the classes,because there a re so many classes,so
in order to make the program more readable and more accessible,we define our classes in different files
so we will be able to find the classes and it makes the program more readable,so lets see how we can
create files for the class and then we will see how we can use this class in main.cpp

So go to file-new-class

Create new class

We will give the class name

Class name:Books

Do not check other boxes

Go to file policy and check this box

Header and implementation file shall be in the same folder

And what it is that you want to create classs files Books

In your project folder

C:\Users\Programming Knowledge\Desktop\MyFirstProg

Suppose we have the project folder and the project folder contains main.cpp and this project file and I
want this class file also in the same folder

Then click create –new classes have been created

do you want to add it to the current project-yes

Select targets the file should belong to this

Debug

Release

-yes

We will see two file called books.h and books.cpp that is created
Books.h

#ifndef BOOKS_H

#define BOOKS_H

Class Books{

pPublic:

Books();

protected:

private;

};

#endif

Books.cpp

#include “books.h”

Books: :Books()

If you get this error

Undefined reference to “MinMain16”

Then wht you can do is that

You can close the project and save all the changes

We will reopen this projrct and once again when we compile this project

Main.cpp

# include<iostream>

# include<cstring>
using namespace std;

int main()

Return 0;

Now there are no errors

Books.h is called header file

Books.cpp is called the source file

Header file contains the declaration of the prototyping of the class or the method,so whatever
declaration of the class you want to do you will do in the header file,and this source file will contain the
definition of those member functions or classes,the definition of the methods,we have seen what if
function prototyping you make a prototype of your function above the main function and you can give
the definition of the function after the main function,so what you define above is called prototyping
same this header file is doing is only contain the prototype and this source file contains only the
definition,it has class and 3 preprocessor directives and in the header file we see Books(); is the
constructor,so we will keep only public ,so lets define members inside this public that is member
variables

Books.h

#ifndef BOOKS_H

#define BOOKS_H

Class Books{

pPublic:

Books();

Int bookId;

Void setBookId(bookId_)
};

#endif

And it takes the argument same as bookid_is the argument and bookid is the member variable function

Books.h

#ifndef BOOKS_H

#define BOOKS_H

Class Books{

pPublic:

Books();

Int bookId;

void setBookId(bookId_)

Int getBookId()

};

#endif

and this, Int getBookId() does not take any argument so this is called prototyping a function,and in the
header file we do the prototyping of the function and in the,and the source file or the definition will
come in this books.cpp

Books.cpp

#include “books.h”
Books: :Books()

void setBookId(int Bookid_)

int getBookId;

so this : : is called binary scope resolution operator,because we can define different classes which can
have the same function set id and getBook id,so how you will recognize that this setBook Id is a part of
tis class,class Books,so you use the

name of the class: :member function

Books: : Books()

Class name: :constructor/member function

We see the first books declared in the header program is the class name and the second books declared
in the header program is the constructor or the member function,we go to the source file for the
definition

So before the name of the function you use the name of the class

Books.cpp

#include “books.h”

Books: :Books()

Void Books: : setBookId(int Bookid_)

int getBookId;

name of the class: : name of the function

so we can say that this function, setBookId(int Bookid_)

is a member function of the Book class,and same we will do with getBookId;

Books.cpp
#include “books.h”

Books: :Books()

void Books: : setBookId(int Bookid_)

int Books: :getBookId;

we need to write the function for setBookId and getBookId;

so in setter function what we do is we take the argument here this and pass it to the member variable in
book.cpp

Books.cpp

#include “books.h”

Books: :Books()

Void Books: : setBookId(int Bookid_)

bookId=bookId_;

int Books: :getBookId;

and what getter does is it only returns your member variable

Books.cpp

#include “books.h”

Books: :Books()
{

Void Books: : setBookId(int Bookid_)

bookId=bookId_;

int Books: :getBookId;{

return bookId;

So we define member functions and now whenever you see this main.cpp

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

int main()

Return 0;

We have the include iostream,cstring and using namespace std; so we need to include it in the header
file also this

Books.h

#ifndef BOOKS_H

#define BOOKS_H

# include<iostream>
# include<cstring>

using namespace std;

Class Books{

public:

Books();

Int bookId;

void setBookId(bookId_)

Int getBookId()

};

#endif

So you use header file iostream so that int bookid does not sees that where this comes from,so we
include it in the header file also,if you see in the books.cpp,it will be including this “Books.h”,so your
source file always be initialized by the inclusion of your header file and why we are including this in
books.cpp,# include “books.h,source file that is book.cpp will always be initialized by the inclusion of the
header file,we are including here this to tell the source file which is book.cpp,we have declared the
prototype of this class in the header file,include all the classes all the declaration from the header file in
the cpp file so this file will include,so this file will include all the declaration done in the header file,now
the books.cpp file will see that it will see the declaration here in the header file and and then it can give
the source code for these member function in the program

Books.cpp

#include “books.h”

Books: :Books()

Void Books: : setBookId(int Bookid_)


{

bookId=bookId_;

int Books: :getBookId;

so we have to always include this Books.h in the books.cpp file,so we will include this in the main.cpp file
also this,so we will call your class in the main.cpp

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

Return 0;

We have the include iostream,cstring and using namespace std; so we need to include it in the header
file also this,so include this file in the main.cpp file so your main.cpp file knows that there is a header file
so it will go to the header file and it will see that there is a class declaration here the,so there it knows
that there is a class in the header file,so we will create an object of the class,so this is object
declaration,for the class in the header file

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”
int main()

Return 0;

Then we will use the object to call the member function of the class

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

Books book1;

Book1.setBookId(100);

cout<<book1.getBookId()<<endl;

Return 0;

We will use print.bookId to print the Id of the Book,so this will getbookId will return 100 because we
have the set the value of book id to 100,so we will compile the program,we see the output

Output

100
Now we can declare the file in the source file and header file,we can use these classes in the main.cpp
file,so it is that you can see the program in the header and the source files,and this makes the code ok in
terms of readability,so when you have many classes so it will make it ok to read your files

Day 30:Arrow Member Selection Operator and Pointers to Classes

It the previous chapter we have seen that how we can create class in other files another that the
main.cpp file,so we have created classes in header file and the source file so we can create files in
separate files,how you can create a class in the separate file,so we will see the class example in the
previous chapter and we will demonstrate,how arrow member selection operators work in the header
file we have the book class and we have the public members,that is public member variable,bookid in int
bookId;and we have created setter and getter methods for this book id,so header file contains prototype
of class and member functions,and source files contains the source code of the prototypes which are
there in the header file and how your cpp file knows by including this header file in the cpp file it Knows
that there is the class that is in header file and the definition of this class is in the source file that is
Books.cpp,and we have written the source code for the setter and getter function in Books.cpp file,so
this header file contains class which has a member variable and a setter and getter function for this
member variable,and the setter and getter and member function for setBookId and getBookId is there in
the source code program,this we have seen,and in the main.cpp file we have seen how we can create an
object of the class book class and how you can call this member method or member functions from the
class that is .setbookId from the object like this,book1.setBookId,so we have called the setBookId and
getBookId fro the Books class,you can also say that this ,Books book1, Books is a user defined data
type,we have seen that we can create string and string with a value function

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

String value;

Books book1;

Book1.setBookId(100);
cout<<book1.getBookId()<<endl;

Return 0;

So we have the string data type and Books class which is the book data type,so this Books is also a user
defined data type and this book 1 is the variable functions so we can use the concept of pointers which
we have seen in the earlier chapters and we can use the object of this variable book1 to access the
member function of the class ,book1.getBookId() so we can define,so we can define the book pointer

Books *bookPointer

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

String value;

Books book1;

Books *bookPointer=& book 1

Book1.setBookId(100);

cout<<book1.getBookId()<<endl;

Return 0;

a pointer is a variable whose address is the value of another variable,so I want to give the value of this
pointer as the address of this book class,so we have created a pointer book and by using this pointer you
can acess setter and getter functions as we have seen when we have created book1 so when we have
created book1 we can access these member variables functions using the dot separator so either you
copy the pointer of type book

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

Books book1;

Books *bookPointer=& book 1

Book1.setBookId(100);

cout<<book1.getBookId()<<endl;

(*bookPointer).setBookId(400)

cout<<(*bookPointer).getBookId()<<endl;

Return 0;

Output

100

400

So the poinyter of book type is working,instead of using the (*bookPointer to call the function)we will
copy book pointer and give arrow like this bookPointer->,this is called the arrow member selection
operator function,the function of this is same as the dot separator but when you use arrow the c++
program knows that this,bookPointer is a pointer and you can acces the member variables using arrow
member selection operator function

bookPointer->setBookId(1000)

Main.cpp

# include<iostream>

# include<cstring>

using namespace std;

# include” Books.h”

int main()

Books book1;

Books *bookPointer=& book 1

Book1.setBookId(100);

cout<<book1.getBookId()<<endl;

(*bookPointer).setBookId(400)

cout<<(*bookPointer).getBookId()<<endl;

bookPointer->setBookId(1000)

cout<<bookPointer->getBookId()<<endl;

return 0;

So from this cout with arrow we see that this bookPointer is the object or the variable function of the
class Books

Output

100
400

1000

So you can define pointer of the class, Books *bookPointer=& book 1

So this is arrow member selection operator function

Day 31:Operator Overloading in C++

In this chapter we will see operator overloading in C++,so c has operators which we can use to perform
algorithmic tasks or you can do comparison task from these operators

+=

-=

*=

/=

%=

&=

<<=

>>=

^=

|=

&
<<

>>

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

};

Int main()

Int x=2,y=3;

Int z=x+y;

return 0;

Here we see that + is an operator function and = is an assignment operator,suppose we have values or
objects to add for example,suppose we have this class Vector and we want to add the two object of the
class

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;
Vector () ();

};

Int main()

Vector vec1;

Vector vec2;

Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

So adding these two vectors 1 and 2 and assigning it in third vector vec3 is it possible in c++

There will be an error because c++ does not know that there is a class called Vector,this Vector class is
user defined class,so if we use + in vec1+vec2,it does not know that it should add two operators of the
class,we can use the operator overloading it is same as the method overloading.

So what is method overloading,we can define two functions of same name,and these two functions can
do two different task,but they can have the same name,in the same way we can do this operator
overloading to two different task from the same operator,suppose I want to add these two objects I can
add them by definining the operator that can be overloaded,so lets see how we can do that,suppose we
want to add two vector values which are the Cartesian values this

(4,2) (4,5)

=(4+4 ,2+5)

=(8,7)

Suppose I want to add these two values using a class and I want to use the + operator and I want the
result like this (8,7)

We can do this by operator overloading

So I have defined the class Vector which is declared public and it has two member variables int x,y and
we have this default constructor Vector() (); that doesn’t take any values,so we will take another
constructor of same name to perform two different task

Program
# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

};

Int main()

Vector vec1;

Vector vec2;

Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

I am initializing this vector constructor by two values a and b,these values a nad b we will assign to x and
y

Program

# include<iostream>

# include<string>
using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

};

Int main()

Vector vec1;

Vector vec2;

Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

so whenever you define operator overloading,we need to make a prototype of this Vector,and operator
overloading in defined as this is vector class so it will return vector

Vector operator+()

We are overloading the + operator so we write + and then we pass the argument in the paranthesis

Vector operator+(cost vector&);

This is the prototype


We want to write the source vector for this,so we copy this and write the definition of this function
outside the prototype

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector operator+(cost vector&){

Int main()

Vector vec1;

Vector vec2;

Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

}
We need to give the scope for this operator function,we need to give the class of the operator and then

: : scope resolution operator function

Now by seeing this

Vector Vector : : operator+(cost Vector&){

We know that the operator is the part of this Vector class

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector&){

Int main()

Vector vec1;

Vector vec2;
Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

Now we can write the definition of this function

Vector Vector : : operator+(cost vector&){

So we will create a new class Vector and object temp

Vector temp;

And using this temp we want to do the addition of these two vectors

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector&){

We will do temp.x which is a member variable of the class

Vector Vector : : operator+(cost Vector& parameters){

Here parameter is the object of the class

temp.x = x + parameter.x;

so parameter is also an object of class vector and temp is also the object of class vector

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;
Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

Int main()

Vector vec1;

Vector vec2;

Vector vec3=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

And whatever we pass here this

Vector Vector : : operator+(cost Vector& parameter){

Vector temp;

temp.x = x + parameter.x;

}
We pass parameter in the Vector class and whatever we pass here this we want to add it to this temp
object in temp.x,similarly we want to do this for y variable,so we can do this like this

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

return temp;
}

Int main()

Int x=2,y=3;

Int z=x+y;

return 0;

Since this Vector Vector : : operator+(cost vector& parameter){

Is expecting vector object return so we will do this is will return the temp variable function so what it is
doing is when we pass any parameter it adds to the temp and then returns the value function,so
thisoperator will be overloaded

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

return temp;

it will be overloaded here this to add these parameters to temp,we can define two object of a vector
class and we will take this constructor that takes two integer values this

Vector(int a , int b)

Vector vec1(4,2)

Vector vec2(4,5)

Program

# include<iostream>
# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

return temp;

Int main()

Vector vec1(4,2);

Vector vec2(4,5);

Int x=2,y=3;

Int z=x+y;

return 0;

}
And we can add these values in the vector coordinates in the third vector

Vector result;

result=vec1+vec2;

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(cost vector&);

};

Vector Vector : : operator+(cost vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

return temp;

Int main()

Vector vec1(4,2);
Vector vec2(4,5);

Vector result;

result=vec1+vec2;

Int x=2,y=3;

Int z=x+y;

return 0;

Now this is not going to give an error we told the c++ library that there is a + operator this

Vector Vector : : operator+(cost vector& parameter){

This + operator is able to add two objects of the class

We will output the result

cout<<”the result is(“<<result.x <<”,”<<result.y<<”)”endl;

Program

# include<iostream>

# include<string>

using namespace std;

Class Vector{

Public:

Int x,y;

Vector () ();

Vector(int a , int b)

x=a;

y=b;

Vector operator+(const vector&);


};

Vector Vector : : operator+(const vector& parameter){

Vector temp;

temp.x = x + parameter.x;

temp.y = y + parameter.y;

return temp;

Int main()

Vector vec1(4,2);

Vector vec2(4,5);

Vector result;

result=vec1+vec2;

cout<<”the result is(“<<result.x <<”,”<<result.y<<”)”endl;

Int x=2,y=3;

Int z=x+y;

return 0;

Output

(8,7)

So we have added two vector object using this + operator function

So in the similar way we can write a program to overload any of the operators as we have seen above
Day 32: C++ Inheritance

We will see here this what is inheritance and how do we use inheritance in c++,so c++ is an object
oriented programming knowledge ,inheritance is one of the most important concepts of object oriented
programming,

so what inheritance does is inheritance allows us to define a class in terms of another class

which makes it ok to create and maintain our application,and this in result will increase the reusability of
code and faster implementation of our code,now suppose you want to calculate the area of some
shapes,polygon can be a rectangle,polygon can be a square and a polygon can be a triangle because
each of the polygon has similar properties,so what is the property,so every polygon square,triange or
rectangle have height and width common,but calculation of area for each of the polygon is different,so
we can define a class that has width and height,that we can resuse in another class like square,triange or
rectangle so it will reduce the writability of the code and we can use the reusability of our height and
width polygon class

so how we will define the inheritance classes in C++,inheritance class shape and this class has two
variables this width and height and what this is these are protected members

Program

# include<iostream>

# include<String>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;
We have not seen protected members of a class,protected members of a class,are reusable or can be
used in other class,which is inheriting this class shape,the public members are available in other classes
which are not inheriting from base class,so we have a class called base class which will be a base class
for square triangle or rectangle class,and height and width we need to keep common for square,triangle
or rectangle class,so we have class called shape which has protected members which is height and width
and which has public member function that sets the height and width,this function takes two arguments
and whatever argument you pass in this function so it will set the values of these height and width

So shape is a base class,suppose I define a class called rectangle and it has a public function called area

class rectangle

public:

void area:

};

We are going to use the height and width from the shape class to the rectangle class,and how we can
use it by using inheritance,we will inherit from our shape class to our rectangle class,the shape class in
our case is called base class and rectangle class in our case os called derived class,and how we can
inherit form the shape class

Program

# include<iostream>

# include<String>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;
Int width;

class rectangle

public:

void area:

};

int main()

and how we can inherit from the base class the member variables or member functions in the derived
class we use this kind of colon

Program

# include<iostream>

# include<String>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:
void area:

};

int main()

then we define the access modifier which is public and then the name of the class from which we are
deriving

class rectangle : public shape

this kind of declaration is called inheriting from the base class to the derived class and rectangle in this
case is called derived class and shape is called the base class from which we are inheriting and what we
are inheriting the height and width or the polygon class,so we have the function public and we want to
calculate the area so what we can do is this,when we are inheriting from the shape class which has
height and width,defined already,we can use all the public and protected members from the base class
in the derived class so we can use the height and width in the derived class,so what is the area of the
rectangle height*width

public:

void area()

return()

};

We are inheriting from shape class and these are the member variables height*width,so inheritance
allows us to reuse the base class in the derived class and since the height and width are there in the
base class we can reuse it in the derived class

public:

void area()

return(height*width)

};

Program

# include<iostream>

# include<string>

Using namespace std;


///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

void area(){

return (height*width)

};

int main()

To calculate the are let us define another class called triangle will also inherit from the base class,we
want to calculate the base class,so this is a second class which is inheriting from the base class

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle


Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

void area(){

return (height*width)

};

class triangle : public shape

public:

void area(){

return (height*width/2)

};

int main()

}
We are reusing the variables from our base class in the derived class,we can define the object of the
triangle class and rectangle class in the main

rectangle rec;

triangle tri;

so we can reuse or use the function which is,setvalue in this void setValues(int a,int b) which is there in
the shape class by using these objects tri or rec,because we are inheriting from the base class

rectangle rec;

triangle tri;

rec.setValues(16,10);

this will set the width and height as 16 and 10 and because we are returning this,return(height*width)

we need to return int instead of void,so we return int area

class rectangle : public shape

public:

int area(){

return (height*width)

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;
height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width)

};

class triangle : public shape

public:

int area(){

return (height*width/2)

};

int main()

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);

}
We are returning integer int area, triangle and rectangle,in the same way we can use triangle variable to
set the triangle value,the member function set value,so same values we want to give here in case of a
triangle,to calculate the are of the triangle ,so this set function,is there in the base class,we can reuse it
in the derived class by using the object of the derived classes,to calculate the are we can write std

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);

std: : cout<<”area Rectangle=”

we can write area of the rectangle from the rectangle function

class rectangle : public shape

public:

int area(){

return (height*width)

we can use the object of this rectangle class=rec.area()<<std: :en

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);

std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

Similarly we can find the area of the triangle

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);
std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

std: : cout<<”area Triangle=”<<tri.area()<<std: :endl;

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

};

class triangle : public shape

{
public:

int area(){

return (height*width/2);

};

int main()

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);

std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

std: : cout<<”area Triangle=”<<tri.area()<<std: :endl;

We see the output

Area of triangle 80

Area of rectangle 160

So this is the concept of inheritance so once again what inheritance does,is it allows to use out member
variables or member functions,from the base class which is the shape class and we can inherit from the
shape class,

Class shape

Public:

void setValues(int a,int b){

because what we want to use is the height and the width from the class
Protected

Int height;

Int width;

We want to reuse this height and width function in our triangle class

class triangle : public shape

public:

int area(){

return (height*width/2);

And we want to reuse this height and width in our rectangle class

class rectangle : public shape

public:

int area(){

return (height*width);

Or even square class,and the derived class ,class rectangle: public shape,chich is inheriting from the base
class,class shape,and this class has the access to both the protected members and public members of
the base class,so protected members are members which can be reused in derived class,but if the height
and width was private member it cannot to reused in the derived class,the private members are private
to the base class,it cannot be reused inside the derived class,and public class can be used everywhere
even if the rectangle class if it was not derived from the base class

class rectangle : public shape

even then we can use public members from shape class which is the base class

so when we have to use the height and width from the base class to the derived class,we have define
the member variables height and width as protected and not private so that it can be reused from the
base class shape to the derived class rectangle,protected members are available only in the derived class
and not any other class,and public members are accessible to any class even though the class is not
inherereting from the base class and private members cannot be used outside the class because they
are private,so this is the difference between public,private and protected access modifiers,now how do
you come to know that you can use inheritance in your c++ program

inheritance always have a is a relation

///polygon // square triangle rectangle “ is a”

If you can find the relation that square “is a” polygon

Triangle “is a” polygon

Rectangle “is a”polygon then you can use inheritance

///polygon // square triangle rectangle “ is a” Animal dog cat

So for base class animal and derived class dog and cat we can use inheritance

Since dog “is a” animal

Cat “is a “animal

Day 34: C++ Multiple Inheritance

In the previous chapter we have seen how to use inheritance,we have seen how we can create a base
class and we have created a derived class from which we can inherit from base class,we have seen that
shape is the base class,we have seen polygon and types of polygon,and the polygon for example shape
was the base class,and the rectangle which was inheriting from the base class was derived class,we were
calculating the area from the rectangle by using inheritance method in this example ,so it is not only that
you can inherit from only 1 class you can also do multiple inheritance,we can inherit from multiple
classes,in the previous chapter we have seen that we have inherited,from the shape class which is the
base class and this is rectangle class, class rectangle : public shape

Let us define another base class description that will give the description

Class description

It takes a string which gives us the description

Class description
{

public:

Void print(string description_)

Std: : cout<<”we are using”<<description_<<”class”<<std: :endl

};

Then we will use the description variable which we are passing as an argument in std: : cout,so this also
a base class,we will give the access specifier also public,so this public,void print, gives us the description
of all that we pass as an argument in std: : cout,we have used the shape class as the base class in the
previous chapter and we also want to use description class as the base class for the rectangle class,so
what we can do is we can multiple inherit from this shape class and description class and how we can
do this,we can separate the two base classes by a comma in inheriting for the derived class rectangle

class rectangle : public shape , public description

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;
};

Class description

public:

Void print(string description_)

Std: : cout<<”we are using”<<description_<<”class”<<std: :endl

};

class rectangle : public shape , public description

public:

int area(){

return (height*width);

};

class triangle : public shape

public:

int area(){

return (height*width/2);

};

int main()

rectangle rec;

triangle tri;
rec.setValues(16*10);

tri.setValues(16*10/2);

std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

std: : cout<<”area Triangle=”<<tri.area()<<std: :endl;

So the rectangle class is inheriting from two bases classes,we have to give public for both the bases
classes seperated by a comma

Now we declare in the main()

rec:print(“ Rectangle“);

so we will pass rectangle as a parameter

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

};

Class description
{

public:

Void print(string description_)

Std: : cout<<”we are using”<<description_<<”class”<<std: :endl

};

class rectangle : public shape , public description

public:

int area(){

return (height*width);

};

int main()

rectangle rec;

rec.setValues(16*10);

std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

rec.print(”Rectangle”);

Output

Area rectangle 160

We are using rectangle class,

The member functions and member variables are available for usage by the instance of derived class
also this is in the base class function
In the main we can use rectangle class object rec and then we write the dot separator,we see that a
print method ,print() : void,is also available in the methods which is we have defined in the description
class and since we are inheriting from the base class it is available for the rectangle class also this,so now
in main() you give this,rec.print(“Rectangle”);in this way you can inherit multiple classes for the
functions,member variables or member functions are available for usage by the instance of derived class
also so this is from the base class function, rec.setValues(16*10);in the previus chapter we have seen
that we have defined in the base class,so in the similar way the print, rec.print(”Rectangle”); is defined
in the base class description,we have not defined any print method in the rectangle class but even then
we will be able to use this print method from the description class,because we are inheriting from the
description class in the rectangle class,and when we inherit the public and protected members of the
base class are available for usage in the derived class,so in this way we can use multiple inheritance in c+
+

Day 34: Class in C++

We will see what are friend classes and how to use friend classes in c++,we know that we cannot use
private and protected members outside the class,for example we have a class called my class,and it has
a private member variable called secret so we know that if we declare the variable as private we cannot
use this outside the class,at times we need to use these private members outside the class and this

Program

# include<iostream>

# include<string>

using namespace std;

Class MyClass

private:

int secret;

Int main()

This is when we use friend classes or friend keywords,so my class has a private member called
secret,lets declare another class which is called
classMyAnotherClass{

};

And this class wants to access a private member variable which is private,we know that we cannot
use,there is public member function: this my another class

classMyAnotherClass{

public:

void showSecret()

};

This function showSecret() will take an argument,so we will pass MyClass from class and pass it as an
argument

classMyAnotherClass{

public:

void showSecret(MyClass mc)

mc.secret;

};

This mc is myclass it is the object of the class,when you want to access this secret variable function
which is a private variable function,we write mc.secret
Program

# include<iostream>

# include<string>

using namespace std;

Class MyClass

private:

int secret;

};

classMyAnotherClass{

public:

void showSecret(MyClass mc)

mc.secret;

};

Int main()

It is showing error withing this context,so myClass secret is private in this context,we also know that we
cannot use private members of a class in another class,but for reason you want to use this private
members in another class,you need to declare in the class in which you want to use the private
member,you need to copy the name of the class,because your another class wants to access the private
member,in the first class called my class,so I need to declare myAnotherClass as a friend of another class

We can write this

Friend class MyAnotherClass:


Friend class and then the class for which I want to make the friend,if you declare that myAnotherClass is
a friend of this class,class MyClass,then this friend keyword allows you to access the private member of
the base class,now when you declare that MyanotherClass is a friend of MyClass,so my Class has the
access to the private members of my class

Suppose the secret is set to a value

Program

# include<iostream>

# include<string>

using namespace std;

Class MyClass

private:

int secret;

};

classMyAnotherClass{

public:

void showSecret(MyClass mc)

mc.secret++;

};

Int main()

MyAnotherClass mac;

MyClass mc;

}
We declare the instance of MyAnotherClass and MyClass as and their objects as mac and mc

Int main()

MyAnotherClass mac;

MyClass mc;

mac.showSecret();

MyClass is the instance of this class, Class MyClass which has the private member int secret=10

public:

void showSecret(MyClass mc)

mc.secret++;

std : : cout<<mc.secret<<std: :endl;

};

Program

# include<iostream>

# include<string>

using namespace std;

Class MyClass

private:

int secret=12;

};

classMyAnotherClass{
public:

void showSecret(MyClass mc)

mc.secret++;

std : : cout<<mc.secret<<std: :endl;

};

Int main()

MyAnotherClass mac;

MyClass mc;

mac.showSecret();

Output

13

So whenever you want to use a private or protected member.from 1 class to another class you need to
use the friend keyword friend class keyword in the class in which you want to use the private
member,here class is MyAnotherClass to the class in which you want to access the private
member,suppose this is the class MyAnotherClass in which you want to access the private member of
MyClass,you give friend class MyAnotherClass;so the friend class knows that MyAnotherClass is a friend
of this Class,so you can use the private members from the base class

Day 34:Introduction to Polymorphism

We will see what is polymorphism and how we can use polymorphism in c++,before this you must know
inheritance and about pointers,you can see how inheritance works first and then see this chapter this
So meaning of polymorphism is having different forms,so typically polymorphism occurs when there is a
hierarchy of classes and they are related by inheritance,so the property of polymorphism can be used
where we are using inheritance,classes are related by the hierarchy of inheritance,so we will see how
polymorphism works for that we will see from the chapter how inheritance works,we will see that
program from the chapter

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

};

class triangle : public shape

{
public:

int area(){

return (height*width/2);

};

int main()

rectangle rec;

triangle tri;

rec.setValues(16*10);

tri.setValues(16*10/2);

std: : cout<<”area Rectangle=”<<rec.area()<<std: :endl;

std: : cout<<”area Triangle=”<<tri.area()<<std: :endl;

Here we have the base class called shape and what was the purpose of this class was that I needed to
calculate the area of a polygon,for example triangle or rectangle or any other polygon,we wanted to
calculated the area of those polygons,because every polygon has the property of height and width so we
calculate the area of this square,triangle or rectangle,in that chapter we have seen inheritance,in class
called shape and a public method set value,and it has member variable which are protected and has
height and width,so we have member variables height,width and area,and we have a member function
for set values is setting whatever values are passed to this

void setValues(int a,int b){

so we have the base class,we have defined derived classes,that are inheriting from my shape base
class,so I have defined a derived class called rectangle class which is inheriting from the base class that is
shape class

class rectangle : public shape

in class rectangle we have only 1 member method here this calculate the area of the rectangle

class rectangle : public shape

public:
int area(){

return (height*width);

};

And how we are calculating the area of the rectangle,because we are inheriting from the base class
shape the member function,the public and protected member function are available in the derived class
rectangle,that is why we include the member function like height and width and multiply height and
width in the derived class and calculate the area,similarly we are creating a class for triangle,which also
has 1 member function like calculating the area of triangle,and the area of triangle is (height*width)/2
and because we are also inheriting from the shape class to triangle class also,so the member variable
and member functions are available in this function also this,so this gives the area of triangle in the
triangle class and the area of rectangle in rectangle class,we can set the height and width here this
polymorphim is having many forms,I want to define my triangle class and rectangle class in terms of the
shape class,first I will define the object of rectangle class

Int main()

Rectangle rec;

Triangle tri;

So what I am going to do is I will create an instance of base class,I will call it polygon,I will define a
pointer,this pointer points to the address of the rectangle class,to the object of the rectangle class

Int main()

Rectangle rec;

Triangle tri;

Shape *poly=&rec

We use & rec which is the address of the object rec,so a pointer is a variable that points to the address
of another variable rec,why we are able to do this because there is property in inheritance is that when
you inherit from the base class to the derived class you can define the object in terms of derived class
object

Int main()

Rectangle rec;

Triangle tri;

Shape *poly1=&rec;

Shape *poly2=&tri;

We are defining a pointer that points to the address of the variable class,so this is polymorphism what
you have done is you have defined a class,*poly1 in terms of another class & rec,so poly1 and shape has
many forms,so once it has rectamgle form,&rec and once it has triangle form,&tri,so polymorphism is
having many forms,so you can define the poly1 object or polygon1 object or the shape object in terms of
triangle also this,&tri,so what we can do is that,we can define the poly1 object,suppose whan we define
a pointer to a class

We write

poly1->setValues(10,20);

poly2->setValues(10,20);

we can write the rectangle object.the area member function that is rec.area()

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

so we have this

Int main()

Rectangle rec;

Triangle tri;

Shape *poly1=&rec;

Shape *poly2=&tri;

poly1->setValues(10,20);
poly2->setValues(10,20);

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

};

class triangle : public shape

{
public:

int area(){

return (height*width/2);

};

Int main()

Rectangle rec;

Triangle tri;

Shape *poly1=&rec;

Shape *poly2=&tri;

poly1->setValues(10,20);

poly2->setValues(10,20);

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

Output

200

100

So you need to have the hierarchy of classes in terms of inheritance,polymorphism is define a class that
can have many forms,so if you have square class also you can define it in terms of another class

Day 36:Virtual Member Functions and Pure Virtual Functions

We will see what is virtual member functions and what is pure virtual member functions,so to do this
chapter you must know polymorphism,so virtual member functions are generally used when you are
using polymorphism,so we will take the program from last chapter to show the virtual member
function,in the previous chapter we have define base class shape,we wanted to calculate
Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

Public:

void setValues(int a,int b){

width=a;

height=b;

Virtual int area()

Return 0;

Protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

};

class triangle : public shape

public:
int area(){

return (height*width/2);

};

Int main()

Rectangle rec;

Triangle tri;

Shape *poly1=&rec;

Shape *poly2=&tri;

poly1->setValues(10,20);

poly2->setValues(10,20);

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

We see that the base class has the member variables in protected and member function setValues in
public,which we use to calculate the area of the triangle,we are setting the values of height and
width,we also defined the derived class rectangle which is inheriting from the base class,that is shape
class,and we have only 1 function area in the derived class to calculate the area of the rectangle,so the
member functions are available to the derived class from the base class which are public or protected
members,similiarly we have triangle class to calculate the area of the triangle,we have the shape class
from which it is inheriting as the rectangle class is also inheriting from the base class,that is shape class

Virtual member function is the member function that can be redefined in the derived class,you can
define a virtual member function in a base class,our base class is shape class

virtual int area()

Return 0;

So what is the use of defining the virtual member function,your member function has a virtual function
in the base class,why the redefinition of this virtual member function in the derived class,we have virtual
member function area we can redefine the virtual member function in the derived class rectangle,we
calculate the area,so we can redefine the virtual function in triangle class and rectangle class,by
redefinition is is that the name of function is same and the prototype of the function is same,but the
implementation is diferent

class rectangle : public shape

public:

int area(){

return (height*width);

};

the prototype is same

Virtual int area()

Return 0;

Definition is different in case of triangle we are calculating area height*width/2 and for rectangle we are
calculating area =height*width

So the basic use of virtual function is to tell c++,that we have defined this function as virtual function
because we want to redefine this function in my derived class,and we want to redefine the definition of
this virtual function in this in the derived class according to the need of the derived class

class rectangle : public shape

public:

int area(){

return (height*width);

And virtual member function we can use this whenever you need to declare this is the main class
suppose you need the instance of poly

Int main()
{

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

poly1->setValues(10,20);

poly2->setValues(10,20);

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

We have defined the instances of my derived class rectangle and triangle

Rectangle rec;

Triangle tri;

And this we also call it the instance of the base class poly

shape *poly1=&rec;

shape *poly2=&tri;

poly1->setValues(10,20);

poly2->setValues(10,20);

according to polymorphism we can point to the derived class using the base class,the pointer *poly1 has
the reference of my derived class object

shape *poly1=&rec;

similarly we have this

shape|*poly2=&tri;

and we have the base class which is pointing to the base class itself

shape*poly3=&poly;

Int main()
{

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

shape*poly3=&poly;

poly1->setValues(10,20);

poly2->setValues(10,20);

poly3->setValues(10,20)

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

std: :cout<<poly.area()<<std: :endl;

And we can set the values of height and width here this

Public:

void setValues(int a,int b){

width=a;

height=b;

and we can calculate the area of specific class

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

std: :cout<<poly.area()<<std: :endl;

Program

# include<iostream>

# include<string>
Using namespace std;

///polygon // square triangle rectangle

Class shape

public:

void setValues(int a,int b){

width=a;

height=b;

virtual int area()

return 0;

protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

};

class triangle : public shape

public:

int area(){

return (height*width/2);

}
};

Int main()

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

shape*poly3=&poly;

poly1->setValues(10,20);

poly2->setValues(10,20);

poly3->setValues(10,20)

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

std: :cout<<poly.area()<<std: :endl;

Output

200

100

we see the are of triangle is 100 and we see the area of rectangle is 200 and the area of polygon is 0,for
polygon because we have defined return for virtual member function as 0,so this is virtual member
function,so what is pure virtual member function is a function which has no definition,now we have
defined the virtual member function like this here this,which is returning 0 this

virtual int area()

return 0;

}
So we have provided a definition to virtualmember function,but if you want to tell that this a pure
virtual member function,you don’t need to provide any definition,so how can you say that this is pure
virtual function,you only need to assign 0 to this function,that is this

virtual int area()=0;

so this is a pure virtual member function,you don’t have to give the definition of this pure virtual
member function in the base class,we define the virtual member function in our derived classes like
this,so it is a way of telling that you have these function in the base class and we can redefine it in the
derived class according to the need of the derived classes,so this is how you can define a virtual member
function,now suppose we don’t give definition of the derived class rectangle here this

class rectangle : public shape

public:

we remove the area of rectangle statement form the main statement

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

public:

void setValues(int a,int b){

width=a;

height=b;

virtual int area()

return 0;

}
protected

Int height;

Int width;

class rectangle : public shape

public:

};

class triangle : public shape

public:

int area(){

return (height*width/2);

};

Int main()

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

shape*poly3=&poly;

poly1->setValues(10,20);

poly2->setValues(10,20);

poly3->setValues(10,20)

std: :cout<<tri.area()<<std: :endl;

std: :cout<<poly.area()<<std: :endl;

When we compile this it gives error


Cannot declare variable poly to be the abstract type shape

This is the error because we have not given the definition of pure virtual function area in the rectangle
class,so if you define a pure virtual member function in the base class,you need to redefine it in the
derived class like rectangle otherwise it will give error,so we have not defined the area member function
in the rectangle class

Class rectangle: public shape

That is why it is giving error,so once you define a virtual member function in the base class it makes your
class an abstract class

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

public:

void setValues(int a,int b){

width=a;

height=b;

virtual int area()

return 0;

protected

Int height;

Int width;

class rectangle : public shape

{
public:

int area(){

return (height*width);

};

class triangle : public shape

public:

int area(){

return (height*width/2);

};

Int main()

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

shape*poly3=&poly;

poly1->setValues(10,20);

poly2->setValues(10,20);

poly3->setValues(10,20)

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

std: :cout<<poly.area()<<std: :endl;

So abstract class is a normal class but it is only the definition of the class,so the abstract class is very
similar to the no implementation of the area function that is given in the pure virtual member
function,so when you give the pure virtual member function in the base class the base class provides
only the prototype of the function and the derived class provides the definition,and the area in pure
virtual member function has no definition

Program

# include<iostream>

# include<string>

Using namespace std;

///polygon // square triangle rectangle

Class shape

public:

void setValues(int a,int b){

width=a;

height=b;

virtual int area()

return 0;

protected

Int height;

Int width;

class rectangle : public shape

public:

int area(){

return (height*width);

}
};

class triangle : public shape

public:

int area(){

return (height*width/2);

};

Int main()

Rectangle rec;

Triangle tri;

shape *poly1=&rec;

shape *poly2=&tri;

poly1->setValues(10,20);

poly2->setValues(10,20);

std: :cout<<rec.area()<<std: :endl;

std: :cout<<tri.area()<<std: :endl;

So while using pure virtual member function poly cannot point to the base class poly itself this

Day 38: C++ Function Templates

In this chapter we will see what are function templetes and how we can use function templates in c++,so
templates are the foundation of generic programming,for example if you want to make your program
more generic to increase the usability of the program,then you use templates,for example,suppose we
want to make a function which adds two values,so we can make a function which returns an integer and
we can pass int a,int b we are passing two arguments,and we return a+b
Program

# include<iostream>

#include<string>

using namespace std;

int add(int a,int b)

return a+b;

Int main()

and we calculate the addition of two values,in the main we can call two values that is

int x=36;

int y=48;

Program

# include<iostream>

#include<string>

using namespace std;

int add(int a,int b)

return a+b;

Int main()

Int x=36;

Int y=48;

}
Std: : cout<<add()

Then we can call the add function

Program

# include<iostream>

#include<string>

using namespace std;

int add(int a,int b)

return a+b;

Int main()

Int x=36;

Int y=48;

Std: : cout<<add(x,y)<<std: : endl;

Output

83

But for example we want to add this so this is adding integer values

Int add(int a,int b)

So you cannot use doble values or float values or string values with this function because the data type
is fixed with this function,suppose you want to make a generic calculator and you want to add a function
like this

Int add(int a,int b)


It can accept two double or any two integer values,so what you can do is that you can overload this
function

int float(float a,float b)

return a+b;

int double(double a,double b)

return a+b;

Program

# include<iostream>

#include<string>

using namespace std;

int add(int a,int b)

return a+b;

int float(float a,float b)

return a+b;

int double(double a,double b)

return a+b;

}
Int main()

Int x=36;

Int y=48;

Std: : cout<<add(x,y)<<std: : endl;

So it is the purpose to make single function generic,so this is becoming more code so to make the
function generic we can use function templates,we can do is we can use the function name above the
function name template

Program

# include<iostream>

#include<string>

using namespace std;

template<class dataType>

int add(int a,int b)

return a+b;

Int main()

Int x=36;

Int y=48;

Std: : cout<<add(x,y)<<std: : endl;


}

So we need to give the template class name as data type,so in our case we have to replace the int with
data type is the statements after this

Program

# include<iostream>

#include<string>

using namespace std;

template<class dataType>

dataType add(dataType a,dataType b)

return a+b;

Int main()

Int x=36;

Int y=48;

Std: : cout<<add(x,y)<<std: : endl;

So what this program is doing is that we are telling c++ using the template that we want to make this
function generic

dataType add(dataType a,dataType b)

so this data type will be replaced in the function with what we are initializing,so we can define float
values or doble values and it will initialize with that data type and we don’t need to define another code
for these data type

Program
# include<iostream>

#include<string>

using namespace std;

template<class dataType>

dataType add(dataType a,dataType b)

return a+b;

Int main()

double x=36.763;

double y=48.899;

Std: : cout<<add(x,y)<<std: : endl;

Output

83.898

Till the purpose of the code function data type is same,so there a thing that the dataType is same in the
template and the function,dataType add

template<class dataType>

dataType add(dataType a,dataType b)

so what if x is an integer and y is a double value

Program

# include<iostream>

#include<string>
using namespace std;

template<class dataType>

dataType add(dataType a,dataType b)

return a+b;

Int main()

int x=36.763;

double y=48.899;

Std: : cout<<add(x,y)<<std: : endl;

So we cannot pass two different dataType in main to the same function above,that is this function

template<class dataType>

dataType add(dataType a,dataType b)

if you define double after the main then all the argument in the above function takes double values,or if
you want to give two integer values you can define two integer values,error no matching function for
call to add(int,& double),so when you are passing two arguments you need to give the same data type
to the main function,there is another way of passing the parameters to the function templates,that we
will see in next chapter

Day 38:C++ Function Templates with Multiple Parameters

In the previous chapter we have seen how we can use function templates which takes 1 parameter,and
we have seen that we can use single data type for this,so we have used function parameter as dataType
in the template class,so when we use function parameter,in the data type you need to give single value
in this,so you need to give the single data type value to this function,so we have to pass the same
datatype in the template and the after statements and we cannot pass two different data types after the
main(),so we can pass two values in templates suppose we want to pass the maximum of two values,so
we want that the two variables in the function above can be different like integer and float and integer
and double any values this,suppose I want to use two operators in c++ and we want to use this

Program

# include<iostream>

#include<string>

using namespace std;

template<class dataType>

dataType add(dataType a,dataType b)

return (a>b?a : b);

Int main()

int x=36.763;

double y=48.899;

Std: : cout<<add(x,y)<<std: : endl;

So what this is that

return (a>b?a : b);

in this condition if a>b is true it returns a and if the condition is false it returns b

suppose we want to pass first data type as first argument to the function and second data type as
second argument to the function
Program

# include<iostream>

#include<string>

using namespace std;

template<class first,class second>

first max(first a,second b)

return (a>b?a : b);

Int main()

int x=36.763;

double y=48.899;

Std: : cout<<max(x,y)<<std: : endl;

Output

48.899

Now suppose you want to change the data type after the main then you can do it like this

Program

# include<iostream>

#include<string>

using namespace std;

template<class first,class second>

first max(first a,second b)

{
return (a>b?a : b);

Int main()

float x=36.763;

int y=48;

Std: : cout<<max(x,y)<<std: : endl;

Output

48

And in this way you can pass multiple parameter to your function template,and you can use multiple
parameters

Day 39:Class Templates

In the previous chapter we have seen how to use function template in c++,in this chapter we will see
how we can use templates with classes,we will see how to use class templates in c++,first of all how to
declare a template class,like declaring a template function you need

Template<class T>

We are giving the data type as T

We will give the class name

Class Maths{
};

In the maths class we have two variables and because we have this,and since this data type T is the
initialization of my class template,so I can define my variables

Program

# include<iostream>

#include<string>

using namespace std;

template<class T>

class Maths{

T a,b

};

Int main()

So we will replace this T in T a,b for whatever initialization tou give in the template class like int or
float,now we will define a public method

Public:

And we will add a constructor to the class maths

Public:

Maths(){

};

So this data type is T,so since T is a dataType for a and b

So we have x is the variable name and T is the data type


Program

# include<iostream>

#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;

public:

Maths(T,x,T,y){

};

Int main()

So we can initialize this

Then we will say a=x;

b=y;

Program

# include<iostream>

#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;
public:

Maths(T,x,T,y){

a=x;

b=y;

};

Int main()

We are initializing the constructor by two arguments and we are setting the values of a and b from these
arguments

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

We will find the maximum of these values a and b

T maxValue();

For defining the implementation what we will do is that,for class implementation,class member function
implementation,what you do is write the name of the class,Maths: :

Maths: : maxValue()

Then you can call the function maxValue this,but because we are using templates in our case,so
returning T here this returing class templates

T Maths: :maxValue(){

}
Int main()

Program

# include<iostream>

#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

};

T Maths : : maxValue(){

Int main()

So whenever we define class template we need to define this signature of the class template

template<class T>

everywhere

so we define this class template above the function T Maths : : maxValue(){

Program

# include<iostream>
#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

};

template<class T>

T Maths : : maxValue(){

Int main()

We need to use this

T Maths<T> : : maxValue(){

which tells c that we are using the member function of a class of Data type T in <T>,we need to initialize
the member function with template keyword,and then we put the angled bracket and the data type
T,that is <T>,now we will return maximum value and we can calculate maximum value by ternary
operator function

return(a>b?a:b);

Program

# include<iostream>
#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

};

template<class T>

T Maths<T>: : maxValue(){

return(a>b?a:b);

Int main()

Maths mat;

Now in order to use the instance of the class,to initiate our class,we can do this maths class in the main
and then

Int main()

/***Maths mat;***/

/****Maths<T> mat;****/

Maths<int> mat;
}

It gives error because whenever you use class template,you have to give the angled brackets T that is
this <T>this T will be replace dby the value or data type you pass in T,for example

T int,so this int will be replaced here this above in this ,template<class T> after using namespace std,and
this T will instantiate this two a and b variables

class Maths{

T a,b;

This T will be instantiated as an int variable in this

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

And then it will call this Maths maxValue member function

T Maths<T>: : maxValue(){

And then it will calculate the maximum of the values

We can give value as 45 here this

Maths<int> mat(45,67);

And because it is returning a value we can calculate maxValue

T Maths<T>: : maxValue(){

Then we can give this

Int main()

Maths<int> mat(45,67);

Cout<<mat.maxValue()

We have the instance of the class or the object of the class maths as mat.

Program

# include<iostream>
#include<string>

using namespace std;

template<class T>

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

};

template<class T>

T Maths<T>: : maxValue(){

return(a>b?a:b);

Int main()

Maths<int> mat(45,83);

Cout<<mat.maxValue();

Output

83

Now to instantiate these a and b as double values this

Program
# include<iostream>

#include<string>

using namespace std;

template<class T>/****class template is instantiated as a function template****/

class Maths{

T a,b;

public:

Maths(T,x,T,y){

a=x;

b=y;

T maxValue();

};

template<class T>/**** definition of the member function of the class****/

T Maths<T>: : maxValue(){

return(a>b?a:b);

Int main()

Maths<double> mat(45.798,83.799);

Cout<<mat.maxValue();

Output

83.799

So class template is instantiated like a function template


And whenever you provide the definition of the member function of the class so this template is there
also the

Day 40:Template Specialization in C++

We will see here this template specialization in template class,we will create a class template and we
have this and ten we will make a class called char finder class

Program

# include<iostream>

#include<string>

Using namespace std;

template<class T>

class charFinder{

};

Int main()

So it will have a public constructor,public charFinder

Program

# include<iostream>

#include<string>

Using namespace std;

template<class T>
class charFinder{

public:

charFinder(T,a){

cout<<a<<” is not a valid char”<<endl;

};

Int main()

Suppose we want to specialize a template class,specialization is that you can redefine a class,specialized
in a particular data type,for example we want to specialize a char fincdr class,in order to find a character
or specialize a character so ewhat I need is this,what I can do is I can redefine a class and what we can
say c++ is that,I want to specialize the other class that has the same name,with the character
specialization and how you can do this,and what you can do to make this other class as character
specialization template,you need to remove this template declaration class,don’t give any declaration in
this class template<>

Program

# include<iostream>

#include<string>

Using namespace std;

template<class T>

class charFinder{

public:

charFinder(T,a){

cout<<a<<” is not a valid char”<<endl;

}
};

template<>

class charFinder{

public:

charFinder(T,a){

cout<<a<<” is a valid char”<<endl;

Int main()

So we will tell c++ that we will make this another class as a specialization of another class,we can do this
for specializing a class by this specifying the specific arguments to the data type in this

charFinder(T,a){

this will be

charFinder(char , a){

and we will put a is a valid character

this way you can specialize a class for a particular data type,the first class is general template and second
class is class template which specialize in character that is char data type and in order to use this second
class what you need to do is this,we can declare the instance of this class

in the bracket we can say

int main()

charFinder<char>

so when you give char it is that you will initialize a specialized instance of this second class

we can write this


int main()

charFinder<char>cha1(‘A’);

charFinder<int>cha1(83);

charFinder<float>cha1(83.799);

Program

# include<iostream>

#include<string>

Using namespace std;

template<class T>

class charFinder{

public:

charFinder(T,a){

cout<<a<<” is not a valid char”<<endl;

};

template<>

class charFinder{

public:

charFinder(T,a){

cout<<a<<” is a valid char”<<endl;

int main()

{
charFinder<char>cha1(‘A’);

charFinder<int>cha1(83);

charFinder<float>cha1(83.799);

So we will complile the program,so it will give error so whenever you leave this template blank you need
to give the data type for the class for which you are specializing

template<class T>

class charFinder{

template<class T>

class charFinder<char>

So char is the data type in which you need to specialize the class,we will leave this angled gtemplate
bracket blank but after the class name,charFinder you need to give the data type that is char,<char>

Program

# include<iostream>

#include<string>

Using namespace std;

template<class T>

class charFinder{

public:

charFinder(T,a){

cout<<a<<” is not a valid char”<<endl;


}

};

template<>

class charFinder<char>{

public:

charFinder(T,a){

cout<<a<<” is a valid char”<<endl;

int main()

charFinder<char>cha1(‘A’);

charFinder<int>cha2(83);

charFinder<float>cha3(83.799);

Output

A is a valid char

83 is not a valid char

83.799 is not a valid char

So what it has done is that,so when you define this instance of charFinder class specialized in character

charFinder<char>cha1(‘A’);

so this then goes to the second class which is specialized in the character class,so it will know that char is
the specialization of this the second template class,so it will print the second class template,A is a valid
char,and then in any other case it will take T as the data type and it will go te first class

template<class T>

class charFinder{
public:

charFinder(T,a){

cout<<a<<” is not a valid char”<<endl;

};

And print is not a valid character,from the general template class

In this way you can specialize a class in order to do the task for a similar data type

Day 41:Create a Text File and Write in it

In this chapter we will see how we can create a text file and how we can write in it,there are three
classes in c++ which we can use to input and output the characters in c++ and these are

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

Using namespace std;

Int main()

std: : cin.get();

return 0;

So from the three classes we will include this fstream

Program
///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

using namespace std;

Int main()

std: : cin.get();

return 0;

Now to create a file we know that we use this ofstream,so we will use this ofstream and we can take the
instance of this class,for example we can name this so the instace of the class ofstream we will take a s
file

Int main()

ofstream file_;

std: : cin.get();

return 0;

To create the file we will take this instance of ofstream that is file_.open(); it takes a constant character
string as an argument which we will give as the name of the text file

Int main()

ofstream file_;

file_.open(“mytext.txt”);
file_.close();

std: : cin.get();

return 0;

So when you open your file you need to close the file it does not take any argument

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

using namespace std;

Int main()

ofstream file_;

file_.open(“mytext.txt”);

file_.close();

std: : cin.get();

return 0;

We will complie the program and hen we will go to the project folder,which will contain my project files
and bin will contain binary files

vids-MyFirstProg-bin
Debug

So it will show debug if you are in debug mode in the complier

Debug-MyFirstProg

We have used this,std: : cin.get();

Other wise the screen will not show,if it goes out of the scope

When we click on MyFirstProg file it creates mytext file

Debug-

MyFirstProg

Mytext

We will include messge in the file_ instance

Int main()

ofstream file_;

file_.open(“mytext.txt”);

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;

file_.close();

std: : cin.get();

return 0;

After compliling the program we go to MyFirstProg and click on the file to execute the output does not
give any message

And then we click on mytextfile it gives the message

this is my first text file 1


this is my first text file 2

this is my first text file 3

this is my first text file 4

in this way we can create a file and write into this,and generally there is 1 more best practice that that
will use this that is

if(file_.is open())

this returns a Boolean value if the file is open it returns true and if the file is closed it returns false,so
check if the file is open,then only do execute these statements so it is a best practices

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

using namespace std;

Int main()

ofstream file_(“mytext.txt”);

/***file_.open(“mytext.txt”);***/

if(file_.is open())

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;


file_.close();

std: : cin.get();

return 0;

Then we will use this line to create the file

file_.open(“mytext.txt”);

we can use this instead of the above line

ofstream file_(“mytext.txt”);

to open the file

and we can use file_close to close the file

Day 42:How to Read from a .txt File using C++

In the last chapter we have seen how to create a file in c++ and how to write in that text file,in this
chapyet we will see how to read form a text file we have seen the program,we have seen the 3 classes
which we use to create or read form a file,and whenever you want to write in a file you have to use
ofstream,and whenever you want to read form a class you have to use ifstream class,so we will use
ifstream class in this file,so we will get started

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

using namespace std;


Int main()

/*******ofstream file_(“mytext.txt”);

if(file_.is open())

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;

file_.close();

}********/

std: : cin.get();

return 0;

We will write a new code to read the text file,so mytext file is in my project folder,we want to print each
line and we want to print each line into the terminal so how we can do this

First we will declare a string variable whose every line we are going to read,so what we are going to do is
that

# include<string>

And we will include a string variable

Std: :string line_;

and in the next line to read the file

ifstream file_(“mytext.txt”);

this line opens the textfile but we will check if the text file is open this

Std: :string line_;

ifstream file_(“mytext.txt”);

if (file_ .is_open())
{

file_.close();

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

#include<String>

using namespace std;

Int main()

/*******ofstream file_(“mytext.txt”);

if(file_.is open())

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;

file_.close();

}********/

Std: :string line_;

ifstream file_(“mytext.txt”);

if (file_ .is_open())
{

file_.close();

std: : cin.get();

return 0;

There is a function in string class called getline,this takes two arguments,this is the overloaded function
we can pass two arguments first the file instance that we have created that is file_ and the second
argument as line which is the string variable

if (file_ .is_open())

While(getline(file_, line_);

file_.close();

std: : cin.get();

return 0;

So what this getline function will do is it will read the file line by line and then the string variable line by
line

While(getline(file_, line_);

So it will read the first lineor first argument of getline function then transfer into this variable line_
which is the second argument of getline function

if (file_ .is_open())

While(getline(file_, line_);

Std: :cout<<line_<<’\n’;
}

file_.close();

std: : cin.get();

return 0;

In the while loop we will print the statement cout line_and in case the file is not open it will print the
message the file is not open this

else

std: :cout<<file is not open”<<’\n”;

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

#include<String>

using namespace std;

Int main()

/*******ofstream file_(“mytext.txt”);

if(file_.is open())

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;


file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;

file_.close();

}********/

Std: :string line_;

ifstream file_(“mytext.txt”);

if (file_ .is_open())

While(getline(file_, line_);

Std: :cout<<line_<<’\n’;

file_.close();

else

std: :cout<<file is not open”<<’\n”;

std: : cin.get();

return 0;

Output

this is my first text file 1

this is my first text file 2

this is my first text file 3

this is my first text file 4

suppose we want to read a custom data from the file,we have the custom data

mytext
1 mark 16

2 trot 13

3 micheal 16

So in 1 mark 16

First word is integer,second word is string and third word is integer

We will save the data in mytext-file-save

We will close the mytext file so we want to read the data one by one so how we can do that

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

#include<String>

using namespace std;

Int main()

/*******ofstream file_(“mytext.txt”);

if(file_.is open())

file_<<”this is my first text file 1\n”;

file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;


file_.close();

}********/

ifstream file_(“mytext.txt”);

int id;

std: : string name;

int age;

if (file_ .is_open())

While(getline(file_, line_);

file_.close();

else

std: :cout<<file is not open”<<’\n”;

std: : cin.get();

return 0;

We will add these lines to the program

int id;

std: : string name;

int age;

and instead of this while

While(getline(file_, line_);

We will give this while(file_>>)

In case of writing to a file we used this angled brackets<<

In case of reading from a file we use this angled bracket>>


While(file_>>id>>name>>)

We will give the string variable name after the id and then we will give age

While(file_>>id>>name>>age)

What it will do that it will read the text file line by line abd the first word that is there is this stored in
this id variable the second word will be stored in the name variable and the third word will be stored in
the age variable

While(file_>>id>>name>>age)

Std: :cout<<id<<” “<<name<<” “<<age<<’\n’;

Program

///ofstream: stream class to write in files

///ifstream:stream class to read form files

///fstream:stream class to both read and write to/from files

# include<iostream>

#include<fstream>

#include<String>

using namespace std;

Int main()

/*******ofstream file_(“mytext.txt”);

if(file_.is open())

file_<<”this is my first text file 1\n”;


file_<<”this is my first text file 2\n”;

file_<<”this is my first text file 3\n”;

file_<<”this is my first text file 4\n”;

file_.close();

}********/

ifstream file_(“mytext.txt”);

int id;

std: : string name;

int age;

if (file_ .is_open())

While(file_>>id>>name>>age)

Std: :cout<<id<<” “<<name<<” “<<age<<’\n’;

file_.close();

else

std: :cout<<file is not open”<<’\n”;

std: : cin.get();

return 0;

Day 44:How to add C++ 13 support to code: : blocks compiler

We have been learning basic functionalities of c++,but c++ has evolved,a newer version of c++ is
released called c++13,best features are used in this c++13,so code blocks by default c++13 features are
not enabled so in c++13 a new keyword was introducted called auto this auto which works like default
data type,suppose we can define a variable with data type auto and then,with the initialization of this
variable the data type of variable a as 42 it will be taken as int suppose we have a=42.38 it will be
automatically taken as data type float

Program

#include<iostream>

#include<thread>

using namespace std;

int main(){

auto a=42;

auto b=42.38;

return 0;

So this auto will recognize that what you initialize your variable by as a integer variable,or float variable
or string variable this

When we compile the program it gives an error

The file requires compiler and library support for ISO C++13 standard

Which is not by default enabled in your code blocks so in order to enable this in the code blocks go to
settings-compiler-compiler settings

See that the compiler is set

Selected compiler-GNU GCC Compiler

Then go to Compiler Flags

-Categories

All categories

You will see this

Have g++ follow C++13 ISO C++ Language standard[-std=c++13]

Check this click enter


And now when we compile the program program will work

Day 44:C++ Vectors

In this chapter we will see what is vectors in c++,so vector is a sequential container same as the array,so
array can contain more that 1 element of same data type,at the same time similarly you can use vectors
to contain collection of data which is of same data type but,there is a difference between array and
vectors,so whenever you define an array like this you need to define the size of the array

Program

#include<iostream>

Using namespace std;

Int main()

Int myarray[3]={10,20,30};

Return 0;

You have to initialize with some size it is difficult to change the size of the array dynamically,but while
using vectors you can change the size of the vectors dynamically,so that is the main difference between
arrays and vectors,but vectors comes with their own features or functionalities which can be used in a
much broader way that the array,so to declare a vector you need to include a vector library

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

Int myarray[3]={10,20,30};
Return 0;

And then to declare a vector you need to call std: :vector<int>

And in the angular brackets you need to give thye data type,suppose we want to have the collection of
integer variables we will give int data type

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>

Return 0;

Then we will give name of the vector

std: :vector<int>my_vec

or you can initialize the vector with some size suppose you give 10

std: :vector<int>my_vec(10)

you can store 10 values in this vector or you can give no values and you can add values to a vaector
dynamically,to add values to the vector you need to call this method

my_vec.push_back()

we use this add the value element to the vector from the back

Program
#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

return 0;

So similar to array the index of vectors start from 0 then 1,2,3 in this case

And to get the size of the vectors,the size of the vectors can be changed dynamically

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);
cout<<”vector size=”<<my_vec.size()<<endl;

return 0;

Output

Vector size=4

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

cout<<”vector size=”<<my_vec.size()<<endl;

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;

return 0;

}
Output

Vector size=2

Vector size=4

So the size of the vector can be changed dynamically

Now to iterate the values in the vector we can use for loop

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec[ i ]<<endl;

/***cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;***/

return 0;

}
Output

vector size=4

vector 0 10

vector 1 20

vector 2 30

vector 3 40

you can also use my_vec at and get the same result

now to erase any value from the vector you can

my_vec.erase() when you move over this it takes the position of the element to be erased

my_vec.erase(my_vec.begin())

when you give this it is that you want to give the vector and delete the first vector

suppose 10 is the first value of the vector and you want to delete this then this will indicate the first
value of the vector this

Program

#include<iostream>

#include<vector>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;
for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

my_vec.erase(my_vec.begin())

cout<<endl<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

return 0;

Output

vector size=4

vector 0 10

vector 1 20

vector 2 30

vector 3 40

vector 0 20

vector 1 30

vector 2 40

similarly you wan use this my_vec.erase(my_vec.end())

suppose you want to delete this 40 from the vector

you can use endl directly we can use this

my_vec.erase(my_vec.begin() +3);

this is that it will delete the index of the element in the vector at 3
so the output will be

vector 0 10

vector 1 20

vector 2 30

we will add another library called include algorithm that has method called std remove

Program

#include<iostream>

#include<vector>

#include<algorithm>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

/***my_vec.erase(my_vec.begin() +3);***/

my_vec.erase(std: :remove(my_vec.begin(),my_vec.end,30.my_vec.end());

cout<<endl<<endl;
for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

return 0;

Std: :remove is a function which can be used to remove some value from the vector,and then

std: :remove(); and then in the brackets it takes three values the first value the second value and the
value itself

output

vector size=4

vector 0 10

vector 1 20

vector 2 30

vector 3 40

vector 0 10

vector 1 20

vector 2 40

so this has removed thevalue 30,so we have seen how to erase value and erase value based on the value
number,how to erase on the basis of index,suppose you want to remove all the values from the vector
this

Program

#include<iostream>

#include<vector>

#include<algorithm>

Using namespace std;

Int main()
{

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

/***my_vec.erase(my_vec.begin() +3);***/

/***my_vec.erase(std: :remove(my_vec.begin(),my_vec.end,30.my_vec.end());***/

My_vec.clear();

cout<<”vector size=”<<my_vec.size()<<endl;

cout<<endl<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

return 0;

Output

vector size=4

vector 0 10

vector 1 20

vector 2 30
vector 3 40

vector size=0

Program

#include<iostream>

#include<vector>

#include<algorithm>

Using namespace std;

Int main()

std: :vector<int>my_vec

my_vec.push_back(10);

my_vec.push_back(20);

my_vec.push_back(30);

my_vec.push_back(40);

cout<<”vector size=”<<my_vec.size()<<endl;

for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

/***my_vec.erase(my_vec.begin() +3);***/

/***my_vec.erase(std: :remove(my_vec.begin(),my_vec.end,30.my_vec.end());***/

/***My_vec.clear();***/

cout<<endl<<endl

cout<<”is vector empty =”<<my_vec.empty()<<endl;


for(int i=0 ; i<my_vec.size() ; i++)

cout<<”vector”<<i<<” “<<my_vec.at(i)<<endl;

return 0;

vector size=4

vector 0 10

vector 1 20

vector 2 30

vector 3 40

is vector empty 0

vector 0 10

vector 1 20

vector 2 30

vector 3 40

so the vector is not empty when you include the clear in the program,it will remove all the elements and
then the is vector empty 1,is true so the vector is empty

so there are many functions in vectors

my_vec.

Erase,add back,pop back,so you can select and try these functions

Day 45:C++ Map

We will see her what are std maps and how to use maps in c++,so map or maps are associated
containers that stores elements formatted by the combination of key values and mapped values,so
unlike vectors that maintains their values on the basis of index,the maps maintain their values on the
basis of key,so maps are associated containers and if you have learned about associated arrays or
associated sets,you will know that in association of sets or the association of arrays,there is a key and on
the basis of key you can assign a value to the container,so we will see the program,you have to include
the library function map in order to use map

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string

return 0;

for first argument in the angular brackets is key data type as int,float,so here we will use std map int and
the values std string,so we create map for student id,so we will map out integer and that will be the key
of our map,and the names we will save as strings,so lets name our,now name our map variable as

name_map

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

return 0;

now to insert values in a map take a variable,name_map and in the square brackets provide the key
Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1]

return 0;

because first data type we have defined as key data type, std: :map<int>,the data type is int,so in the
square brackets we will assign the key suppose 1 in this case then we will assign value by giving this
equal to sign,similarly we can assign more elements to the map

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;
name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

return 0;

so the numbers 1,2,3,4,5 are keys of the map and the

now depending upon the key you can access the values,for example you want to access the value of the
map at key 4 you can write

std: :cout<<name_map and then you can call the key using the using the square bracket

std: : cout<<name_map[3]<<std: :endl;

return 0 ;

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

std: : cout<<name_map[3]<<std: :endl;

return 0;
}

Output

Micheal

Because maps are associative,you cannot provide duplicate keys,for two values so from this you see that

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map[5] = ”Trotytyt tyt”;

std: : cout<<name_map[4]<<std: :endl;

return 0;

So here the last assignment of map 5 that is trotytyt tyt will be preffered

Program
#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[4] = ”Trotyt” tyt;

name_map[5] = ”Trotytyt”;

std: : cout<<name_map[4]<<std: :endl;

return 0;

In case of same key assignment we can do this the last key assignment with Trotyt tyt will be considered

Output

Trotyt tyt

So we cannot duplicate keys in the map,now in order to iterate over the map we can do this,what you
can do is you can use an iterator,there is a special class called iterator and using the for loop we use the
map

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Then we will give values to the iterator,in the same way you can provide and so this is called the iterator
and we can iterate over the values like this,so first of all iterator,can iterate over the values using the key
Std: : cout<<it.first<< “ -> “<<it.second<<std: :endl;

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

std: : cout<<name_map[4]<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it.first<< “ -> “<<it.second<<std: :endl;

return 0;

So there was a error so instead of it.first we will write it->first because it is pointing to first,it is a pointer

Program

#include<iostream>

#include<map>
using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

std: : cout<<name_map[4]<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

output

Trotyt tyt

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

So it will iterate over whole map and show the value and you can also print the size of map

Program
#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

std: : cout<<”map size=”<<name_map size()<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Output

Map size =5

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt
So the size function returns you the size of the map,there is another function called erase,let us see the
function clear as we have seen that clear,clears the map

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.clear();

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Output

Size of map=0
so if you comment the map.clear() you can see the map elements

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

/***name_map.clear();***/

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Map size =5

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt
5=> Trotytyt

So there are other ways to insert the values to a map,that is using the function called insert so the name

name_map.insert(std: :pair<>)

Using this std: : pair you can create a pair of two data types,We can create integer and string pair

So our map is integer and string pair,std: :map<int> , std: : string>name_map;

name_map.insert(std: :pair< std<int , std: : string> )

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

{
Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Output

Map size =7

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

6=> Trotyt tyt

7=> Trotyt tytyt

Now suppose you want to insert another value here this

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;
name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

name_map.insert(std: :pair< std<int , std: : string>(8,Trotyt tytytytyt )

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

For(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Output

Map size =7

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

6=> Trotyt tyt

7=> Trotyt tytyt

8=>Trotyt tytytytyt

Suppose you want to search a value function in a map,you can call a function in the map

For finding a thing in the map you have to define an iterator like this

std: :map<int,std: :string>: :iterator it


Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: :map<int,std: :string>: :iterator it=name_map.find(5);

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

}
You can assign the name to the iterator,name map find 5,suppose you want to find the key 5 in this map
so you can find this,and you can find the key using this iterator

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: :map<int,std: :string>: :iterator it=name_map.find(5);

std: : cout<<”key found-”<<it->second<<std: :endl;

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

}
return 0;

So it will store the value in the map 5

std: :map<int,std: :string>: :iterator it=name_map.find(5);

and using this iterator it you can find the second value this

output

key found=Trotytyt

Map size =7

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

6=> Trotyt tyt

7=> Trotyt tytyt

Suppose you want to find the key at position 4 then

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;


name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: :map<int,std: :string>: :iterator it=name_map.find(4);

std: : cout<<”key found-”<<it->second<<std: :endl;

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

So it will store the value in the map 4

std: :map<int,std: :string>: :iterator it=name_map.find(4);

and using this iterator it you can find the second value this

output

key found=Trotyt

Map size =7
1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

6=> Trotyt tyt

7=> Trotyt tytyt

There is 1 more way to do this

Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )


std: :map<int,std: :string>: :iterator it=name_map.find(5);

std: : cout<<”key found-”<<name_map.find(5)->second<<std: :endl;

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Output

key found=Trotyt tytyt

Map size =7

1=> Mark

2=> Trot

3=> Micheal

4=>Trotyt

5=> Trotytyt

6=> Trotyt tyt

7=> Trotyt tytyt

Suppose you want to erase a key at 4

Since we are finding the value at key 5 after that it will erase the value at 5

We will see the output of the program with one deleted for key

Program
#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: :map<int,std: :string>: :iterator it=name_map.find(4);

name_map.erase(it);

/***std: : cout<<”key found-”<<name_map.find(5)->second<<std: :endl;***/

/***name_map.clear();***/

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;

Suppose you want to delete the value where key is 5


Program

#include<iostream>

#include<map>

using namespace std;

int main(){

/***std: :map<std: :string>***/

std: :map<int> , std: : string>name_map;

name_map[1] = ”Mark”;

name_map[2] = ”Trot”;

name_map[3] = ”Micheal”;

name_map[4] = ”Trotyt”;

name_map[5] = ”Trotytyt”;

name_map.insert(std: :pair< std<int , std: : string>(6,Trotyt tytyt )

name_map.insert(std: :pair< std<int , std: : string>(7,Trotyt tytytyt )

std: :map<int,std: :string>: :iterator it=name_map.find(5);

name_map.erase(it);

/***std: : cout<<”key found-”<<name_map.find(5)->second<<std: :endl;***/

/***name_map.clear();***/

std: : cout<<”map size=”<<name_map.size()<<std: :endl;

for(std: :map<int,std: :string>: :iterator it=name_map.begin();it !=name_map.end(); it++)

Std: : cout<<it->first<< “ -> “<<it->second<<std: :endl;

return 0;
}

Since we are finding the value at key 5 after that it will erase the value at 5

We will see the output of the program with one deleted for key 5

There is another function called

std: : cout<<”is empty=”<<name_map.empty()<<std: :endl;

to check if it is empty you can use clear function in the program and it will show empty=1 true

we can see the total number of map elements that is 7,there are othet function which you can

see so this is the function of maps

You might also like