C++ Language Notes
C++ Language Notes
C++ Language Notes
C++ is very close to hardware, so you get a chance to work at a low level which
gives you lot of control in terms of memory management, better performance and
finally a robust software development.
C++ programming gives you a clear understanding about Object Oriented Programming
You will understand low level implementation of polymorphism when you will
implement virtual tables and virtual table pointers, or dynamic type identification.
C++ is one of the every green programming languages and loved by millions of
software developers. If you are a great C++ programmer then you will never sit
without work and more importantly you will get highly paid for your work.
C++ is the most widely used programming languages in application and system
programming. So you can choose your area of interest of software development.
C++ really teaches you the difference between compiler, linker and loader, different
data types, storage classes, variable types their scopes etc.
Object-Oriented Programming (OOPs)
C++ supports the object-oriented programming, the four major pillar of
object-oriented programming (OOPs) used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
Usage of C++
By the help of C++ programming language, we can develop different types of
secured and robust applications:
1. Window application
2. Client-Server application
3. Device drivers
4. Embedded firmware etc.
C++ program :
#include<iostream.h>
#include<conio.h>
Void main()
{
Clrscr();
cout<<“hello students please stay at your home when corona is live.”
getch();
}
Example 2:
#include<iostream.h>
#include<conio.h>
Void main(){
Int a,b;
cout<<“enter two numbers”;
cin>>a>>b;
cout<<a+b;
getch();
}
*
-by kanhaiya lal kumawat
C++ Variable :
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times. It is a way to represent memory location
through symbol so that it can be easily identified.
float 4 byte
double 8 byte
A list of 30 Keywords in C++ Language which are not available in C language are
given below.
asm dynamic_cast namespace reinterpret_cast bool
An operator is simply a symbol that is used to perform operations. There can be many
types of operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C
language.
1. Arithmetic Operators (+,-,*,/,%,++,--)
2. Relational Operators(==,!=,>,>=,<,<=)
3. Logical Operators(&&,||,!)
4. Bitwise Operators(&,|,^,>>,<<)
5. Assignment Operator(=,+=,-+,*=,/=,%=)
6. Ternary or Conditional Operator(?:)
7. Special Operator(sizeof, addressof(&), pointer)
Program for arithmetic operator: Program for relational operator:
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a,b,c; int a,b,c;
clrscr(); clrscr();
cout<<“enter two numbers”; cout<<“enter two numbers”;
cin>>a>>b; cin>>a>>b;
c=a+b; c=a==b;
cout<<c; cout<<c;
getch(); getch();
} }
c=a-b; c=a!=b;
c=a*b; c=a>b;
c=a/b; c=a>=b;
c=a%b; c=a<b;
c=a<=b;
1. Bitwise AND(&) :
In bitwise AND operator first we need to calculate binary of the given
numbers and after it we can perform bitwise and operation.
256 128 64 32 16 8 4 2 1
1 1 10 10
Example for bitwise AND operator : Example for bitwise OR operator :
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a,b,c; int a,b,c;
clrscr(); clrscr();
cout<<“enter two numbers”; cout<<“enter two numbers”;
cin>>a>>b; cin>>a>>b;
c=a&b; c=a|b;
cout<<c; cout<<c;
getch(); getch();
} }
Suppose a=5, b=15 then result : Suppose a=5, b=15 then result :
256 128 64 32 16 8 4 2 1 256 128 64 32 16 8 4 2 1
0101 0101
& 1111 | 1111
----------- -----------
0101 1111
Bitwise XOR operator :
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0
In this operator when all conditions are same then result is false otherwise true.
4. Bitwise right shift(>>) :
bitwise right shift operator is used for shifting number of bits
on the right side. In this operator we need an number and how much bits for shifting
On right side.
Example : How to solve it : 16 bit register
#include<iostream.h> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#include<conio.h>
void main() Suppose number is a=49 so first calculate binary :
{ 64 32 16 8 4 2 1
Int a,b,c; a= 1 1 0 0 0 1
clrscr(); And shifting of bits is 3 because maximum bits we can shift
cout<<“enter an number”; Are 16.
cin>>a;
cout<<“enter number of shifting bits”;
cin>>b;
c=a>>b; Binary put on the register :
cout<<c;
0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1
getch();
}
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0
6
5. Bitwise left shift(<<) :
bitwise left shift operator is used for shifting number of bits
on the left side. In this operator we need an number and how much bits for shifting
On left side.
How to solve it : 16 bit register
Example :
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#include<stdio.h>
#include<conio.h> Suppose number is a=49 so first calculate binary :
void main() 64 32 16 8 4 2 1
{ a= 1 1 0 0 0 1
Int a,b,c; And shifting of bits is 2 because maximum bits we can shift
clrscr(); Are 16.
printf(“enter an number”);
scanf(“%d”,&a);
printf(“enter number of shifting bits”);
Scanf(“%d”,&b);
c=a>>b; Binary put on the register :
printf(“%d”,c);
getch(); 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1
} 128 64 32 16 8 4 2 1
0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0
At the last 2
0 bit autometic
Result : 196 added
6. Conditional operator :
it is also know an ternary operator and ?: operator.
Syntax :
condition ? True part : false part;
In this operator we have an condition if the condition is true the true part executed
otherwise false part is executed.
Example :
Program for check a number is even or odd.
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<“enter a number”;
cin>>a;
(a%2==0) ? cout<<“number is even” : cout<<“number is odd”;
getch();
}
Program for check a greater number between two numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
cout<<“enter two number”;
cout>>a>>b;
(a>b) ? cout<<“a is greater” : cout<<“b is greater”;
getch();
}
7. Special operators :
a. address of(&)
b. sizeof
c. pointer
a. Address of(&) :
address of operator is used for finding address of the variable in
Computer memory.
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<“enter a number”;
cin>>a;
cout<<a; // value of a
cout<<&a; // find address of variable a
getch();
}
b. sizeof operator :
using sizeof operator we can find size of the variable in c program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<“enter a number”; Note : when in an expression any
cin>>a; type of variables are present
cout<<a; then we choose always maximum
cout<<sizeof(a); size variable.
getch();
} sizeof(5+5.7+4) // 4
int A=2
sizeof(A) // 2
float A=2.2 //4
sizeof(A) // 1
char a=„m‟
sizeof(a)
Operators Precedence in C
Category Operator Associativity
1. If statement :
if statement is the most simple decision making statement. It is used
to decide whether a certain statement or block of statements will be executed or not
i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax:
if(condition)
{ // Statements to execute if
// condition is true
}
Example 1 : Example 2 :
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
Int a; Int a,b;
clrscr(); clrscr();
cout<<enter a number”; cout<<“enter two number”;
cin>>a; scanf>>a>>b;
If(a%2==0) If(a>b)
{ {
cout<<“number is even”; cout<<“a is greater”;
} }
getch(); getch();
} }
Example 3 : for print week day name according the given number between 1 to 7.
#include<iostream.h>
if(a==4)
#include<conio.h>
{
void main()
cout<<“wednesday”;
{
}
Int a;
if(a==5)
clrscr();
{
cout<<“enter a number”;
cout<<“thursday”;
cin>>a;
}
if(a==1)
if(a==6)
{
{
cout<<“sunday”;
cout<<“friday”;
}
}
if(a==2)
if(a==7)
{
{
cout<<“monday”;
cout<<“saturday”;
}
}
if(a==3)
getch();
{
}
cout<<“tuesday”;
}
2. if-else statement :
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won‟t. But what if we want to do
something else if the condition is false. Here comes the C++ else statement. We can use
the else statement with if statement to execute a block of code when the condition is
false.
Syntax :
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example 1 : Example 2 :
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a; int a,b;
clrscr(); clrscr();
cout<<“enter a number”; cout<<“enter two number”;
cin>>a; cin>>a>>b;
if(a%2==0) if(a>b)
{ {
cout<<“number is even”; cout<<“a is greater”;
} }
else else
{ {
cin<<“number is odd”; cout<<“b is greater”;
} }
getch(); getch();
} }
3. if-else if-else statement :
Here, a user can decide among multiple options. The C++ if statements are
executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions are true, then the final else statement will
be executed.
if (condition1)
{
statement;
}
else if (condition2)
{
statement;
}
else if(condition3)
{
Statements;
}
.
.
else
{
statement;
}
Write a program for check a number is positive, negative, or zero.
#include<iostream.h>
#include<conio.h>
void main()
{
int a;
clrscr();
cout<<“enter a number”;
cin>>a;
if(a==0)
{
cout<<“number is zero”;
}
else if(a>0)
{
cout<<“number is positive”;
}
else if(a<0)
{
cout<<“number is negative”;
}
getch();
}
Write a program for check division of a student according to percentage.
#include<iostream.h> }
#include<conio.h> else if(percentage>=36)
void main() {
{ cout<<“third division”;
float percentage; }
clrscr(); else if(percentage>=33)
cout<<“enter your percentage”; {
cin>>percentage; cout<<“pass by gress”;
if(percentage>=60) }
{ else
cout<<“first division”; {
} cout<<“fail”;
else if(percentage>=45) }
{ getch();
cout<<“second division”; }
4. Nested if statement :
A nested if in C++ is an if statement that is the target of another if statement.
Nested if statements means an if statement inside another if statement. Yes, both C
and C++ allows us to nested if statements with in if statements, i.e, we can place an if
statement inside another if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
//else statement
}
}
else
{
// else statement
}
Write a program for check greater number between given 3 numbers.
#include<iostream.h> else
#include<conio.h> {
void main() If(b>c)
{ {
int a,b,c; cout<<“b is greater”;
clrscr(); }
cout<<“enter three numbers”; else
cin>>a>>b>>c; {
if(a>b) cout<<“c is greater”;
{ }
if(b>c) }
{ getch();
cout<<“a is greater”; }
}
else
{
cout<<“c is greater”;
}
}
5. Switch case statement :
Switch statement is a control statement that allows us to choose only one
choice among the many given choices. The expression in switch evaluates to return an
Integral or character value, which is then compared to the values present in different
cases. It executes that block of code which matches the case value. If there is no
match, then default block is executed(if present).
Syntax :
.
switch(expression) .
{ .
case 1: case n:
block-1; block-n;
break; break;
case 2: default:
block-2; default-block;
break; break;
case 3: }
block-3;
break;
case 4:
block-4;
break;
Write a program for print week day name according to given number using switch
case.
#include<iostream.h>
#include<conio.h> case 5:
void main() cout<<“Thursday”;
{ break;
int n; case 6:
clrscr(); cout<<“Friday”;
cout<<“enter a number b/w 1 to 7”; break;
cin>>n; case 7:
switch(n) cout<<“Saturday”;
{ break;
case 1: default :
cout<<“Sunday”; cout<<“please choose valid case”;
break; break;
case 2: }
cout<<“Monday”; getch();
break; }
case 3:
cout<<“Tuesday”;
break;
case 4:
cout<<“Wednesday”;
break;
Write a program using switch case statement where we have 4 cases 1 for addition, 2
for subtruction,3 for multipalication and 4 for division.
#include<iostream.h> c= a-b;
#include<conio.h> cout<<c;
void main() break;
{ case 3:
int n; int a,b,c;
clrscr(); cout<<“enter two numbers”;
cout<<“enter a number b/w 1 to 4”; cin>>a>>b;
cin>>n; c= a*b;
switch(n) cout<<c;
{ break;
case 1: case 4:
int a,b,c; int a,b,c;
cout<<“enter two numbers”; cout“enter two numbers”;
cin>>a>>b; cin>>a>>b;
c= a+b; c= a/b;
cout<<c; cout<<c;
break; break;
case 2: Default:
int a,b,c; cout<<“please choose valid case”;
cout<<“enter two numbers”; break;
cin>>a>>b; }
getch(); }
Write a program using switch case for print traffic light instruction according to light
signal and also apply case label R, G, Y.
#include<stdio.h>
#include<conio.h> Default:
void main() cout<<“please choose valid case”;
{ break;
char ch; }
clrscr(); getch();
cout<<“choose a character R,G,Y”; }
cin>>ch;
switch(ch)
{
case „R‟:
case „r‟:
cout<<“Stop”;
break;
case „G‟:
case „g‟:
cout<<“Go”;
break;
case „Y‟:
case „y‟:
cout<<“Ready for go”;
break;
*
- By kanhaiya lal kumawat
A Loop executes the sequence of statements many times until the given condition
becomes false. Suppose we want to print “hello world” 10 times then we have two
Options.
1. We can use 10 printf function to printf 10 time “hello world”.
2. We can use a loop from i=1 to i<=10 and print “hello world” in side block
Example :
Int I;
(1) (2) (4)
For(i=1;i<=10;i++)
{ (3)
cout<“hello world”;
}
Types of loops :
1. for loop
2. while loop
3. do-while loop
1. for loop :
for loop is used to execute a set of statements repeatedly until a particular
condition is satisfied.
Syntax :
(1) (2) (4)
for(initialization; condition; increment/decrement)
{ (3)
statement-block;
}
#include<stdio.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=1; i<=10 ; i++)
{
cout<<“hello world”;
}
getch();
}
#include<stdio.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=0; i<10 ; i++)
{
cout<<i<<\t;
}
getch();
}
Result :
0123456789
3. Write a program to print all number b/w 50 to 150.
#include<iostream.h>
#include<conio.h>
Void main()
{
int I;
clrscr();
for (i=50; i<=150 ; i++)
{
cout<<i<<\t;
}
getch();
}
4. Write a program to print table of a given number.
#include<iostream.h>
#include<conio.h>
Void main()
{ Suppose number is 5.
int I, n,table; Then,
clrscr(); i=1,i<=10(true)
cout<<“enter a number”; Then,
cin>>n; table=1*5=5
for (i=1; i<=10 ; i++) i++ = 2
{ table=2*5=10
table=i*n; i++ = 3
cout<<table<<\t; table = 3*5=15
}
getch();
}
5. Write a program to print factorial of the given number.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n,fact=1;
clrscr();
cout<<“enter a number”;
cin>>n;
for (i=1; i<=n ; i++)
{
fact=fact*i;
}
cout<<fact;
getch();
}
6. Write a program to print all even numbers between the given range.
#include<iostream.h>
#include<conio.h>
void main()
{
int min, max,i;
clrscr();
cout<<“enter starting and ending number”;
cin>>min>>max;
for(i=min;i<=max;i++)
{
if(i%2==0)
{
cout<<i<<\t;
}
}
getch();
}
7. Write a program to print all factors of the given number.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n;
clrscr();
cout<<“enter a number”;
cin>>n;
for (i=1; i<=n ; i++)
{
If(n%i==0)
{
cout<<i<<\t;
}
}
getch();
}
8. Write a program for swapping of two integers without using third variable.
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
cout<<“enter two number”;
cin>>a>>b;
a=a+b;
b=a-b;
a=a-b;
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<“enter two number”;
cin>>a>>b;
c=a;
a=b;
b=c;
Syntax :
initialization; for(initialization ; con ; inc/dec)
while(condition) {
{ statements;
Statements; }
Increment/decrement;
}
#include<iostream.h> }
#include<conio.h> getch();
void main() }
{
int i;
clrscr();
i=1;
while(i<=100)
{
cout<<i<<\t;
i++;
Write a program to print table of the given number using while loop.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, n,table;
clrscr();
cout<<“enter a number”;
cin>>n;
i=1;
while(i<=10)
{
table=i*n;
cout<<table<<\t;
i++;
}
getch();
}
Write a program to print factorial of the given number using while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n,fact=1;
clrscr();
cout<<“enter a number”;
cin>>n;
i=1;
while(i<=n)
{
fact=fact*I;
i++;
}
cout<<fact;
getch();
}
3. do-while loop :
do-while loop is also known as exit control loop. In this type of loop we have
Also three important statements initialization, condition and increment and decrement.
Do-while loop also print group of statement repeatedly until the given condition is not
Satisfied.
Syntax :
Example:
initialization;
do
#include<iostream.h>
{
#include<conio.h>
statements;
void main()
inc/dec;
{
}
int i;
while(condition);
clrscr();
i=1;
do
{
cout<<i<<\t;
i++;
}
while(i<=100);
getch();
}
Write a program to print table of the given number using do-while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n,table;
clrscr();
cout<<“enter a number”;
cin>>n;
i=1;
do
{
table=i*n;
cout<<table<<\t;
i++;
}
while(i<=10);
getch();
}
Write a program to print factorial of the given number using do-while loop.
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n,fact=1;
clrscr();
cout<<“enter a number”;
cin>>n;
i=1;
do
{
fact=fact*I;
i++;
}
while(i<=n);
cout<<fact;
getch();
}
Difference between while and do-while loop :
While do-while
1. While loop is an entry control loop. 1. do-while loop is an exit control loop.
2. In while loop if first time the given 2. But in do-while loop if first time given
condition is false then loop does not condition is false then loop execute
execute. at least once.
3. In this loop we first test the given 3. But in do-while loop we check condition
condition after at take decision. At the end of loop.
Nested for loop :
loop inside another loop is called nested of loop.
Syntax:
for(initialization;condition;inc/dec)
{
for(initialization;condition;inc/dec)
{
statements;
}
}
#include<iostream.h> getch();
#include<conio.h> } * *** *
void main() * *** *
{ * *** *
Int I,j; * *** *
clrscr(); * *** *
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
cout<<“*”;
}
cout<<“\n”;
}
#include<iostream.h>
#include<conio.h> *
void main() * *
{ * **
Int I,j; * ***
clrscr(); * ****
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<“*”;
}
cout<<“\n”;
}
getch();
}
#include<iostream.h>
#include<conio.h> 1
void main() 2 2
{ 3 33
Int I,j; 4 444
clrscr(); 5 5555
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<i;
}
cout<<“\n”;
}
getch();
}
#include<iostream.h>
#include<conio.h> 1
void main() 1 2
{ 1 23
Int I,j; 1 234
clrscr(); 1 2345
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<j;
}
cout<<“\n”;
}
getch();
}
#include<iostream.h>
#include<conio.h> 1
void main() 23
{ 456
Int I,j,ch=1; 7 8 9 10
clrscr(); 11 12 13 14 15
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<ch;
ch++;
}
cout<<“\n”;
}
getch();
}
#include<iostream.h> ASCII-American standard code for information
#include<conio.h> interchange
void main()
{
Int I,j;
char ch=65;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<ch;
ch++;
}
cout<<“\n”;
}
getch();
}
A
BC
DEF
GHIJ
KLMNO
#include<iostream.h>
#include<conio.h> A
void main() BB
{ CCC
Int I,j; DDDD
Char ch=65; EEEEE
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<ch;
}
Ch++;
cout<<“\n”;
}
getch();
}
#include<iostream.h>
#include<conio.h> A
void main() AB
{ ABC
Int I,j; ABCD
Char ch; ABCDE
clrscr();
for(i=1;i<=5;i++)
{
Ch=65;
for(j=1;j<=i;j++)
{
cout<<ch;
ch++;
}
cout<<“\n”;
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j; * * * * *
clrscr(); * *
for(i=0;i<=5;i++) * *
{ * *
for(j=1;j<=5;j++) * *
{ * * * * *
if(i=1 || i=5 || j=1 ||j=5)
{
cout<<“*”;
}
else
{
cout<<“ “;
}
}
cout<<“\n”;
}
getch();
}
Write a program for check a given number is prime or not.
2,3,5,7,11,13,17,19,23………………………n
#include<iostream.h>
#include<conio.h>
void main()
{
Int n,i,temp;
clrscr();
cout<<“enter a number”;
cin>>n;
temp=n;
for(i=2;i<n;i++)
{
If(n%i==0)
{
cout<<“number is not prime”;
break;
}
}
If(i==temp)
{
cout<<“number is prime”;
}
getch();
}
Write a program for print reverse of the given number.
123 546
321 645
#include<iostream.h>
#include<conio.h>
void main()
{
Int n,r,rev=0;
clrscr();
cout<<“enter a number”;
cin>>n;
while(n>0)
{
r=n%10;
n=n/10;
rev=rev*10+r;
}
cout<<rev;
getch();
}
Write a program for check a given number is palindrome or not.
1221 141 444
1221 141 444
#include<iostream.h>
#include<conio.h> else
void main() {
{ cout<<“not palindrome”;
Int n,r,rev=0,temp; }
clrscr(); getch();
cout<<“enter a number”; }
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
n=n/10;
rev=rev*10+r;
}
if(rev==temp)
{
cout<<“palindrome”;
}
*
- By kanhaiya lal kumawat
Control statements are used for control the flow of the loop execution in an program.
In c++ language we have 4 control statements :
1. Break statement
2. Continue statement
3. Goto statement
4. Exit statement
1. Break statement :
Break statement is used for control the flow of the loop in an program, in an
loop if we apply break statement on the specific condition then the break statement
stop the loop execution.
For example :
if(i==5)
#include<iostream.h>
{
#include<conio.h>
break;
void main()
}
{
cout<<i;
Int i;
}
clrscr();
getch();
for(i=1;i<=10;i++)
}
{
Result : 1 2 3 4
2. Continue statement :
The continue statement is used inside loops. When a continue statement is
encountered inside a loop, control jumps to the beginning of the loop for next iteration,
skipping the execution of statements inside the body of loop for the current iteration.
For example :
#include<iostream.h>
#include<conio.h>
void main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
Continue;
}
cout<<i;
}
getch();
}
result : 1 2 3 4 6 7 8 9 10
3. Goto statement :
The goto statement is a jump statement which is sometimes also referred to
as unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.
For example :
#include <iostream.h>
#include<conio.h>
void main()
{
int num,i=1;
cout<<"Enter the number whose table you want to print?";
cin>>num;
table:
cout<<num<<“*”<<i<<num*i);
i++;
if(i<=10)
{
goto table;
}
getch();
}
4. Exit statement :
break statement stop the loop execution but the exit statement also stop
Program execution on a specific condition. <stdlib.h> header file is used for exit
Statement.
For example :
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
Int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
{
exit(1);
}
cout<<i;
}
getch();
}
*
- By kanhaiya lal kumawat
An array is a collection of similar types of data means an integer type array storage
Integer type values, and an float type array store float type values.
Array concept is used for store similar type values in a single variable and these value
Have also continues memory location.
Declaration of an array :
int number[10]={1,2,3,56,78,88,56,45,76,34};
float number[10]={1.2,2.3,3.4,4.5,5.6,6.7,7.8,8.9,9.0,2.1};
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Program for print array elements
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int i; int i;
int marks[5];//declaration of array int marks[5]={80,60,70,85,75};
marks[0]=80;//initialization of array for(i=0;i<5;i++)
marks[1]=60; {
marks[2]=70; cout<<marks[i]<<“\n”;
marks[3]=85; }
marks[4]=75; getch();
//traversal of array }
for(i=0;i<5;i++)
{
cout<<marks[i]<<“\n”;
}
getch();
} Output :
80 60 70 85 75
Program for print array elements where elements are entered by user
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
int marks[5];//declaration of array
cout<<“enter array elements”;
for(i=0;i<5;i++)
{
cin>>marks[i];
}
//traversal of array
for(i=0;i<5;i++)
{
cout<<marks[i]<<“\n”;
}
getch();
}
Program for print array elements in reverse order where elements are entered by
user
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
int marks[5];//declaration of array
cout<<“enter array elements”;
for(i=0;i<5;i++)
{
cin>>marks[i];
}
//traversal of array
for(i=4;i>=0;i--)
{
cout<<marks[i]<<“\n”;
}
getch();
}
Write a program for print sum of given array elements
#include<iostream.h>
#include<conio.h>
void main() 10 20 30 40 50
{
int i; Sum=0+10=10
int marks[5],sum=0; Sum=10+20=30
cout<<“enter array elements”; Sum=30+30=60
for(i=0;i<5;i++) Sum=60+40=100
{ Sum=100+50=150
cin>>marks[i];
}
for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
cout<<sum<<“\n”;
getch();
}
Write a program for print average of given array elements
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
int marks[5],sum=0;
Float average;
cout<<“enter array elements”;
for(i=0;i<5;i++)
{
cin>>marks[i];
}
for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
average=(float)sum/i;
cout<<average;
getch();
}
Write a program for print smallest element from an array.
#include<iostream.h>
7 9 5 90 45
#include<conio.h>
void main()
{
int i;
int marks[5];
int smallest;
cout<<“enter array elements”;
for(i=0;i<5;i++)
{
cin>>marks[i];
}
smallest=marks[0];
for(i=1;i<5;i++)
{
If(smallest>marks[i])
{
smallest=marks[i];
}
cout<<smallest;
getch();
}
Write a program for print largest number form an given integer array.
#include<iostream.h>
#include<conio.h>
void main()
{ 7 9 5 90 45
int i;
int marks[5];
int largest;
clrscr();
cout<<"enter array elements";
for(i=0;i<5;i++)
{
cin>>marks[i];
}
largest=marks[0];
for(i=1;i<5;i++)
{
if(largest<marks[i])
{
largest=marks[i];
}
}
cout<<largest;
getch();
}
2. Multi-dimensional arrray :
Multi dimensional array may be two dimensional or three
Dimensional means 2D and 3D.
1. Two dimensional
2. Three dimensional
1. Two dimensional array :
two dimensional array means array of array. It is also known as
matrix or tabular array
Declaration of 2D array :
Data_type array_name[row][column]
Example :
int A[3][3]={1,2,3,4,5,6,7,8,9};
0 1 2
1 2 3
4 5 6
7 8 9
Write a program for print elements of two dimensional array.
#include<iostream.h>
#include<conio.h>
void main()
{
Int I,j;
Int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<a[i][j]<<“\t”;
}
cout<<“\n”;
}
Result :
1 2 3
4 5 6
7 8 9
Write a program for print elements of two dimensional array where elments entered
by user.
#include<iostream.h> cout<<“\n”;
#include<conio.h> }
void main()
{ Result :
Int I,j; 1 2 3
Int a[3][3]; 4 5 6
clrscr(); 7 8 9
cout<<“enter array elements”;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<a[i][j])<<“\t”;
}
Write a program for print addition of two two dimensional array elements.
#include<iostream.h>
#include<conio.h> cout<<“addition of two matrix”;
void main() for(i=0;i<3;i++)
{ {
Int I,j; for(j=0;j<3;j++)
Int a[3][3],b[3][3],c[3][3]; {
clrscr(); c[i][j]=a[i][j]+b[i][j];
cout<<“enter first array elements”; cout<<c[i][j];
for(i=0;i<3;i++) }
{ cout<<“\n”;
for(j=0;j<3;j++) }
{ getch();
cin>>a[i][j]; }
} Result :
}
3 4 5 4 6 8
cout<<“enter second array elements”;
6 7 8
for(i=0;i<3;i++) + 10 12 14
{ 1 2 3 16 18 20
for(j=0;j<3;j++)
{ 7 10 13
cin>>b[i][j]; 16 19 22
}
} 17 20 23
Write a program for print two matrix multiplication.
#include<iostream.h> {
#include<conio.h> cin>>a[i][j];
Void main() }
{ }
Int a[2][2],b[2][2],c[2][2]; cout<<“enter first matrix elements :”;
Int i,j,k; for(i=0;i<2;i++)
clrscr(); {
cout<<“enter first matrix elements :”; for(j=0;j<2;j++)
for(i=0;i<2;i++) {
{ cin>>b[i][j];
for(j=0;j<2;j++) }}
cout<<"multiply of the matrix :\n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++) 1 2 5 6
{
c[i][j]=0; 3 4 0 7
for(k=0;k<2;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j]; i=0,j=0,k=0
} C[0][0]=0;
} C[0][0]=c[0][0]+a[0][0]*b[0][0];
} C[0][0]=0+1*5=5;
//for printing result C[0][0]=5+2*0=5;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<c[i][j];
}
cout<<"\n";
}
Write a program for print transpose of a matric.
#include<iostream.h>
#include<conio.h>
Void main()
{
Int a[2][2],ta[3][3];
Int i,j;
clrscr();
cout<<“enter matrix elements :”;
for(i=0;i<3;i++)
{ cout<<"Transpose of given matrix: \n";
for(j=0;j<3;j++) for(i=0;i<3;i++)
{ {
cin>>a[i][j]; for(j=0;j<3;j++)
} {
} cout<<ta[i][j];
for(i=0; i<3;i++) }
{ cout<<"\n";
for(j=0;j<3;j++) }
{ getch();
ta[i][j] = a[j][i]; }
}
}
Write a program for print diagonal matrix.
#include<iostream.h>
for(i=0;i<3;i++)
#include<conio.h>
{
void main()
for(j=0;j<3;j++)
{
{
int i,j;
cout<<a[i][j];
int a[3][3];
}
clrscr();
cout<<"\n";
for(i=0;i<3;i++)
}
{
getch();
for(j=0;j<3;j++)
}
{
if(i==j)
1 0 0
{
0 1 0
a[i][j]=1;
0 0 1
}
else
{
a[i][j]=0;
}
}
}
*
- By kanhaiya lal kumawat
String is a character type array, so we can store many characters in the character
array. And an string is a collection of characters. In c programming string is always
written in double quotation mark.
For example :
“kanhaiya”
Syntax :
char array_name[size];
1. strlen() function :
this function is used for calculate the length of the string characters.
Example :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
clrscr();
cout<<“enter your name”;
cin>>(name);
i = strlen(name);
cout<<i;
getch();
}
2. strrev() function :
strrev() function is used for print string in reverse order.
Example :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
clrscr();
cout<<“enter your name”;
cin>>name;
cout<<(strrev(name));
getch();
}
3. strcmp() function :
compare two strings. If string one is greater then result is positive and
If string two is greater then result is negative number and both strings are equal then
Result is zero.
Example :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20],nick_name[20];
Int i;
clrscr();
cout<<“enter your name”;
cin>>name;
cout<<“enter your nick name”;
cin>>nick_name;
i=strcmp(name,nick_name);
cout<<i;
getch();
}
4. strcpy() function :
strcpy function is used for copy a string to another.
Example :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20],nick_name[20];
Int i;
clrscr();
cout<<“enter your name”;
cin>>name;
cout<<“enter your nick name”;
cin>>nick_name;
strcpy(name,nick_name);
cout<<“name”;
getch();
}
Note : when string two coping into the string one then value of string one is removed
And string 2’s value is copyed there.
5. strcat() function :
concatenate two strings.
Example :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char first_name[20],last_name[20];
Int i;
clrscr();
cout<<“enter your first name”;
cin>>first_name;
cout<<“enter your last name”;
cin>>last_name;
strcat(first_name,last_name);
cout<<“first_name”;
getch();
}
*
- By kanhaiya lal kumawat
A function is a block of code that performs a particular task. There are many situations
where we might need to write same line of code for more than once in a program. This
may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer. So, C++ language provides an approach in which you can declare and define
a group of statements once in the form of a function and it can be called and used
whenever required.
These functions defined by the user are also know as User-defined Functions.
1. Library functions are those functions which are already defined in C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to use
these functions. These are already declared and defined in C++ libraries.
2. A User-defined functions on the other hand, are those functions which are defined
by the user at the time of writing program. These functions are made for code reusabilit
and for saving time and space.
Benefits of Using Functions
• It provides modularity to your program's structure.
• It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
• In case of large programs with thousands of code lines, debugging and editing become
easier if you use functions.
• It makes the program more readable and easy to understand.
1. Function Declaration :
returntype functionName(type1 parameter1, type2 parameter2,...);
Like any variable or an array, a function must also be declared before its used. Function
declaration informs the compiler about the function name, parameters is accept, and its
return type. The actual body of the function can be defined separately. It's also called as
Function Prototyping. Function declaration consists of 4 parts.
• returntype
• function name
• parameter list
• terminating semicolon
Returntype :
When a function is declared to perform some sort of calculation or any operation and is
expected to provide with some result at the end, in such cases, a return statement is
added at the end of function body. Return type specifies the type of value(int, float,
char, double) that function is expected to return to the program which called the
function.
Note: In case your function doesn't return any value, the return type would be void.
functionName :
Function name is an identifier and it specifies the name of the function. The function
name is any valid C identifier and therefore must follow the same naming rules like
other variables in C language.
parameter list :
The parameter list declares the type and number of arguments that the function
expects when it is called. Also, the parameters in the parameter list receives the
argument values when the function is called. They are often referred as formal
parameters.
2. Definition :
return_type function_name(parameter_list)
{
code of function;
}
3. Calling :
function_name(parameter_list);
Example of function :
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
myfunction(); // calling
getch();
}
Write a program for addition of two numbers using function.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for check a number is even or odd using function.
#include<iostream.h>
#include<conio.h>
void main()
{
void evenodd(); //declaration
clrscr();
evenodd(); // calling
void evenodd() // definition
evenodd();
{
getch();
int a;
}
cout<<“enter a number”;
cin>>a;
if(a%2==0)
{
cout<<“number is even”;
}
else
{
cout<<“number is even”;
}
}
Nesting of function :
nesting of function is not possible in function. But we can only declare a
function in another function.
#include<iostream.h>
void main()
#include<conio.h>
{
void kanhaiya();
clrscr();
void kanhaiya()
kanhaiya();
{
sikar();
cout<<“my name is kanhaiya”;
rajasthan();
void sikar();
getch();
}
}
void sikar()
{
cout<<“I am from sikar”;
void rajasthan();
}
void rajasthan()
{
cout<<“state rajasthan”;
}
Types of user define functions :
four types.
1. No arguments and No return type
2. No arguments and A return type
3. A argument and No return type
4. A argument and A return type
Declaration :
void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for addition of two numbers using function.
NO argument and A return type
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
add(); // calling
add();
getch();
}
Write a program for addition of two numbers using function.
A argument and NO return type
#include<stdio.h>
#include<conio.h>
void main()
{
Int a=8,b=10;
clrscr();
add(a,b); // calling
add(a,b);
getch();
}
Write a program for addition of two numbers using function.
A argument and A return type
#include<stdio.h>
#include<conio.h>
void main()
{
float a=8.9,b=10.5;
clrscr();
add(a,b); // calling
add(a,b);
getch();
}
Write a program for print table of the given number using function.
Syntax :
struct sturcture_name
{
datatype1 item1;
datatype1 item1;
datatype1 item1;
datatype1 item1;
}
Example :
struct book
{
char book_name[20];
int book_pages;
float book_price;
}
Initialization of an structure :
Note : here we can also declare structure outside the void main function and
Initialize by different ways.
Values of structure input by user :
#include<iostream.h>
#include<conio.h>
void mian()
{
struct book
{
char book_name[20];
int pages;
float price;
};
cout<<bk.book_name;
cout<< bk.pages;
cout<< bk.price;
getch();
}
Write a program for print an student details using structure where details are rollnumber
, name, course, gender and fathers name.
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rollnumber;
char name[20];
char course[20];
char gender[10];
char f_name[20];
};
struct student s1;
cout<<“enter student rollnumber, name, course, gender, father‟s name”;
cin>>s1.rollnumber>>s1.name>>s1.course>>s1.gerder>>s1.f_name;
cout<<s1.rollnumber<<s1.name<<s1.course<<s1.gerder<<s1.f_name”);
getch();
}
Array of structure :
we can create array type variable of any structure. And use it many
times using loop.
Example :
#include<iostream.h> for(i=0;i<5;i++)
#include<conio.h> {
void main() cout<<s1[i].rollnumber<<s1[i].name<<s1[i].course
{ <<s1[i].gerder<<s1[i].f_name”;
struct student }
{ getch();
int rollnumber; }
char name[20];
char course[20];
char gender[20];
char f_name[20];
};
struct student s1[5];
for(i=0;i<5;i++)
{
cout<<“enter student rollnumber, name, course, gender, father‟s name”;
cin>>s1[i].rollnumber>>s1[i].name>>s1[i].course>>s1[i].gerder>>s1[i].f_name;
}
Structure of structure :
It means we can create object of an structure in another structure.
Syntax :
struct structure1
{ struct address
datatype1 member1; {
datatype1 member1; char city[20];
datatype1 member1; char state[20];
datatype1 member1; long int pincode;
}; };
Structure Union
struct book union book
{ {
char name[20]; char name[20];
int pages; int pages;
float price; float price;
}; };
name name
Example :
#include<iostream.h>
#include<conio.h>
void main()
{
int x=10;//local variable
Cout<<x;
getch();
}
Global Variable
A variable that is declared outside the function or block is called a global
variable. Any function can change the value of the global variable. It is available to all
the functions. It must be declared at the start of the block.
Example :
#include<iostream.h>
#include<conio.h>
int value=20;//global variable
void main()
{
int x=10;//local variable
cout<<x;
cout<<value;
getch();
}
*
- By kanhaiya lal kumawat
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable.
• scope i.e where the value of the variable would be available inside a program.
• default initial value i.e if we do not explicitly initialize that variable, what will be
its default initial value.
• lifetime of that variable i.e for how long will that variable exist.
Example :
#include<iostream.h>
#include<conio.h>
void main()
{
auto int a;
cout<<a;
getch();
}
• The automatic variables are initialized to garbage by default.
• Keyword that used for defining automatic variables is auto.
• Every local variable is automatic in c by default.
• It‟s scope is local variable.
• This variable store in computer memory(RAM).
2. Register storage class :
The register variable is stored in the computer CPU register. And the register
Access is faster then the memory access. If the CPU register memory is full then the
value of register variable is store on the memory.
When you declare float and double type variable as register, it treats as auto variable
because it takes more space to store.
Example :
#include<stdio.>
#include<conio.h>
void main()
{
register int num;
for(num=1;num<=5;num++)
{
cout<<num;
}
getch();
}
3. External storage class :
when you are declaring the variables as external storage class, it is accessed in
all the functions which is defined in the same program. These variables are called
extern or global variables. External variables are declared outside the function body.
In case both external and auto variables are declared with the same name in a program,
The first priority is given to the auto variable.
Example :
#include<iostream.h>
#include<conio.h>
extern int num=5;
void display();
void display()
{
cout<<num;
}
void main()
{
Int num=20;
cout<<num;
display();
getch();
}
4. Static storage class :
The static variable may be of an auto and global type depending upon where
It is declared. If declared outside the function of the body it will be static global. In
Case, if it is declared in the particular block, it is treated as the local or auto variable.
a static variable is initialized only once, it is never reinitialized. The value of
the static variable save at each call.
Example :
#include<iostream.h>
#include<conio.h>
void count();
void count()
{
Static int num=1;
cout<<num;
num++;
}
void main()
{
count();
count();
count();
getch();
}
*
- By kanhaiya lal kumawat
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of
the pointer variable is always 2 bytes.
Example :
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of
type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.
B A
2000 10
3000 2000
Example 1: Example 2:
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int number=50; int a=5,b=10;
int *p; int *A=&a, *B=&b;
p=&number; Int c;
cout<<number; c=*A+*B;
cout<<&number; cout<<c;
cout<<"Address of p variable is “<<“\t”<<p; getch();
cout<<"Value of p variable is %d ”<<“\t“<<*p; }
getch();
}
Example 3 :
#include<iostream.h>
#include<conio.h>
void main()
{
int a=8,b=10;
int *A=&a, *B=&b;
*A=*A+*B;
*B=*A-*B;
*A=*A-*B;
cout<<*A<<*B);
getch();
}
Array of Pointer :
we can store address of an array onto the pointer type array.
#include<iostream.h>
#include<conio.h>
void main()
{
int marks[5]={50,60,70,80,90};
int i, *p[5];
for(i=0;i<5;i++)
{
p[i]=&marks[i];
}
for(i=0;i<5;i++)
{
cout<<*p[i];
}
getch();
}
Write a program for print sum of array elements using pointer.
#include<iostream.h>
#include<conio.h>
void main()
{
int marks[5]={40,50,60,70,80};
int i,*p[5],sum=0;
for(i=0;i<5;i++)
{
p[i]=&marks[i];
}
for(i=0;i<5;i++)
{
sum=sum+*p[i];
}
cout<<sum;
getch();
}
Pointer to pointer :
Pointer is known as a variable that contain address of another variable. The
pointer variable also has an address. The pointer variable containing address of another
pointer is known as pointer of pointer.
**P *p x
3000 2000 5
4000 3000 2000
#include<iostream.h>
#include<conio.h>
void main()
{
int var=3000;
int *p=&var;
int **P=&p;
cout<<var;
cout<< &var;
cout<< p;
cout<< *p;
cout<< &*p;
cout<< &p;
cout<< P;
cout<< **P;
cout<< &**P;
cout<< &P;
getch();
}
Pointer as function argument :
pointer as a function argument is used to hold addresses of arguments
passed during function call. This is known as call by reference. When a function is
called by reference any change made to the reference variable with effect the
original variable.
Write a program for swapping two numbers using pointer as function argument.
#include<iostream.h>
#include<conio.h>
void swap(int *a,int *b);
void swap(int *a,int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
cout<<a<<“\n”<<b;
}
void main()
{
int m=10,n=20;
swap(&m,&n);
cout<<m<<“\n”<<n;
getch();
}
Pointer to structure :
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
char name[10];
int rollnumber;
};
struct student s1={“kanhaiya”,12};
struct student *st;
st =&s1;
cout<<s1.name;
cout<< s1.rollnumber;
cout<< *st->name;
cout<< *st->rollnumber;
getch();
}
Arrow symbol is used when we want to access structure members by
pointer variable.
C++ OOPs Concepts :
The major purpose of C++ programming is to introduce the concept of object
orientation to the C programming language. Object Oriented Programming is a paradigm
that provides many concepts such as inheritance, data binding, polymorphism etc.
The programming paradigm where everything is represented as an object is known as
truly object-oriented programming language. Smalltalk is considered as the first truly
object-oriented programming language.
Class :
Collection of objects is called class. It is a logical entity.
Inheritance :
When one object acquires all the properties and behaviours of parent objec
i.e. known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism :
When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
In C++, we use Function overloading and Function overriding to achieve polymorphism.
Abstraction :
Hiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.
Encapsulation :
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
C++ Object :
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data
and behavior means functionality.
Object is a runtime entity, it is created at runtime. Object is an instance of a class. All
the members of the class can be accessed through object.
Example :
Student s1; //creating an object of Student
Student is the type and s1 is the reference variable that refers to the instance of
Student class.
C++ Class :
In C++, object is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.
Example :
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
C++ Object and Class Example :
#include <iostream>
#include<conio.h>
class Student
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
void main()
{
Student s1; //creating an object of Student
s1.id = 201;
s1.name = “subhash";
cout<<s1.id;
cout<<s1.name;
getch();
}
#include <iostream>
#include<conio.h>
class Student {
public:
int id;
string name;
void insert(int i, string n)
{
id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name;
}
};
void main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
}
C++ Class Example: Store and Display Employee Information :
#include<iostream.h>
#include<conio.h> void main()
class Employee {
{ Employee e1;
public: Employee e2;
int id; e1.insert(201, "Sonoo",990000);
string name; e2.insert(202, "Nakul", 29000);
float salary; e1.display();
void insert(int i, string n, float s) e2.display();
{ getch();
id = i; }
name = n;
salary = s;
} Output:
void display() 201 Sonoo 990000 202 Nakul 29000
{
cout<<id<<" "<<name<<" "<<salary;
}
};
Constructor :
constructor is a special method which is invoked automatically at the time of
object creation. It is used to initialize the data members of new object. The constructor
in C++ has the same name as class or structure.
1. Default Constructor :
A constructor which has no argument is known as default constructor. It is invoked at the
time of creating object.
Example :
#include <iostream.h> void main()
#include<conio.h> {
class Employee Employee e1;
{ Employee e2;
public: getch();
Employee() }
{
cout<<"Default Constructor Invoked“<<endl;
}
};
2. Parameterized Constructor :
A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.
Example :
class ProtectedAccess
{
// protected access modifier
protected:
int x; // Data Member Declaration
void display(); // Member Function decaration
}
3. Access Modifier: Private
These members are only accessible from within the class. No outside Access is allowed.
EXample :
class PrivateAccess
{
// private access modifier
private:
int x; // Data Member Declaration
void display(); // Member Function decaration
}
Inheritance :
inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. In such way, you can reuse, extend or modify the
attributes and behaviors which are defined in other class.
In C++, the class which inherits the members of another class is called derived class and
the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
Types Of Inheritance:
C++ supports five types of inheritance:
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance
Derived Classes:
A Derived class is defined as the class derived from the base class.
Syntax :
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
• When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.
• When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.
Note:
1. In C++, the default mode of visibility is private.
2. The private members of the base class are never inherited.
1. C++ Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited
from the only one base class.
Where 'A' is the base class, and 'B' is the derived class. When one class inherits another
class, it is known as single level inheritance. Let's see the example of single level
inheritance which inherits the fields only.
#include <iostream.h>
#include<conio.h>
class Account
{
public:
float salary;
};
class Programmer:: public Account
{
public:
float bonus;
};
void main()
{
Programmer p1;
p1.salary=60000;
p1.bonus=5000;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
getch();
}
Output :
Salary: 60000
Bonus: 5000
2. C++ Multilevel Inheritance :
Multilevel inheritance is a process of deriving a class from another derived class.
#include <iostream.h>
void main()
#include<conio.h>
{
class Animal
BabyDog d1;
{
d1.eat();
public:
d1.bark();
void eat()
d1.weep();
{
getch();
cout<<"Eating..."<<endl;
}
}
};
class Dog: public Animal
{
public:
void bark()
{
cout<<"Barking..."<<endl;
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}};
3. Multiple Inheritance :
Multiple inheritance is the process of deriving a new class that inherits the attributes
from two or more classes.
Syntax :
class D : visibility B-1, visibility B-2, ?
{
// Body of the class;
}
#include <iostream> class C : public A,public B
#include<conio.h> {
class A public:
{ void display()
protected: {
int a; std::cout << "The value of a is : " <<a<< std::endl;
public: std::cout << "The value of b is : " <<b<< std::endl;
void get_a(int n) cout<<"Addition of a and b is : "<<a+b;
{ }
a = n; };
} void main()
}; {
C c;
class B c.get_a(10);
{ c.get_b(20);
protected: c.display();
int b;
public: getch();
void get_b(int n) }
{
b = n;
}
};
4. Hybrid Inheritance :
Hybrid inheritance is a combination of more than one type of inheritance.
#include <iostream.h>
}
#include<stdio.h>
};
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;
}
};
class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : " <<endl;
cin>>b;
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
}; void main()
class D : public B, public C {
{ D d;
protected: d.mul();
int d; getch();
public: }
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
5. Hierarchical Inheritance :
Hierarchical inheritance is defined as the process of deriving more than one class from
a base class.
Syntax :
class A
{
class D : public A
// body of the class A.
{
}
// body of class D.
class B : public A
}
{
// body of class B.
}
class C : public A
{
// body of class C.
}
#include <iostream>
#include<conio.h>
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area() getch();
{ }
float result = 0.5*a*b;
return result;
}
};
void main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
Polymorphism :
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main concepts:
inheritance, encapsulation, and polymorphism.
2. Run time polymorphism: Run time polymorphism is achieved when the object's meth
is invoked at the run time instead of compile time. It is achieved by method overriding
which is also known as dynamic binding or late binding.
Differences b/w compile time and run time polymorphism.
• methods,
• constructors, and
• indexed properties
void main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
cout << "r1 is : " <<r1<< endl;
cout <<"r2 is : " <<r2<< endl;
getch();
}
Operators Overloading :
Operator overloading is a compile-time polymorphism in which the operator is
overloaded to provide the special meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the operators available in C++. It
is used to perform the operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined data type that is applied to
the built-in data types.
The advantage of Operators overloading is to perform different operations on the same
operand.
void showdata()
{
cout<<“a=”<<a<<“b=“<<b;
}
};
void main()
{
clrscr();
complex c1,c2,c3;
Operator overloading example :
#include<iostream.h>
#include<conio.h>
class complex void main()
{ {
private: clrscr();
int a,b; complex c1,c2,c3;
public: c1.setdata(3,4);
void setdata(int x,int y) c2.setdata(5,6);
{ c3=c1+c2;
a=x,b=y; c3.showdata();
} getch();
void showdata() }
{
cout<<"a="<<a<<"b="<<b;
}
complex operator +(complex c)
{
complex temp;
temp.a=a+c.a;
temp.b=b+c.b;
return(temp);
}
};
Function Overriding :
If derived class defines same function as defined in its base class, it is known as function
overriding in C++. It is used to achieve runtime polymorphism. It enables you to provide
specific implementation of the function which is already provided by its base class.
Syntax :
Pure virtual function can be defined as:
virtual void display() = 0;
#include <iostream.h>
#include<conio.h>
class Base
{ Output:
public: Derived class is derived from the base class.
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
cout << "Derived class is derived from the base class." <<endl;
}
};
void main()
In the above example, the base class contains
{
the pure virtual function. Therefore, the base
Base *bptr;
class is an abstract base class. We cannot create
//Base b;
the object of the base class.
Derived d;
bptr = &d;
bptr->show();
getch();
}
Interfaces in C++ (Abstract Classes) :
Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the
process to hide the internal details and showing functionality only. Abstraction can be
achieved by two ways:
• Abstract class
• Interface
Abstract class and interface both can have abstract methods which are necessary for
abstraction.
Let's take a real life example of AC, which can be turned ON or OFF, change the
temperature, change the mode, and other external components such as fan, swing.
But, we don't know the internal details of the AC, i.e., how it works internally. Thus,
we can say that AC seperates the implementation details from the external interface.
C++ provides a great level of abstraction. For example, pow() function is used to
calculate the power of a number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an
example of data abstraction.
Data Abstraction can be achieved in two ways:
1. Abstraction using classes
2. Abstraction in header files.
Abstraction using classes: An abstraction can be achieved using classes. A class is used
to group all the data members and member functions into a single unit by using the
access specifiers. A class has the responsibility to determine which data member is to
be visible outside and which is not.
Abstraction in header files: An another type of abstraction is header file. For example,
pow() function available is used to calculate the power of a number without actually
knowing which algorithm function uses to calculate the power. Thus, we can say that
header files hides all the implementation details from the user.
// program to calculate the power of a number.
#include <iostream.h>>
#include<math.h>
#include<conio.h>
void main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
cout << "Cube of n is : " <<result<< endl;
getch();
}
Output :
Cube of n is : 64
In the above example, pow() function is used to calculate 4 raised to the power 3. The
pow() function is present in the math.h header file in which all the implementation
details of the pow() function is hidden.
Let's see a simple example of data abstraction using classes.
#include <iostream.h>
#include<conio.h>
class Sum
Output:
{
Enter two numbers: 3 6
private: int x, y, z; // private variables
Sum of two number is: 9
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main() In the above example, abstraction is achieved using classes.
{ A class 'Sum' contains the private members x, y and z are
Sum sm; only accessible by the member functions of the class.
sm.add();
return 0;
}
Advantages Of Abstraction:
• Implementation details of the class are protected from the inadvertent user level erro
• A programmer does not need to write the low level code.
• Data Abstraction avoids the code duplication, i.e., programmer does not have to
undergo the same tasks every time to perform the similar operation.
• The main aim of the data abstraction is to reuse the code and the proper partitioning
of the code across the classes.
• Internal implementation can be changed without affecting the user level code.
C++ Templates :
A C++ template is a powerful feature added to C++. It allows you to define the generic
classes and generic functions and thus provides support for generic programming.
Generic programming is a technique where generic types are used as parameters in
algorithms so that they can work for a variety of data types.
1. Function Templates :
We can define a template for a function. For example, if we have an add() function,
we can create versions of the add function for adding the int, float or double type
values.
2. Class Template:
We can define a template for a class. For example, a class template can be created for
the array class that can accept the array of various types such as int array, float array
or double array.
Function Template :
• Generic functions use the concept of a function template. Generic functions define a
set of operations that can be applied to the various types of data.
• The type of the data that the function will operate on depends on the type of the
data passed as a parameter.
• A Generic function is created by using the keyword template. The template defines
what function will do.
Where
Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Result :
Addition of i and j is :5
Addition of m and n is :3.5
CLASS TEMPLATE :
Class Template can also be defined similarly to the Function Template. When a class
uses the concept of Template, then the class is known as generic class.
Syntax :
template<class Ttype>
class class_name
{
.
.
}
Ttype is a placeholder name which will be determined when the class is instantiated.
We can define more than one generic data type using a comma-separated list. The
Ttype can be used inside the class body.
};
int main()
{
A<int> d;
d.add();
return 0;
}
Output :
Addition of num1 and num2 : 11
Function Templates with Multiple Parameters :
We can use more than one generic type in the template function by using the comma to
separate the list.
Syntax:
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
In the above syntax, we have seen that the template function can accept any number
of arguments of a different type.
#include <iostream.h>
#include<conio.h>
template<class X,class Y> void fun(X a,Y b)
{
cout << "Value of a is : " <<a<<endl;
cout << "Value of b is : " <<b<<endl;
}
int main()
{
fun(15,12.3);
return 0;
getch();
}
Output :
Value of a is : 15
Value of b is : 12.3
Overloading a Function Template:
We can overload the generic function means that the overloaded template functions
can differ in the parameter list.
Example :
#include <iostream.h>
#include<conio.h>
template<class X> void fun(X a)
{
cout << "Value of a is : " <<a<<endl;
}
template<class X,class Y> void fun(X b ,Y c)
{
cout <<"Value of b is : " <<b<<endl; Output :
cout <<"Value of c is : " <<c<<endl;
} Value of a is : 10
int main() Value of b is : 20
{ Value of c is : 30.5
fun(10);
fun(20,30.5);
return 0;
getch();
}
Stream computation with console:
Console input / output function take input from standard input devices and compute
and give output to standard output device.
Generally, keyboard is standard input device and monitor is standard output device.
In case of C++ it uses streams to perform input and output operations in standard
input output devices (keyboard and monitor). A stream is an object which can either
insert or extract the character from it.
The standard C++ library is iostream and standard input / output functions in C++ are:
1. cin
2. cout
A) void get() :
It is a method of cin object used to input a single character from keyboard. But its main
property is that it allows wide spaces and newline character.
Syntax:
char c=cin.get();
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
char c=cin.get();
cout<<c<<endl;
getch();
}
Output :
I
I
B) void put() :
It is a method of cout object and it is used to print the specified character on the
screen or monitor.
Syntax :
cout.put(variable / character);
Example:
#include<iostream>
#include<conio.h>
void main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('c'); //Here it prints the character 'c';
getch();
}
Output :
I
Ic
C) getline(char *buffer,int size) :
This is a method of cin object and it is used to input a string with multiple spaces.
Syntax :
char x[30];
cin.getline(x,30);
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;
getch();
}
Output :
Enter name : kanhaiya
kanhaiya
D) write(char * buffer, int n) :
It is a method of cout object. This method is used to read n character from buffer
variable.
Syntax :
cout.write(x,2);
Example:
#include<iostream.h>
#include<conio.h>
void main()
{
cout<<"Enter name : ";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout.write(c,9); //It reads only 9 character from buffer c;
getch();
}
Output :
Enter name : kanhaiya
kanhaiya
E) Cin :
It is the method to take input any variable / character / string.
Syntax :
cin>>variable / character / String / ;
Example :
#include<iostream.h>
#include<conio.h>
void main()
{
int num;
char ch;
string str;
cout<<"Enter Number"<<endl;
cin>>num; //Inputs a variable;
cout<<"Enter Character"<<endl;
cin>>ch; //Inputs a character;
cout<<"Enter String"<<endl;
cin>>str; //Inputs a string;
getch();
}
F) cout
This method is used to print variable / string / character.
Syntax :
cout<< variable / charcter / string;
Example :
#include<iostream.h>
#include<conio.h>
void main()
{
int num=100;
char ch='X';
string str="Deepak";
cout<<"Number is "<<num<<endl;
cout<<"Character is "<<ch<<endl;
cout<<"String is "<<str<<endl;
getch();
}
2) Formatted console input output operations :
In formatted console input output operations we uses following functions to make
output in perfect alignment. In industrial programming all the output should be
perfectly formatted due to this reason C++ provides many function to convert any file
into perfect aligned format. These functions are available in header file <iomanip>.
iomanip refers input output manipulations.
A) width(n) :
This function is used to set width of the output. Means space between
two answers.
Syntax :
cout<<setw(int n);
Example :
#include<iostream.h>
#include<iomanip.h>
#include<conio.h> output : 10
void main()
{
int x=10;
cout<<setw(20)<<x;
getch();
}
B) fill(char) :
This function is used to fill specified character at unused space.
Syntax:
cout<<setfill('character')<<variable;
Example :
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
getch();
}
Output :
##################10
C) precison(n) :
This method is used for setting floating point of the output.
Syntax :
cout<<setprecision('int n')<<variable;
Example :
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
getch();
}
Output :
10.123
File Handling using File Streams in C++ :
File represents storage medium for storing data or information. Streams refer to
sequence of bytes. In Files we store data i.e. text or binary data permanently and use
these data to read or write in the form of input output operations by transferring bytes
of data. So we use the term File Streams/File handling. We use the header file
<fstream.h>.
• ofstream: It represents output Stream and this is used for writing in files.
• ifstream: It represents input Stream and this is used for reading from files.
• fstream: It represents both output Stream and input Stream. So it can read from files
and write to files.
#include<iostream.h>
#include<conio.h>
#include <fstream.h>
void main()
{
fstream st;
st.open(“hello.txt",ios::out);
cout<<"New file created";
st.close();
}
getch();
}
Writing to a File :
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
void main()
{
fstream st;
st.open(“hello2.txt",ios::out);
cout<<"New file created";
st<<"Hello";
st.close();
getch();
}
Reading from a File :
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
void main()
{
fstream st;
st.open(“hello2.txt",ios::in);
char ch[10];
st >>ch;
cout << ch;
st.close();
getch();
}
Close a File :
It is done by FilePointer.close().
Example :
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
void main()
{
fstream st;
st.open(“abc.txt",ios::out);
st.close();
getch();
}
Exception Handling in C++ :
Errors can be broadly categorized into two types. We will discuss them one by one.
1. Compile Time Errors
2. Run Time Errors
Syntax:
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}
1. try block
The code which can throw any exception is kept inside(or enclosed in) atry block. Then,
when the code will lead to any error, that error/exception will get caught inside the
catch block.
2. catch block
catch block is intended to catch the error and handle the exception condition. We can
have multiple catch blocks to handle different types of exception and perform different
actions when the exceptions occur. For example, we can display descriptive messages
to explain why any particular exception occurred.
3. throw statement
It is used to throw exceptions to exception handler i.e. it is used to communicate
information about error. A throw expression accepts one parameter and that parameter
is passed to handler.
throw statement is used when we explicitly want an exception to occur, then we can
use throw statement to throw or generate that exception.
Understanding Need of Exception Handling :
#include <iostream.h>
#include<conio.h>
void main()
{
int a=10,b=0,c;
c=a/b;
cout<<c;
getch();
}
The above program will not run, and will show runtime error on screen, because we
are trying to divide a number with 0, which is not possible.
How to handle this situation? We can handle such situations using exception handling
and can inform the user that you cannot divide a number by zero, by displaying a
message.
Using try, catch and throw Statement :
#include <iostream.h>
#include<conio.h> In the code above, we are checking the
void main() divisor, if it is zero, we are throwing an
{ exception message, then the catch block
int a=10, b=0, c; catches that exception and prints the
// try block activates exception handling message.
try Doing so, the user will never know that
{ our program failed at runtime, he/she
if(b == 0) will only see the message "Division by
{ zero not possible".
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
return 0;
}
Output :
Division by zero not possible