0% found this document useful (0 votes)
193 views187 pages

C++s Slides DEC 20 19 Uverted

This document contains code snippets demonstrating the use of switch statements in C++. It discusses some key properties of switch statements including: 1) The expression in a switch must be an integral type like int or char. 2) The default case can be placed anywhere and will execute if no other case matches. 3) Not including a break in some cases will cause subsequent cases to also execute. 4) Switch statements are generally faster than long if-else if chains when evaluating the same conditions since it does direct jumping rather than sequential comparisons.

Uploaded by

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

C++s Slides DEC 20 19 Uverted

This document contains code snippets demonstrating the use of switch statements in C++. It discusses some key properties of switch statements including: 1) The expression in a switch must be an integral type like int or char. 2) The default case can be placed anywhere and will execute if no other case matches. 3) Not including a break in some cases will cause subsequent cases to also execute. 4) Switch statements are generally faster than long if-else if chains when evaluating the same conditions since it does direct jumping rather than sequential comparisons.

Uploaded by

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

This slides no are of below slides for main

exam
Unit I Slide No 2-41
Unit II Slide No 42-58 , 158-180
Unit III Slide No 59-83
Unit IV Slide No 84-122
Unit V Slide No 123-157
Assignment will be a part of main exam.
/*Program to show char is an integer data
type.Program to print next four character
from the chatacter entered by the user*/
#include <iostream>
using namespace std;
int main()
{char ch='A’;
ch=ch+1;
cout<<ch<<endl;
ch=ch+1;
cout<<ch<<endl;
ch=ch+1;
cout<<ch<<endl;
ch=ch+1;
cout<<ch<<endl;
}
Write a program to calculate and print the sums of even and odd integers of the n natural numbers depending on users choice.

#include<iostream.h>

void main( )
{int n , sum_even =0 , sum_odd = 0, ctr = 1;
cout<<“Upto which natural number “;
cin>>n;
while(ctr<=n)
{
if(ctr%2 = = 0)
sum_even = sum_even+ctr;
else
sum_odd = sum_odd+ctr;
ctr++;
}
cout<<“\n”<<“The sum of even integers is”<<sum_even;
cout<<“\n”<<The sum of odd integers is”<<sum_odd;
}
Precedence of operators :-
1)++(post increment) , -- (post decrement)
2)++(pre increment),--(pre decrement) ,sizeof ,! (not), - , +
3)*(multiply) , / (divide) , % (modulus)
4)+(add) , - (subtract)
5)<(less than) , <=(less then or equal) , > , >=
6)==(equal) , !=(not equal)
7)&&(logical AND)
8)||(logical OR)
9)? : (conditional expression)
10)= (simple assignment) and other assignment operators
11) , (Comma operator)
Each row holds operator with same precedence.
What will be the order of evaluation of following
according to compiler:-
(a)8>3||5<2
Since logical operators(except !) have lower precedence
then relational operators
(8>3)||(5<2)
(b)!x+y>z
Logical negation operator ! Has higher precedence over
any relational or arithmetic operator So compiler will do
(((!x)+y)>z)
(c)a<4||d>e||!d>6
((a<4)||(d>e))||((!d)>6)
What will be the output of the following:-
a=3,b=6,c=4,d=2?
a+b>c&&b-c<d||b+d>=a+c
Keepig in mind that arithmetic opertaors have higher
precedence then relational operators and relational
operators have higher precedence over logical operaors.
(((a+b)>c)&&((b-c)<d))||(b+d)>=(a+c)
(1&&0)||1 = 1
Q) Ans of b=(a=3,a+1) is 4 .
Q)int i=j=k=0 is illegal correct way is first declare them
and then assign
int i,j,k;
i=j=k=0;
Conditional or Ternary operator
Let n = 500; Suppose sales = 2000;
bonus = n + sales > 1500? 250 : 50
Answer bonus will be 250.
because + has higher precedence over > and ? :
We correct the above mistake by putting parenthesis
n = 500;
Suppose sales = 2000;
bonus = n + (sales > 1500? 250 : 50)
Answer bonus will be 750.
int x, y; float value; cin>>value;
value>500?x:y=10;(Correct)
int x;const int y=25; float value; cin>>value;
value>500?x:y=10;(InCorrect y is a constant )
To find minimum of three numbers.
int x,y,z;
cin>>x>>y>>z;
int temp=(x<y)?((x<z)?x:z):((y<z)?y:z);
Type Conversions
1)Implicit Coversion
char ch=‘a’;
int val=12;
int code=val+ch;
cout <<code;//
Answer will be 109.
ch will be converted from char to int
according to the right side table and then
the addition will be done. This is
known as type promotion
Remember operations (+,-,*,/) are done on
similar data types.
void main ()
{ clrscr();
int number,factorial=1;
cout << "Enter Number To Find Its Factorial: ";
cin>>number;
for(int i=1;i<=number;i++)
{ factorial=factorial*i; }
cout<<"Factorial of Number is: " << factorial ;
return 0;
}
void main() { Output when value of
int i,j,rows; rows is given as 5
*
cout<<"Enter the number
**
of rows of half pyramid:
***
";
****
cin>>rows; *****
for(i=1;i<=rows;++i)
{ for(j=1;j<=i;++j)
{ cout<<"* ";
}
cout<<"\n";
}
}
void main() { int i,j,rows; For the value of rows =5
cout<<"Enter the number the following inverted
of rows for inverted half half pyramid will be
pyramid: "; printed:-
cin>>rows; *****
for(i=rows;i>=1;--i) ****
{ for(j=1;j<=i;++j) ***
{ **
cout<<"* "; *
}
cout<<"\n";
}
}
void main() { int i,j,rows; when value of rows is 5 the
cout<<"Enter the number following output will be
of rows to print half printed:-
pyramid of numbers : ";
1
cin>>rows;
12
for(i=1;i<=rows;++i)
123
{ for(j=1;j<=i;++j)
1234
{
12345
cout<<j<<" ";
}
cout<<"\n";
}
}
void main( ) The output of program
{clrscr(); will be:-
int i, j, k,; *
for(int i=1;i<=5;i++) ***
{ *****
for(int j=1;j<=5-i;j++) *******
{cout<<“ “; *********
}
for(int k=1;k<=2*i-1;k++)
{cout<<“*”;
}
cout<<“\n”;
}
1) The expression used in switch must be integral type ( int main()
int, char and enum). Any other type of expression is not
allowed.float not allowed in switch { int x = 2;
int main() switch (x)
{ float x = 1.1; { case 1: cout<<"Choice is 1";
switch (x) break;
{case 1.1: case 2: cout<<"Choice is 2";
cout<<"Choice is 1"; break;
break; case 3: cout<<"Choice is 3";
default: break;
cout<<"Choice other than 1, default:
2 and 3");
cout<<"Choice is
break;
wrong";
}
break;
return 0;
}
} return 0; }
/*The default block can be placed // There is no break in some
anywhere. The position of default doesn’t
matter, it is still executed if no match cases
found./* int main()
// The default block is placed above other
cases. { int x = 2;
int main() switch (x)
{ int x = 4; {case 1: cout<<"Choice is 1";
switch (x) break;
{ default: cout<<"Choice is case 2: cout<<"Choice is 2";
other than 1 and 2"; case 3: cout<<"Choice is 3 ";
break; case 4: cout<<"Choice is 4";
case 1: cout<<"Choice is 1"; break;
break; default: cout<<"Choice is
case 2: cout<<"Choice is 2"; other than 1, 2, 3 and 4\n";
break; break;
} } } }
Program to calculate area of a circle, case 1 :
a rectangle or a triangle depending cout<<“Enter radius of the circle:”;
upon users choice.
cin>>rad;
#include<iostream.h>
area = 3.14 * rad *rad;
#include<math.h> //for sqrt
cout<<“\n”<<“Circle area is”<<area;
void main( )
break;
{float area,rad,len,bre,a,b,c,s;
case 2:
int ch;
cout<<“Enter length & breadth of rectangle:”;
cout<<“Area Menu”<<“\n”;
cin>>len>>bre;
cout<<“1. Circle”<<“\n”;
area = len*bre;
cout<<“2. Rectangle<<“\n”;
cout<<“\n”<<“The area of rectangle is “;
cout<<“3 Triangle<<“\n”;
cout<<area<<“\n”;
cout<<“Enter your choice:”;
break;
cin>>ch;
case 3:
cout<<“\n”;
cout<<“Enter three sides of a triangle:”;
switch(ch)
cin>>a>>b>>c;
{
s=(a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c)); Write a program to generate
cout<<“\n”<<“The area of triangle the following series of
is “;
numbers :-
cout<<area<<“\n”;
1
break;
12
default :
123
cout<<“Wrong choice !!!!”;
1234
break;
12345
}
123456
}
1234567
Is switch faster than Case 2
if…elseif………else switch(b)
Yes it is faster {case 1:break;
Case I case 2:break;
if(b==1) case 3:break;
………….. case 4:break;
else if(b==2) case 5:break;
………………. }
else if(b==3) In both cases let us assume the value of
variable b is 5.In case 1 compiler will do
……………….. sequential comparison as b==1 first,then
else if(b==4) b==2 then b==3 then b==4 and then b==5
at the last so much time will be wasted.But
………………. in case of switch statement the execution
will directly go to case 5.Thus switch
else if(b==5) based implementation will be in general
always faster than equivalent nested if
else implementation
#include<iostream> (b) Generate the following :-
using namespace std; *******
int main( ) *****
{clrscr( ); ***
for(int i = 1 ; i<=7 ; ++i) *
{ #include<iostream>
for(int j = 1 ; j< =i ; ++j) using namespace std;
{ cout<<j ; int main( )
} {for(int i =4 ; i >=1; --i)
cout<<“\n”; {for(int j = 1 ; j < =4-i ; ++j)
} { cout<< “ “; }
getch( ); for(int k = 1 ; k<=(2*i-1) ;k++)
} { cout<<“*”};
}
void main( ) Output for 5 rows of
{ int n, i, c, a = 1; Floyds triangle:-
cout << "Enter the number 1
of rows of Floyd's triangle 23
to print: ";
456
cin >> n;
78910
for (i = 1; i <= n; i++)
1112131415
{ for (c = 1; c <= i; c++)
{ cout << a;
a++; }
cout << endl;
}
}
C++ program to print the pyramid of digits in pattern as below.

void main() { int count=0,count1=0; count1=count-2;


cout<<"Enter the number of rows: "; for(int j=1; j<=i-1;j++)
cin>>rows; {cout<<count1;
for( int i=1;i<=rows;++i) count1=count1-1;
{ for(space=1;space<=rows-i;++space) }
{ cout<<" "; } cout<<“\n”;
if(i==1) }//else closed
cout<<“1 \n”; }//for closed
else }//main closed
{ count = i; 1
for(int j=1; j<=i;j++) 232
{cout<<count; 34543
count=count+1; 4567654
} 567898765
C++ Program to Find Largest Number Among Three Numbers(Using if)
void main() {
int n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if(n1>=n2 && n1>=n3)
{ cout << "Largest number: " << n1; }
if(n2>=n1 && n2>=n3)
{ cout << "Largest number: " << n2; }
if(n3>=n1 && n3>=n2)
{ cout << "Largest number: " << n3; }
return 0;
}
int main() //Program to find largest of three numbers using if….else
{ int n1, n2, n3; cout << "Enter three numbers: "; cin >> n1 >> n2 >> n3;

if (n1 >= n2)


{ if (n1 >= n3)
{ cout << "Largest number: " << n1; }
else
{ cout << "Largest number: " << n3; }
}
else
{ if (n2 >= n3)
{ cout << "Largest number: " << n2; }
else
{ cout << "Largest number: " << n3; }
}
//Program to find largest of three numbers using if….else if…..else
statement or ladder.
void main()
{ int n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
{ cout << "Largest number: " << n1; }
else if ((n2 >= n1) && (n2 >= n3))
{ cout << "Largest number: " << n2; }
else
{ cout << "Largest number: " << n3; }
}
//Program to find largest of three numbers using if….else
if…..else statement or ladder.
void main()
{ int n1, n2, n3,max;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
max=n1;
if(n2>max)
max=n2;
if(n3>max)
max=n3;
cout<<“Largest number is “<<max;
}
//Program to print Fibonacci series. 0 1 1 2 3 5 8 ……………….
int main()
{
int firstTerm=0,secondTerm=1, thirdTerm ,n;
cout << "Enter the number of terms to print of fibonacci series ";
cin >> n;
cout << endl << firstTerm <<" " <<secondTerm << " " ;
for(int i =1; i<=(n-2); i++)
{
thirdTerm = firstTerm+ secondTerm;
cout << c << " ";
firstTerm=secondTerm;
secondTerm=ThirdTerm;
}
/*C++ program to print prime numbers from 1 to n*/
int main()
{ int num,n,div,p;
cout<<"Enter the value of n:”;
cin>>num;
for(n=2; n<=num; n++)
{p=1;
for(div=2; div<n/2; div++)
{ if(n%div==0)
{ p=0;
break;
}
}
if(p)
cout<<n;
}
getch();
return 0;
//Program to check whether a given number is
Armstrong or not, palindrome or not if(num==n)

int main() cout << n << " is Armstrong.";


else
{int n, n1,rem, num=0,rev=0,digits=0;
cout << n << " not Armstrong ";
cout << "Enter a positive integer: ";
cin >> n; n1=n;
n1=n; n2=n; while(n1!=0)
while(n2!=0) {rem=n1%10;
{digits++; rev=rev*10 + rem;
n2=n2/10; n1=n1/10;
} }
while(n1!=0) if(rev==n)
{ rem=n1%10; cout << n << " is Palindrome.";
num=num+pow(rem,digits); else
n1=n1/10; cout << n << " not Palindrome ";
} getch(); }
For even number of For odd number of
lines pyramid lines pyramid
ex lines=7 ex lines=8
* *
*** ***
***** *****
******* *******
***** *******
*** *****
* ***
*
int main( ) if(i==(lines+1)/2 && (lines%2)==0)
{int lines; {
cout<<“\n Enter number of }
lines”; else if(i<(lines+1)/2)
cin>>lines; {space=space-1;
int stars=1,space=lines/2; stars=stars+2;
for(int i=1; i<=lines; i++) }
{ else
for(int j = 1;j<=space;j++) {space=space+1;
cout<<“ “; stars=stars-2;
for(int k=1;k<=stars;k++) }
{cout<<“*”; cout<<endl;
} }
}
int main(){ for(int k=1;k<=numbers;k++)
int lines; {if(i<=(lines+1)/2)
cout<<"Enter number of lines"; {cout<<x;
cin>>lines; if(k<=i-1)
int numbers=1,x,space=lines/2; x++;
for(int i=1; i<=lines; i++) else
{x=i; x--;
for(int j = 1;j<=space;j++) }
cout<<" "; else
{cout<<x;
if(k<=lines-i) x++;
else x--;
}
}
if(i<(lines+1)/2) 1
{space=space-1;
232
numbers=numbers+2;
} 34543
else 4567654
{space=space+1; 56765
numbers=numbers-2;
676
}
cout<<endl; 7
}
}
#include<iostream> 5
#include<math.h> 45
using namespace std; 345
int main( )
2345
{int i,j,x;
cout<<“Enter the number of 12345
lines”; 012345
cin>>x;
12345
for(int i=x;i>=-x;i--)
{for(int j=abs(i);j<=x;j++) 2345
{cout<<j; } 345
cout<<endl; 45
}
5
#include <iostream>
int main()
using namespace std;
{int n;
int main(){ int n;
cout<<"Enter the number of
cout<<"Enter the number of lines
lines to print z design for ";
to print sand box design for ";
cin>>n; cin>>n;
for (int i =1;i <=n; i++) for (int i =1;i <=n; i++)
{for (int j =1; j <=n; j++) {for (int j =1; j <=n; j++)
{ if (i==n||(i+j)==n+1 || i==1) { if (i==n||(i+j)==n+1 ||i==1||i==j)
cout<<"*"; cout<<"*";
else else
cout<<“ “; cout<<" " ;
} }
cout<<endl; cout<<endl;
} }
} }
int main( )
{int num,sumneg,sumeven,sumodd;
sumneg=sumeven=sumodd=0;
do
{cout<<“\nEnter 0 to terminate”;
cin>>num;
if(num<0)
sumneg=sumneg+num;
else if(num%2==0)
sumeven=sumeven+num;
else
sumodd=sumodd+num;
}while(num!=0);
cout<<sumneg<<sumeven<<sumodd;
}
int main( ) 2)for(i=10;i<=50;i=i+10)
{int i,num; j=i/2;
cout<<“Enter an integer”; cin>>num;
cout<<j<<“ “;
for(i=1;i<=num/2;++i)
Ans 25
{ if(num%i==0)
3)int f=1,i=2;
cout<<endl<<i;
while(++i<5)
}
f=f*i;
}
cout<<f;
Q)for(i=10;i<=50;i=i+10)
Ans 12
{j=i/2;
4) int f=1,i=2;
cout<<j<< “ “;
do{
}
f=f*i;
cout<<endl<<i;
}while(++i<5);
Ans 5 10 15 20 25
cout<<f;
60
1 2 4 8 16 32 64 128 int main( )
{int i,num;
int main( )
cout<<“Enter an integer;”
{ cin>>num;
for(int i=1; ; ) for(int i=1;i<=num/2;i++)
{cout<<i<“ “; { if(num%i==0)
cout<<“\n”<<i;
if(i==128)
}
break; }
i=i*2;
}
}
Write a program to #include<math.h>
print the sum of void main()
{int i ,j,x,n,fact, sign=-1,sum=0;
cos(x) series take
cin>>x>>n;
the number of
for( i=2;i<=n;i=i+2)
terms to sum and {fact=1;
the value of x numerator=pow(x,2);
from user. for( j=1;j<=i<j++)
{ fact = fact*j; }
sum=sum+sign*(numerator/fact);
sign=sign*-1;
}
cout<<1+sum;
}
char ch=‘A’; A label may not immediately
do{cout<<endl<<ch; precede a closing brace.
ch++; {goto last :
}while(ch<=‘Z’);
This will print A to Z. last:
}
The goto statement You can correct this by putting
semicolon
a=0;
{goto last :
start:
cout<<endl<<++a;
last: ;
if(a<50) goto start;
}
The above will print numbers
from 1 to 50
int main() //Forward jumping not allowed But backward jumping over an
{goto last ; initialized variable is allowed in
char ch=‘a’; C++.
last : int main() //Backward jumping allowed
………… {
…………
last :
}
/*Forward jumping Allowed when variable definition is occurring in block.*/ char ch=‘a’;
…………
int main()
…………
{goto last ;
goto last ;
{char ch=‘a’;
}
}
last :
…………
…………
int a,b,c,i; int main( )
for(i=0;i<20;++i) {int i;
{cout<<“Enter 2 numbers”; for(i=1;i<=10;i++)
cin>>a>>b; { if((i%3)==0)
if(b==0) break;
break; else
else cout<<i<<endl;
c=a/b; } Ans 1 2
cout<<“\n for(i=1;i<=10;i++)
Quotient=“<<c<<endl; { if((i%3)==0)
} continue;
/*You can write continue in place of break
but meanings are different .break will else
immediately take you out of loop but cout<<i<<endl;
continue will stop the current iteration and
will start the next loop iteration.*/ }Ans 1 2 4 5 7 8 10
int main(){ int i=298; int main(){ int i=298;
char ch; float f=i; //safe initialization
ch=i; //unsafe initialization cout<<f;
cout<<ch; }
} Output 298.00
Output will be * which is the
ASCII value of 42.
298 binary is 100101010 which
is of nine bits but char ch can
store only 8 bits and the left
side 1 will be lost at the time of
storage so 00101010 will be
stored in ch which is the binary
of 42.
42 is the ASCII of *.
void main() // Call by value method of parameter passing
{void swap(int , int ) ; //Local Function Declaration or Function prototype
int a =7,b=4;
cout<<“\n Orignal values are\n”<<“a=<<a<<“b=“<<b;
swap(a,b); // Function call to exchange value of a and b.
cout<<“\n The values after swap are :\n” <“a=“<<a<<“b=“<<b;
}
void swap (int x,int y)
{int temp;
temp=x;
x=y;
y=temp;
cout<<“\nSwapped values are”;
cout<<“a=“<<x<<“b=“<<y<<“\n”;
void main() // Call by reference method of parameter passing
{void swap(int & int &); //Local Function Declaration or Function prototype
int a =7,b=4;
cout<<“\n Orignal values are\n”<<“a=<<a<<“b=“<<b;
swap(a, b); // Function call to exchange value of a and b.
cout<<“\n The values after swap are :\n” <“a=“<<a<<“b=“<<b;
}
void swap (int &x,int &y)
{int temp;
temp=x;
x=y;
y=temp;
cout<<“\nSwapped values are”;
cout<<“a=“<<x<<“b=“<<y<<“\n”;
Returning by reference
void main( ) Only the function
{ float &min(float & , float &); returning a
float a=7,b=4; reference can
min(a,b)=-1; appear on the left
cout<<a<<b; side of an
} assignment
float &min(float &c, float &d) expression.
{if(c<d)
return c;
else
return d;
}
Default Arguments
void main( )
{ float si_int;
float interest(float principal, int time, float rate =0.10);
si_int = interest(5400,2);
}
float interest(float principal, int time, float rate)
{ float interest = principal*time*rate;
return interest;
}
Default Arguments
void main( )
{ float si_int;
float interest(flat principal, int time, float rate =0.10);
si_int = interest(5400,2,0.20);
cout<<“Simple interest is”<<si_int;
}
float interest(flat principal, int time, float rate)
{ float interest = principal*time*rate;
return interest;
}
Default Arguments
//Any arguments cannot have default value unless all
arguments to its right have their default values.
void main( )
{ flaot si_int;
float interest(flat principal, int time=2, float rate );//Illegal
si_int = interest(5400,2,0.20);
cout<<“Simple intersest is”<<si_int;
}
float interest(flat principal, int time, float rate)
{ float interest = principal*time*rate;
return interest;
}
Scope Rules
(a)#include<iostream.h> (b)int g=20;
int a =20; void func(int &x,int y)
{x=x-y;
void main()
y=x*10;
{int a=50;
cout<<x<<<<“,”<<y<<“\n”;
cout<<::a<<a<<endl; }
} void main()
(a)Output of (a) program20 5 {int g=7;
(b)Output of (b) program func(g , ::g);
-13,-130 cout<<g<<“ ,”<<::g<<endl;
-13,20 func(::g , g);
cout<<g<<“ ,”<<::g<<endl;
33,330
}
-13,33
#include <iostream>

using namespace std;

int sel=5,out=10;
int findout(){
if(sel==5)
return
out=out*2;
return 0; }
int main(){
findout();
cout<<sel<<" "<<out<<endl;
sel=8,out=7;
findout();
cout<<sel<<" "<<out;}
Output:-
5 20
8 7
Use of boolean data type in C++
• #include <iostream>
bool isEven(int n)
{ if(n%2 == 0)
return true;
else
return false;
}
void main()
{ int num;
cin >> num;
if(isEven(num))
cout << "Number is even." << endl;
else
cout << "Number is odd." << endl;}
Generating random #include<stdlib.h>
numbers in C++ int main( )
By default rand( ) generates random
numbers within range 0 to to RAND- {randomize( );
MAX.If you want to generate random int num,rndnum;
numbers within a specified range say 0
to 50.then lower limit L is 15 and upper cin>>num;
lmit U is 50
rndnum=random(num)+7;
then simply change rand( ) to :-
15+(rand()%(50-15+1)) for(int n=1;n<=rndnum;n++)
L+(rand()%(U-L+1) cout<<n;
}Output :- (Possible)
1234567891011
random(num) generates a
random number within range
0 to num-1. First, randomize() or srand() here are a
way of giving a new seed to the random-number
generator, so that each time the program runs the
results will be different. (Though it uses the current
time as a seed - if it was run more than once during
the same second the output would not change).
#include<iostream.h>
#include<stdlib.h>
int main ( )
{randomize( );
int game[ ] ={10,16},p;
int turn = random(2)+5;
for(int t=0;t<2;t++)
{p=random(2);
cout<<game[p]+turn;<<‘#’;
}
}
Options:-
(i)15#22#
(ii)22#16#
(iii)16#21#
(iv)21#22#
Ans(ii) Output can be expected.
Write C/C++ code to void expand(int value)
convert given number into { const char * const ones[20]
words for 4 digit numbers. = {"zero", "one", "two",
"three","four","five","six","seven",
eg:- Input: 1234 "eight","nine","ten","eleven","twelve",
Output: One thousand two "thirteen","fourteen","fifteen","sixteen",
hundred thirty-four. "seventeen","eighteen","nineteen"};
void expand(int); const char * const tens[10] =
int main() {"","ten","twenty","thirty","forty",
{ int num; "fifty","sixty","seventy",
cout<<"Enter a number : "; "eighty”,”ninety”};
cin>>num; if(value<0)
expand(num); { cout<<"minus ";
} expand(value);
}
}
else if(value>=1000) else if(value >= 100)
{ expand(value/1000); {
cout<<" thousand"; expand(value / 100);
cout<<" hundred";
if(value % 1000) if(value % 100)
{ {
if(value % 1000 < 100) cout << " and ";
{ expand (value % 100);
cout << " and"; }
} }
cout << " " ;
expand(value % 1000);
}
else if(value >= 20)
{
cout << tens[value / 10];
if(value % 10)
{
cout << " ";
expand(value % 10);
}
}
else
{
cout<<ones[value];
}
return;
// Program to find and return the sum of elements from all
alternate elements of a 2D array
int SKIPSUM(int A[][3], int N, int M)
{int sum=0;
for(int i=0;i<N,i++)
{ for(int j=0;j<M;j++)
{if(i+j)%2==0)
sum=sum+A[i][j];
}
}
return sum;
}
void COLSUM(int A[ ],int N)
{int r,c,csum[N];
for(c=0;c<N;c++)
{csum[c]=0;
for(r=0;r<N;r++)
csum[c]=csum[c]+A[r][c];
}
void REVCOL(int P[][5],int N,int M)
{int i,j;
for(j=0;i<=N-1;j++)
{ for(i=M-1;i>=0;i--)
cout<<P[i][j]<<‘ ‘;
cout<<endl;
}
Write a function in C++ which accepts an integer array and its size as arguments/parameters and exchanges the values of
first half side elements with the scond half side elements of the array.

void swap(int A[ ] ,int size)


{int i, j, tmp, mid=size/2;
if(size%2==0)
j=mid;
else
j=mid+1;
for(i=0;i<mid;i++,j++)
{tmp=A[i];
A[i]=A[j];
A[j]=tmp;
}
}
//Program to calculate average and total
sales of a month of a shop.
int main( )
{int size=31;
float sales[size],avg=0,total=0;
for(int i=1;i<=size;i++)
{cout<<“Enter sales for <<i<<day <<endl;
cin>>sales[i];
total=total+sales[i];
}
avg=total/size;
cout<<“Total sales of month”<<total;
cout<<“Average sales of month ” << avg;
}
Program to check if a string is palindrome or not.
if(flag)
#include<iostream.h>
cout<<“Palindrome”;
using namespace std;
else
int main( )
cout<<“Not Palindrom” ;
{ char string[80];
return 0;
cout<<“Enter string (max 79 characters) “;
}
gets(string);
for(int len = 0 ; string[len]!=‘\0’ ; len ++) ;
int i , j , flag = 1;
for(i = 0, j=len-1 ;i<len/2 ; i++,j--)
{ if(string[i]!=string[j]
{flag = 0;
break ;
}
}
Write a program to reverse a string.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main( )
{clrscr( );
char str[80];
int i ,j;
cout<<“\n Enter any string(max 80)”;
gets(str);
for( i =0 ; str[i]! = ‘\0’ ; ++ i );
char rev[80];
int k;
for( j = i – 1 , k = 0 ; j> = 0 ; --j ,++ k)
{rev[k ] = str[j]; }
rev[k ] = ‘\0’;
cout<<“\n String in reverse order is : “;
puts(rev);
getch( );
}
Program to delete a substring from a string.
#include<iostream.h>
#include<conio.h>
void main( )
{clrscr( );
char str[80];
int i , p , n ,len;
cout<<“\n Enter any string(max 79)”;
cin.getline(str,80);
for( len =0 ; str[len]! = ‘\0’ ; ++ len );
cout<<“Enter the starting position of substring to be deleted”;
cin>>p;
if(p>len)
cout<<“Starting position must be less than the length of string”;
else
{cout<<“\n Enter the number of characters of substring to be deleted : “;
cin>>n;
if(n+p> len+1)
n = len – p + 1;
for( i = p-1 ; ; ++i)
{str[i] = str[i+n];
if(str[i]= = ‘\0’)
break;
}
cout.write(str,80);
}
Write a program that reads a string/line of text and displays the string with each
pair of adjacent letter reversed in individual words.For example if,the line of text
entered is “hello there” then it should print “ehllo htree”.
#include<iostream>
#include<stdio.h> char ch1;
#include<string.h>
for(int k=i;k<j;k=k+2)
using namespace std;

int main(){ {if(string[k+1]==' ' || string[k+1]=='\0’)


char string[50]; break;
cout<<“Enter the string”; ch1=string[k];
cin.getline(string,50); string[k]=string[k+1];
int len=strlen(string); string[k+1]=ch1;
int i=0,j,last=0; }
for(j=0;j<len;j++) i=j+1;
{ }
while(string[j]!=' ' && string[j]!='\0’) cout.write(string,len);
j++; }
//Program to find all positions of a given word(substring) in a
line. for(j=0;j<len;)
#include<iostream>
#include<stdio.h>
{if(line[j]==sub[0])
#include<string.h> {foundf=j;
using namespace std; k=0;
int main( ){ while(line[j]==sub[k])
int foundf; {j=j+1;
char line[80]; k=k+1;
char sub[15]; if(sub[k]=='\0')
cout<<"Enter line of text\n"; {cout<<foundf<<endl;
cin.getline(line,80); break;
cout<<"Enter substring to }
find\n"; } // end of while
cin.getline(sub,15); }// end of if

int len=strlen(line); else


int i,j,k,spos,lpos; j++;}}// end of for and main
If input is Mohandas while(line[i]!='\0')
Karamchand Gandhi . {if(line[i]==' ') k=i+1;
The program should i=i+1;}
display M.K. Gandhi line[0]=toupper(line[0]);
#include<iostream> if(k==0)
#include<ctype.h> {cout<<line;}
using namespace std; else
int main() {cout<<line[0]<<". “<<“ “;
{ for(j=0;j<=i-1;j++)
int i=0,j,k=0; { if(line[j]==' '&&j!=k-1)
char line[51]; {line[j+1]=toupper(line[j+1]);
cout<<"ENTER A NAME (NOT if(line[j+1]!=‘ ’)
MORE THAN 50)\n"; cout<<line[j+1]<<".";
cin.getline(line,51); }
line[k]=toupper(line[k]); Q)If 1 D array is 1 2 3 .The resultant 2D array is given
below:-
cout<<line[k]; 123

for(int x=k+1;x<=i-1;x++) 120


100
{ line[x]=tolower(line[x]);
cout<<line[x]; void func(int arr[ ],int size)
} {int i,j ,a2[20][20];
}// end of else for(i=0;i<size;i++)
return 0; { for(j=0;j<size;j++)
} { if(i+j)>=size)
a2[i][j]=0;
else
a2[i][j]=arr[j];
cout<<a2[i][j]<<“ “;
}
}
/*Each array has a string.We have two arrays .We want to concatenate strings of two arrays into a third array*/

int main( )
{char str1[25] , str2[25 ] , str3[50];
int i,k,x1;
cout<<“\n Enter first string(max 24 characters) :\n”;
cin.getline(str1,25);
cout<<“\n Enter second string(max 24 characters) :\n”;
cin.getline(str2,25);
for(i = 0 ; str1[i]! = ‘\0’ ; ++i)
str3[i] = str1[i];
for(k = 0 ; str2[k]! = ‘\0’ ; ++k)
str3[i++] = str2[k];
str3[i]='\0';
x1 = strlen(str3);
cout<<“\n The concatenated string is : \n “;
cout.write(str3 , x1);
}
------------------------------XXXXXXXXXXX-----------------
if int A[4]={1,2,3,4}; find output of:-
for (i = 0 ; i<4 ; ++i)
A[i+1] = A[i];
for (i = 3 ; i>=0 ; --i)
A[i+1] = A[i];
Program to reverse words of a for(i=0;str[i]!=‘\0’;i++)
string individually {if(str[i]!= ‘ ‘)
eg If you enter iet is great { word[k]=str[i];
it should display: tei si taerg. k=k+1;
#include<iostream> }
#include<stdio.h> else
#include<string.h> {
int main() while(k>=0)
{int i, j , k=0; {k=k-1;cout<<word[k];}
char str[80],word[80]; cout<<str[i];
cout<<“Enter any string(max }
79 chars)”<<endl;
}// end of for
gets(str);
return 0;
strcat(str,” “);
}
Program to convert a cout<<“\nEnter any string(max 80
string to proper case ie chars):”;
to capitalize first letter gets(str);
of each word of the str[0]=toupper(str[0]);
string eg if the string is for(i=1;str[i]!=‘\0’;i++)
:mira rehaan Augustine { if(str[i])==‘ ‘)
it should display it as : str[i+1] = toupper(str[i+1]);
Mira Rehaan Augustine }
#include<iostream> puts(str);
#include<stdio.h> return 0;

#include<ctype.h> }

int main()
{char str[80];
int i;
Write a program to print all the LEADERS in the array. An element
is leader if it is greater than all the elements to its right side. And
/* Driver program to test above
the rightmost element is always a leader. For example in the array function */
{16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
int main()
void printLeaders(int arr[],int size)
{
{ for (int i = 0; i < size; i++)
int arr[] = {16, 17, 4, 3, 5, 2};
{ int j;
int n = sizeof(arr)/sizeof(arr[0]);
for (j = i+1; j < size; j++)
printLeaders(arr, n);
{ if (arr[i] <= arr[j])
return 0;
break;
}
}
if (j == size)
// the loop didn't break
cout << arr[i] << " ";
}
}
Digital Root (repeated digital sum) of the else {
given large integer
The digital root of a positive integer is found by summing the int dsum = 0;
digits of the integer. If the resulting value is a single digit then
that digit is the digital root. If the resulting value contains two
or more digits, those digits are summed and the process is
int temp = n;
repeated. This is continued as long as necessary to obtain a
single digit. while (temp > 9) {
Input : num = "1234" n = temp;
Output : 1
dsum = 0;
Explanation : The sum of 1+2+3+4 = 10,
digSum(x) == 10 while (n > 0) {
Hence ans will be 1+0 = 1 dsum += n % 10;
Input : num = "5674" n /= 10;
Output : 4
}
int n;
cout<<"Enter a positive integer: "; temp = dsum;
cin>>n; }
//If the input is one digit to begin with, print it; we're done.
cout<<"The digital root is" <<
if (n <=9) {
temp;
cout<<"The digital root is " <<n;
}
//Program to print largest and smallest word of a line entered by
user while (ei <= len)
#include<iostream> { if (ei < len && line[ei] != ' ')
#include<cstring> ei++;
using namespace std; else
int main(){ { int curr_length = ei - si;
char line[50] = "Indians are if (curr_length < min_length)
great"; { min_length = curr_length;
min_start_index = si; }
int len = strlen(line) ;
if (curr_length > max_length)
int si = 0, ei = 0;
{max_length = curr_length;
int min_length = len; max_start_index = si; }
int min_start_index = 0; ei++;
int max_length = 0; si = ei;
}
int max_start_index = 0;
}
// Loop while input string is not
empty
cout<<"The smallest word in line is"<<endl;
for(int i=min_start_index ; i<min_start_index+min_length;i++)
cout<<line[i];
cout<<endl;
cout<<"The largest word in line is"<<endl;
for(int i=max_start_index ; i<max_start_index+max_length;i++)
cout<<line[i];
}
Write a program to calculate for( j =0 ; j<3;j++)
grades of 4 students from 3 { cin>>marks[i][j];
test scores. sum = sum + marks[i][j];
# include<iostream> }
using namespace std; avg = sum/3;
int main( ) if(avg<45.0)
{float marks[4][3] ,sum ,avg; grade[i] = ‘D’;
char grade[4]; else if(avg<60.0)
int i, j; grade[i] = ‘C’;
for(int i =0 ; i<4 ; i++) else if (avg<75.0)
{ sum =avg =0; grade [i]=‘B’;
cout<<“Enter 3 scores of else
student”<<i+1<<“ : “ ; grade[i]=‘A’;
}
for( i =0 ; i<4; i++)
{
cout<<“Student”<<i+1<<“\tTotal marks =“<<marks[i][0]
+marks[i][1] + marks[i][2] << “\tGrade = “<<grade[i]<<“\n”;
}
return 0; } // End of main
Enter 3 scores of student 1 : 78 65 46
Enter 3 scores of student 2 : 56 65 66
Enter 3 scores of student 3 : 90 89 92
Enter 3 scores of student 4 : 78 65 46
Student 1 Total Marks = 189 Grade = B
Student 2 Total Marks = 187 Grade = B
Student 3 Total Marks = 271 Grade = A
Student 4 Total Marks = 189 Grade = B
#include<iostream.h> cout<<“\nMatrix A is:”;
using namespace std; for(i = 0 ; i<3;++i)
int main( ) {cout<<“\n”;
for(j=0;j<3;++j)
{
cout<<A[i][j]<<“ “;
int A[3][3] , B[3][3],C[3][3];
cout<<“\n Enter the elements of }
Matrix A :\n”; cout<<“\nMatrix B is:”;
for(i = 0 ; i<3;++i) for(i = 0 ; i<3;++i)
for(j=0;j<3;++j) {cout<<“\n”;
cin>>A[i][j]; for(j=0;j<3;++j)
cout<<“\n Enter the elements of cout<<B[i][j]<<“ “;
Matrix B :\n”;
}
for(i = 0 ; i<3;++i)
for(j=0;j<3;++j)
cin>>B[i][j];
cout<<“ \n Addition of two matrices : “;
for( i = 0 ; i < 3 ; ++i)
{ cout<<“\n” ;
for( j = 0 ; j <3 ; ++j)
{ C[i][j] = 0 ;
C[i][j] = A[i][j] +B [i][j];
cout<<C[i][j] << “ “;
}
}
#include<iostream.h>
using namespace std;
int main( )
{
int A[10][10] , B[10][10],C[10[10];
int m , n , p , q , k , I, j;
cout<<“\n Enter the rows and columns of Matrix A:\n”;
cin>>m>>n;
cout<<“\n Enter the rows and columns of Matrix A:\n”;
cin>>p>>q;
if(n==p)
{
cout<<“\n enter the elements of Matrix A :\n”;
for(i = 0 ; i<3;++i) cout<<“\nMatrix B is:”;
for(j=0;j<3;++j) for(i = 0 ; i<3;++i)
cin>>A[i][j]; {cout<<“\n”;
cout<<“\n Enter the elements of for(j=0;j<3;++j)
Matrix B :\n”; cout<<B[i][j]<<“ “;
for(i = 0 ; i<3;++i) }
for(j=0;j<3;++j)
cin>>B[i][j];
cout<<“\nMatrix A is:”;
for(i = 0 ; i<3;++i)
{cout<<“\n”;
for(j=0;j<3;++j)
cout<<A[i][j]<<“ “;
}
cout<<“ \n Product of two matrices : “;
for( i = 0 ; i < 3 ; ++i)
{ cout<<“\n” ;
for( j = 0 ; j <3 ; ++j)
{ C[i][j] = 0 ;
for(k = 0 ; k < 3 ; ++k)
C[i][j] = C[i][j] + A[i][k] * B [k][j];
cout<<C[i][j] << “ “;
}
}
}// end of if
else
cout<<“\n Matrices cant be multiplied”;
}
#include<iostream>//CLASS DEMONSTRATION
using namespace std;

class item
{ private:
int number;
float cost;
public:
void getdata( int a, float b);
void putdata(void)
{ cout<<“number :”<<number<<“\n”;
cout<<“cost :”<<cost<<“\n”;
}
};
void item:: getdata( int a, float b)
{ number=a;
cost=b;
}
// C++ program to illustrate the iterators in vector
#include <iostream>
#include <vector>
#include<algorithm> // for sort function
using namespace std;
int main()
{vector<int> g1;
for(int i =1; i <= 5; i++)
g1.push_back(i);
cout<<"Output of begin and end: ";
for (auto i = g1.begin(); i != g1.end(); ++i)
cout << *i << " ";
cout << "\nOutput of rbegin and rend: ";
for (auto ir=g1.rbegin();ir!= g1.rend(); ++ir)
cout << *ir << " ";
}
sort(g1.begin(),g1.end());
}
Output of begin and end: 1 2 3 4 5
Output of rbegin and rend: 5 4 3 2 1
#include <bits/stdc++.h> v.pop_back(); // removes last element
#include <vector> cout << "\nThe vector elements ar";
using namespace std; for (int i = 0; i < v.size(); i++)
int main() { cout << v[i] << " ";
vector<int> v; cout<<endl;
v.assign(5, 10); // fill the array with 10 five times // inserts 5 at the beginning
cout << "The vector elements are: v.insert(v.begin(), 5);
"; vector<int>::iterator t =v.begin()+1;
for (int i = 0; i < v.size(); i++) v.insert(t,5);
cout << v[i] << " "; //Final elements are
v.push_back(15); // inserts 15 to the last position for (int i = 0; i < v.size(); i++)
int n = v.size(); cout << v[i] << " "; }
Output:-
cout << "\nThe last element is: " << v[n -
1]; The vector elements are: 10 10 10 10 10
TThe last element is: 15
The vector elements are: 10 10 10 10 10
5 5 10 10 10 10 10
#include<set> auto it= s.lower_bound(3);
set<int> s;
cout<<*it;//Ans is 3
s.insert(5); /*lower_bound used for finding first number>=given number
s.insert(4); upper_bound used for finding first number>given number*/
auto it= s.upper_bound(3);
s.insert(3); cout<<*it;//Ans is 4
for(int x:s) auto it= s.upper_bound(10);

cout<<x<<“ “; if(it==s.end())
auto it=s.find(5)
cout<<“Sorry cant find
if(it==s.end())
upperbound”;
cout<<“Value is not present”;
else
cout<<“Value is present”;
cout<<*it;
#include<bits/stdc++.h> //Demo of pair
map<int,int> A; set<pair<int,int>> s;
A[1]=50; s.insert({1,10});
A[2]=60; s.insert({11,20});
A[3]=70; s.insert({25,30});
A[4]=80; int point=19 ;
map<char,int> cnt; auto it=s.upperbound({point,INT_MAX});
string s =“Arpit Agrwal” it--;
for (char ch :s) pair<int,int> current = it;
cnt[ch]++; if(current.first<=point&&point<=current.second)
cout<<cnt[‘A’]; cout<<“yes its present in range ”
cout<<cnt[‘r’]; <<current.first<<“ “ <<current.second;
else
cout<<“It is not present”;
//Ans will be yes it is present in 11 20
int main( )
{item x;
cout<<“\nobject x “<<“\n”;
x.getdata(100,290.5);
x. putdata( );
item y;
cout<<“\n object y”<<“\n”;
y.getdata(200,220.78);
y.putdata( );
}
object x
number:100
cost: 290.5
object y
number : 200
cost : 220.78
Nesting of Member Functions
#include<iostream.h>
class set
{ private:
int m, n;
public:
void input(void);
void display(void);
int largest(void);
};
int set :: largest(void)
{ if( m>=n)
return m;
else
return n;
}
void set :: input(void)
{
cout<<“Input values of m and n”<<“\n”;
cin>>m>>n;
}

void set:: display(void)


{
out<<“Largest value=“<<largest()<<“\n”;
}

void main( )
{set s;
s.input( );
s.display( );
}
class X //Demo of Global Object
{public:
int a;
void fc(void);
};
X ob1;
void main()
{ob1.a=20;//valid
ob1.fc();//valid
}
void func1(void)
{ob1.a=20; //valid
ob1.fc() ; //valid
}
class X //Demo of Local Object ob1.fc(); //valid;
{public: ob2.i=15;//valid
int a;
ob2.afun(); //valid
void fc(void);
}
};
void main()
void func1(void)
{class Y {X ob3;
{ public: Y ob4; //invalid
int i; ob3.a=25; //valid
void afun(void); ob3.fc(); // valid
}; ob1.a=10; // Invalid
X ob1;
ob2.afunc(); //Invalid
Y ob2;
}
ob1.a=5;//valid
//Scope of public Members X ob1;
class X { private: void main()
int a; {ob1.i=10;//valid
void fc(void) ob1.fcc1();//valid
{cout<<a; } ob1.a=5; //Invalid
public: ob1.fc(); //Invalid
int i; }
void fcc1(void)
{cout<<2*i;
a=13;
fc();
}
};
/*Scope */
X ob1;
class X {
void main()
private:
{X ob2;
int a;
ob1.i=10;//valid
void fc(void)
ob1.fcc1();//valid
{cout<<a; }
ob2.i=20; //valid
public:
ob2.fc();//invalid
int i;
}
void fcc1(void)
void func1()
{cout<<2*i;
{X ob3;
a=13;
ob1.fcc1();//valid
fc();
ob2.i=25; //Invalid
}
ob2.fcc1();//Invalid
};
ob3.fcc1();
// STATIC CLASS MEMBER
#include<iostream.h>
class item
{
static int count;
int number;.
public:
void getdata(int a)
{ number = a;
count++;
}
void getcount(void)
{ cout<<“count:”;
cout<<count<<“\n”;
}
};
int item :: count;
void main()
{
item a, b, c; Output Screen:
a.getcount();
b.getcount();
count:0
c.getcount(); count:0
a.getdata(100);
b.getdata(200)
count:0
c.getdata(300) After reading data
cout<<“After reading
data”<<“\n”; count:3
a.getcount( ); count:3
b.getcount( );
c.getcount( ); count:3
}
Static Data Members

It is initialized to zero when the first object of its class is


created.
Only one copy of that member is created for the entire class and is
shared by all the object of that class, No matter how many object
are created.
It is visible only within the class, but its lifetime is the entire
program.
The declaration of a static data member in the member list of a class
is not a definition. You must define the static member outside of the
class declaration, in namespace scope.
For example:
class X
{ public: static int i; };
int X::i = 0; // definition outside class declaration
#include<iostream>

using namespace std;

int main( )

class test
{
int code;
static int count;
public:
void setcode(void)
{ code =++count;
}
void showcode(void)
{ cout<<“Object Number:”<<code<<“\n”;
}
static void showcount(void)
{
cout<<“count:”<<count<<“\n”;
}
};
int test : : count;
void main( ) Output of the program:-
{ count:2
test t1,t2; count:3
t1.setcode(); object number:1
t2.setcode(); object number:2
test :: showcount();
object number:3
test t3;
t3.setcode();
test :: showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}
Static Member Functions
A static member functions can have access to only other static members(
functions or variables) declared within the same class.

A static member function can be called using the class name( instead of
its objects) as follows

class-name :: function-name;
#include<iostream.h>
class employee
{ char name[30];
float age;
public:
void getdata(void);
void putdata(void);
};
void employee :: getdata(void)
{ cout<<“Enter Name”;
cin>>name;
cout<<“Enter age”;
cin>>age;
}

void employee ::putdata(void)


{
cout<<“Name: ”<<name<<“\n”;
cout<<Age: ”<<age<<“\n”;
}
void main( ) Output
{const int size = 2; Details of Manager 1
employee manager[size];
for(int i=0,i<size;i++) Enter name:XXX
{ Enter age:45
cout<<“Details of Details of Manager 2
Manager”<<i+1<<endl; Enter name:YYY
manager[i].getdata();
} Enter age:35
cout<<endl; Manager 1
for(int i=0,i<size;i++) Name: XXX
{ Age: 45
cout<<“Manager”<<i+1<<endl; Manager 2
manager[i].putdata();
Name: YYY
}
} Age: 35
//Passing Objects as Coordinates
#include<iostream.h>
class time
{int hours,minutes;
public:
void gettime(int h, int m)
{hours=h; minutes=m;}
void puttime(void)
{ cout<<hours<<“hours and”;
cout<<minutes<<“minutes “<<endl;
}
void sum(time,time);
};
void time :: sum(time t1,time t2)
{minutes=t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
void main() Output:
{ T1 = 4 hours 45 minutes
time T1,T2,T3; T2 = 3 hours 30 minutes
T1.gettime(4,45); T3 = 8 hours 15 minutes
T2.gettime(3,30);
T3.sum(T1,T2);
cout<<“T1 = “;
T1.puttime( );
cout<<“T2 = “;
T2.puttime( );.
cout<<“T3 = “;
T3.puttime( );
}
class X { private: X ob1;
int a; void main()
{
int sqr(int a)
Ob1.b=5;
{ return a*a; } Ob1.a=2;//invalid
public: Ob1.twice(10);
int b; Ob1.sqr(10);//invalid
int twice(int i) {return 2*i;} Ob1.tsq(10);
int tsq(int i) }//Rest all valid

{int p= sqr(i);
int q = twice(p);
return q;
}
};
Friendly Functions
A friend function possesses certain special characteristics:
It is not in the scope of the class to which it is declared as friend.
Since it is not in the scope of the class it cannot be called using the object of
that class.
It can be invoked like a normal function without the help of any object.
Unlike member functions, it cannot access the member names directly and has
to use an object name and dot membership operator with each member name .
It can be declared either in the public or private part of a class without affecting
its meaning, Usually, it has objects as arguments.

Need for Friend Function:


When a data is declared as private inside a class, then it is not accessible from
outside the class. A function that is not a member or an external class will not
be able to access the private data. A programmer may have a situation where
he or she would need to access private data from non-member functions and
external classes. For handling such cases, the concept of friend functions is a
useful tool.
class sample
{ int a;
int b;
public:
void setvalue( ){a=25;b=40;}
friend float mean (sample s);
};
float mean( sample s)
{ return(s.a+s.b)/2; }
void main()
{
sample X;
X.setvalue();
cout<<Mean Value=“<<mean(X)<<endl;
}
Output:
Mean value=32.5
class b; int common(a oa,b ob)
class a {
{ return (oa.i+ob.m);
private: }
int i; void main()
public: {
a() clrscr();
{ a oa;
i=100; b ob;
} int i;
friend int common(a,b); i=common(oa,ob);
}; cout<<"\nReturn from the friend
class b function:"<<I;
{ getch();
private: }
int m; class b is declared before the definition of the first
public: class - a starts. This is because since a class can
b() not be referred to until it has been declared. Class b
{ is being referred to in the declaration of the friend
m=150; function in class a. This declaration tells the
} compiler that class b is defined later.
friend int common(a,b);
};
The constructor function has the following characteristics:-
Constructors declared in private and protected section are available for only objects
created by member and friend functions ,however public constructors are available for
objects created in any functions.
They are invoked automatically when the objects are created.
They do not have return types not even void and therefore they cannot return values.
Member functions may be called from within a constructor.
They cannot be inherited, though a derived class can call the base class constructor.
Like any C++ function they can have default arguments.
It is not possible to gets its address.
They make “ implicit calls” to the operators new and delete when memory allocation is
required.
It may be called implicitly or explicitly.
#include<iostream>//
Demo of overloaded constructors and friend

class complex
{
float x, y;
public :
complex( ){ }
complex( float a ) {x=y=a;}
complex( float real , float imag )
{x = real; y = imag ; }
friend complex sum( complex , complex)
friend void show( complex);
};
complex sum( complex c1 , complex c2)
{complex c3;
c3.x=c1.x+c2.x;
c3.y=c1.y+c2.y;
return ( c3) ;
}
void show( complex c) Output:
{cout<<c. x<<“ + j”<<c. y<<endl;
} A=2.7+j3.5
B=1.6+j1.6
void main( )
{complex A(2.7,3.5);
C=4.3+j5.1
complex B(1.6);
complex C; P=2.5+j3.9
C=sum( A,B);
cout<<“A= “; show(A); Q=1.6+j2.5
cout<<“B= “; show(B); R=4.1+j6.4
cout<<“C= “; show(C);
complex P,Q,R;
P=complex(2.5,3.9);
Q=complex(1.6,2.5);
R=sum(P,Q);
cout<<endl;
cout<<“P = “; show(P);
cout<<“Q = “; show(Q);
cout<<“R = “; show(R);
}
Copy Constructor
It is used to declare and initialize an object from another object

A reference variable is used as an argument to the copy


constructor. We cannot pass the argument by value to the
copy constructor

When no copy constructor is defined compiler calls its own copy


constructor.

The process of initializing through a copy constructor is


called copy initialization.
# include<iostream.h> void main()
class code { code A(100); // Constructor called
{ code B(A); // Copy constructor called
int id; code C = A; // Copy constructor called
public: code D;
code( ) { } D=A;// Assignment operator called.
code( int a) cout<<“\n id of A : ” ; A.display( ) ;
{ id = a; cout<<“\n id of B : ” ; B.display( ) ;
} cout<<“\n id of C : ” ;C.display( ) ;
code( code & x) cout<<“\n id of D : ” ;D.display( ) ;
{// This is copy constructor }
id = x.id ; Output:-
} id of A : 100
void display (void) id of B : 100
{cout<<id; id of C : 100
} id of D : 100
}; A copy constructor will be called when a new
object is being instantiated. The assignment
operator is called for an existing object to
which a new value is being assigned.
Destructor:-
A destructor is also a member function whose name is the same as the class
name but is preceded by tilde(‘~’)
Destructor functions are invoked automatically when the objects
are destroyed.
You can have only one destructor for a class.
Member functions may be called from within a destructor.
“dtor” is typical abbreviation for destructors.
Only the function having access to a constructor and destructor of a class
can define objects of this class types otherwise the compiler reports an
error.
A destructor never takes any argument nor does it return any value.
It will be invoked implicitly by the compiler upon exit from the program or
block or function as the case may be) to clean up storage that is not
accessible.
It is a good practice to declare destructors in a program as it
releases memory for future use.
A destructor may not be static , it is not possible to take the address of destructor.
# include <iostream.h>
int count = 0;
class alpha
{
public :
alpha( )
{
count++ ;
cout<<“\n Number of object created “ <<count;
}
~alpha( )
{
cout<<“\n Number of object destroyed”<<count;
count--;
}
};
void main( ) Output:-
{ ENTER MAIN.
SNo .of object created 1
cout<<“\n \n Enter Main\n”;
SNo .of object created 2
alpha A1, A2 , A3 , A4 ; SNo .of object created 3
{ SNo .of object created 4
cout<<“ Enter BLOCK1”; Enter BLOCK1
alpha A5; SNo .of object created 5
} SNo .of object destroyed 5
Enter BLOCK2
{cout<<“\n Enter BLOCK2”;
SNo .of object created 5
alpha A6; SNo .of object destroyed 5
} Re-enter Main
cout<<“\n Re-enter Main”; SNo .of object destroyed 4
} SNo .of object destroyed 3
SNo .of object destroyed 2
SNo .of object destroyed 1
Operator Overloading
It allows to attach additional meaning to operators.
The general form of an operator function is:-
return_type class_name: : operator symbol(argument list)
{
// task defined
}
The function operator op( ) is always written in the public part of
the class. It may be either a member function or a friend function
Overloading Unary Minus
# include<iostream> void space : : display (void)
using namespace std; {cout<< x <<“ ”;
class space cout<< y << “ “;
{ int x,int y, int z; cout<< z <<“ “ ;
}
public:
void space : : operator-( )
void getdata(int a,int b,int c);
{x = - x;
void display(void); y= - y;
void operator – ( ); z= -z; }
}; int main()
void space ::getdata(int a,int b,int c) {space s;
{x=a; s.getdata(2,3,4);
y=b; -s;//overloading of unary -
z=c; s.display();
} }
Overloading Binary + operator
#include<iostream.h> complex complex ::operator +
class complex ( complex c)
{ float x, y; {complex temp;
public : temp . x= x + c. x;
complex( ) { } temp . y= y + c .y;
complex(float real , float imag) return (temp);
{ x = real ; }
y = imag ; void complex : : display (void)
} {
complex operator +(complex); cout<<x<< “ + j” <<y << “\n”;
void display(void); }
};
void main ( )
{
complex C1 , C2 ,C3;
C1 = complex(2.5 , 1.5);
C2 = complex(1.5 , 2.5);
C3=C1+C2;
cout<< “C1 = “; C1.display( ) ;
cout<< “C2 = “; C2.display( ) ;
cout<< “C3 = “; C3.display( ) ;
}

Output : -
C1 = 2.5 + j1.5
C2= 1.5 + j2.5
C3= 4.0 + j4.0
Rules for Overloading Operators:-
1. Only existing operators can be overloaded. New
operators cannot be created.
2. The overloaded operator must have atleast one
operand.
3. We cannot change the basic meaning of an
operator.That is to say that we cannot redefine the (+)
operator to substract one value from the other.
4. Overloaded operators follow the syntax rules of
original operators.They cannot be overridden.
5. There are some operators that cannot be overloaded.
6. We cannot use friend functions to overload certain
operators.
However ,member functions can be used to overload
them.
• Operators that cant be overloaded
Sizeof Size of operator
. Membership operator
.* Point-to-member operator
:: Scope resolution operator
?: Conditional operator

Where a friend cannot be used


= Assignment operator
() Function call operator
[] Subscripting operator
-> Class member access operator
7. Unary operators overloaded by means of a member function
take no explicit arguments and return no explicit values, but
those overloaded by means of a friend function ,take one
reference argument (the object of the relevant class).

8. Binary operators overloaded through a member function take


one explicit argument and those which are overloaded through
a friend function take two explicit arguments.

9. When using binary operators overloaded through a member


function the left hand operand must be an object of the relevant
class.

10.Binary arithmetic operators such as + , - , * , / must explicitly


return a value.They must not attempt to change their own
arguments.
void main( )
Object Pointers {
item abc;
class item
item *ptr = &abc;
{ int cd;
/* ptr is a pointer object of
float cost;
item class that is initialized
public:
with the address of another
void getdata( int x , float y)
object abc.*/
{ cd = x;
abc.getdata(26 , 150.50);
cost = y;
abc .show( );
}
Or
void show(void)
{cout<<“Code:”<<cd<<“\n”
ptr->getdata(26 , 150.50);
<<“Price:”<<cost<<“\n”; ptr-> show( );
} (*ptr).getdata(26 , 150.50);
}; (*ptr) .show( );
}
Output:-
Code:26
Cost: 150.50
Code:26
Cost: 150.50
Code:26
Cost: 150.50
Inheritance : Extending Classes
Reusability is yet another feature of OOP.
It is always nice if we could reuse something
that already exist rather than trying to create
the same all over again.
It will not only save time and money but also
reduce frustration and increase reliability
Once a class has been written and tested ,it can
be adopted by other programmers to suit their
requirements.
This is basically done by creating new
classes, reusing the properties of existing ones.
The mechanism of deriving a new class from an
old one is called inheritance (or derivation).
The old class is referred to as the base class and
the new one is called derived class or subclass.
Single Inheritance:-
A derived class with only one base class

B
Multiple Inheritance:-
A derived class with several base classes.

A B

C
Hierarchical Inheritance:-
The traits of one class may be inherited by more
than one class

B C D
Multilevel Inheritance:-
The mechanism of deriving a class from another
‘derived class’.
A

C
The general form of deriving a derived class is:-
class derived-class-name : visibility-mode base-class-name
{……….//
............// members of derived class
};
class ABC: private XYZ
{members of ABC
};
class ABC :public XYZ
{members of ABC
};
//By default base class is derived privately as shown below:-
class ABC : XYZ
{members of ABC
};
A public derivation informs the compiler that the object of the derived
class can access the public member functions of the base class and a
private derivation informs the compiler that the object of the derived
class can not access even the public base class member functions.

If base class member data are private, the derived class cannot inherit the
base class data . Further if member functions of a base class are public
,it gives public access to the member functions outside the class and not
only to the derived class. In case it is desired that the member functions
and data be inherited and accessed by the derived class alone, protected
access specifier is used.
Single Inheritance :PUBLIC public:-
# include<iostream.h> void mul(void);
class B void display ( );
{ int a; };
public: void B : :get_ab(void)
int b; {a = 5 ; b = 20 ;
void get_ab( ); }
void get_a(void); int B : : get_a ( )
void show_a(void); { return a ; }
}; void B : : show_A ( )
class D : public B {cout < <“A = “<<a<<“\n”;}
{ int c; void D : : mul( )
{ c = b * get_A( ) ; }
void D : : display( ) d . b = 20;
{cout<<“a = “<<get_a( )<<“\n”; d.mul( );
cout <<“b =“<<b<<“\n”; d.display( );
cout <<“c= “<<c<<“\n\n”; }
} Output:-
//---------------------------------- a=5
void main ( ) a=5
{D d; b = 10
d. get_ab( ); c = 50
d.mul( );
d.show_a( ); a=5
d.display( ); b = 20
c = 100
# include<iostream> void display(void);
class B };
void B : : get_ab(void)
{ int a;//private not inheritable
{cout<<“Enter a and b”;
public : cin>>a>>b;
int b; }
void get_ab( ); int B : : get_a( )
int get_a(void); { return a ; }
void show_a(void); void B : : show_a( )
{cout<<“a = “<<a<<“\n”;
};
}
class D : private B void D : : mul( )
{ int c; {get_ab( );
public: c = b* get_a( );
void mul(void); }// ‘a’ cannot be used directly
void D : : display ( ) d . b = 20; // wont work
{ d . mul( );
show_a( ); d.display( );
cout<<“b = “<<b<<“\n”; }
cout<<“c =“<<c<<“\n\n”; Output:-
} Enter values of a and b:
5 10
void main ( ) a=5
b = 10
{
c = 50
D d; Enter values of a and b:
// d. get_ab( ); WON’T WORK 12 20
d.mul( ); a = 12
d.show_a( ); WON’T WORK b = 20
d.display( ); c = 240
Multilevel Inheritance class test : public student
class student {
{ protected:
protected: float sub1;
int roll_number; float sub2;
public: public:
void get_number(int); void get_marks(float, float );
void put_number(void); void put_marks(void);
}; };
void student::get_number(int a) void test : :get_marks(float x,float
y)
{ roll_number = a ;
{ sub1 = x ; sub2= y ; }
}
void test : : put_marks ( )
void student : : put_number( )
{cout<<“Marks in
{ cout<<“Roll Number : SUB1=“<<sub1<<“\n”;
“<<roll_number<<“\n” ;
cout<<“Marks in
} SUB2=“<<sub2<<“\n”;
}
class result : public test void main( )
{float total;//private by default {result student1;
public: student1.get_number(111);
void display(void); student1.get_marks(75.0,59.5);
}; student1.display( );
void result : : display(void) }
{ Output:-
total = sub1 + sub2; Roll Number: 111
put_number( ); Marks in SUB1 = 75
put_marks( ); Marks in SUB2 = 59.5
cout<<“Total = Total = 134.5
“<<total<<“\n”;
}
Multiple Inheritance:- class P : public M , pubic N
class M {
{protected: public:
int m; void display(void);
public: };
void get_m(int); void M : : get_m(int x)
}; { m=x;}
class N
{ void N : : get_n(int y)
protected: { n= y;}
int n; void P : : display(void)
public: {
void get_n(int); cout<<“m = “<<m<<“\n”;
}; cout<<“n = “<<n<<“\n”;
cout<<“m*n =“<<m*n<<“\n”;
}
void main( )
{ P p;
p.get_m(10);
p.get_n(20);
p.display( );
}
Output:-
m = 10
n = 20
m*n = 200
Resolving Ambiguity in void main( )
Single Inheritance:- {
class A B b;
{ //invokes display( ) in B
public:
b.display( );
void display ( )
{ cout << “A \n”; } //invokes display( ) in A
}; b . A : : display( );
class B : public A //invokes display( ) in B
{ b. B : : display( ).
public: }
void display( )
Output:-
{ cout << “B \n” ; }
}; B
A
B
// HYBRID INHERITANCE public :
class student void get_marks(float x,
{ protected: float y)
int roll_number; {part1 = x ; part2 = y; }
public: void put_marks(void)
void get_number(int a ) {cout<<“Marks obtained:”<<“\n”;
{ roll_number = a ; } cout<<“Part1 = “<<part1<<“\n”;
void put_number(void) cout<<“Part2= “ <<part2<<“\n”;
{cout<<“Roll }
No:”<<roll_number<<“\n”; } };
};
class test : public student class sports
{ { protected:
protected: float score ;
float part1, part2;
public : void result : : display(void)
void get_score(float s) {total = part1+part2+score;
{score = s ; } put_number( ) ;
void put_score(void) put_marks( );
{cout<<“Sports wt put_score( );
:”<<score<<“\n”; cout<<“Total
} Score:”<<total<<“\n”;
}; }
class result : public test, public void main( )
sports { { result student_1;
float total ; student_1.get_number(1);
public: student_1.get_marks(27.5,33.0);
void display(void); student_1.get_score(6.0);
}; student_1.display( ) ;
}
Output:-
Roll No: 1
Marks Obtained :
Part1:27.5
Part2:33
Sports wt : 6

Total Score:66.5
Constructors in derived class:-
# include<iostream .h> class beta
class alpha { float y ;
{
public:
int x;
public:
beta( float j )
alpha( int i) {
{ y=j;
x=i; cout<<“beta initialized”;
cout<<“alpha initialized \n”; }
} void show_y(void)
void show_x(void) { cout<<“y = “<<y<<“\n”; }
{ cout<<“x = “<<x<<“\n”; }
};
};
class gamma : public beta, void show_mn(void)
public alpha {
{ int m ,n ; cout<<“m = “<<m<<“\n”;
public: <<“ n = “<<n<<“\n”;
gamma( int a , float b , int c }
int d ) : alpha (a) , beta(b) };
{ void main( )
m = c; {
n = d; gamma g(5 ,10.75,20,30);
cout<<“gamma initialized cout<<“\n”;
\n “; g.show_x( );
} g.show_y( );
g.show_mn( );
}
Output:- constructor(arglist) :
beta initialized initialization section
alpha initialized {
gamma initialized assignment-section
}
x=5
y = 10.75
m = 20
n = 30
/* C++ supports another
method of initializing class
objects. This method uses
what is called initialization
list in the constructor function.
INITIALIZATION LIST IN class beta
CONSTRUCTORS { float p , q ;
# include<iostream.h> public :
class alpha beta (float a, float b) :
{ p(a) , q(b+p)
int x;
{
public:
cout<<“\n beta constructed”;
alpha( int i)
}
{ x=i;
void show_beta(void)
cout<<“alpha initialized \n”;
{
}
cout<<“ p = “<<p<<“\n”;
void show_x(void)
cout<<“ q = “<<q<<“\n”;
{ cout<<“x = “<<x<<“\n”; }
}
};
};
class gamma :public beta , void main( )
public alpha {
{int u , v ; gamma g(2, 4 , 2.5);
public : cout<<“\n\n Display
gamma(int a , int b, float c) : member values “;
alpha(a*2),beta(c , c) ,u(a) g.show_alpha( );
{v = b; g.show_beta( );
cout<<gamma constructed”; g.show_gamma( );
} }
void show_gamma(void)
{cout<<“u = “<<u<<“\n”;
cout<< v = “ <<v<<“\n”;
}
};
Output:- /* The argument list in the
beta constructed derived constructor gamma
alpha constructed contains only three
gamma constructed parameters a, b and c
Display member values which are used to initialize
x =4 five data members
p = 2.5 contained in all the three
q =5 classes.*/
u =2
v =4
Polymorphism
It simply means ‘one name, multiple forms’.

The overloaded member functions are ‘selected’ for


invoking by matching arguments, both type and
number. This information is known to the compiler
at the compile time and therefore compiler is able to
select the appropriate function for a particular call
at the compile time itself.

This is called early binding or static binding


or static linking or compile time polymorphism.
Polymorphism

Compile Time Polymorphism Run Time Polymorphism

Function Overloading Operator Overloading Virtual Functions


FUNCTION OVERLOADING:- double volume(double r,
# include<iostream.h> int h) // cylinder
int volume ( int );
{
double volume (double , int);
long volume(long , int , int);
return (3.14 *r*r*h);
void main ( ) }
{ long volume(long l , int b
cout<<volume(10)<<“\n”; , int h) // cuboid
cout<<volume(2.5 , 8)<<“\n”; {
cout<<volume(100L,75,15)<<“\n”;
return (l*b*h);
}
int volume( int s) // cube
}
{ Output:-
return (s*s*s); 1000
} 157.26
112500
Demo of Virtual Functions:- int main( ) {
Run Time Polymorphism Base B;
class Base Derived D;
{public: Base *bptr;
void display( ) {cout<<“\nDisplay Base”;} bptr=&B;
virtual void show( ) //Below two lines calls Base Version of function

{cout<<“\nShow Base”;} bptr->display();


}; bptr->show();
class Derived :public Base bptr=&D;
//Calls Base display version
{public:
bptr->display();
void display( ) //Calls Derived Show version

{cout<<“\nDisplay derived”;} bptr->show();


void show( ) return 0;
{cout<<“\nShow Derived”;} }
};
Runtime polymorphism:- class book : public media
# include<iostream .h> { int pages;
# include<cstring> public:
class media book (char *s, float a , int p) :
{protected: media(s ,a )
char title[50]; { pages = p; }
float price; void display( );
public : };
media( char *s ,float a)
{strcpy (tilte , s ) ; class tape : public media
price = a ; { float time ;
} public :
virtual void display( ) { } tape( char * s , float a , float t)
// empty virtual function : media ( s, a)
/* Can also be written as { time = t ; }
virtual void display( ) = 0 known void display( );
as pure virtual function.*/ };
};
void book : : display( ) void main( )
{ {
cout<<“\n Title :”<<title; char *title = new char[30];
cout<<“\n Pages:”<<pages; float price , time;
cout<<“\n Price:”<<price; int pages ;
} cout<<“\nENTER BOOK DETAILS”;
void tape : : display( ) cout<<“Title :” ; cin>>title ;
{ cout<<“Price :”; cin>>price;
cout<<“\n Title :”<<title; cout<<“Pages : “ ; cin>>pages;
cout<<“\n Play Time:”<<time; book book1(title , price , pages) ;
cout<<“\n Price:”<<price; cout<<“\nENTER TAPE DETAILS”;
} cout<<“Title :” ; cin>>title ;
cout<<“Price :”; cin>>price;
cout<<“Play Time : “ ; cin>>time;
tape tape1(title , price , time) ;
media *list[2]; ENTER TAPE DETAILS
list[0] = &book1; Title : Computing Concepts
list[1] = &tape1; Price : 90
cout<<“\n MEDIA DETAILS”; Play Time : 55
cout<<“\n………BOOK…….”;
list[0] -> display( ) ; MEDIA DETAILS
// display book details …………BOOK………….
cout<<“\n………TAPE…….”; Title : Programming in C++
list[1] -> display( ) ; Pages : 400
// display tape details Price : 88
}
Output:- …………TAPE……………
ENTER BOOK DETAILS Title : Computing Concepts
Title : Programming in C++ Play Time : 55
Price : 88 Price : 90
Pages : 400
The concept of the virtual function solves the following problem:
In OOP when a derived class inherits a base class, an object of
the derived class may be referred to (or cast) as either being the
base class type or the derived class type. If there are base class
methods overridden by the derived class, the method call
behavior is ambiguous.

Rules for Virtual Functions


1. The virtual functions must be members of some class.
2. They cannot be static members.
3. They are accessed by using object pointers.
4. A virtual function can be friend of another class.
5. A virtual function in a base class must be defined even though it may
not be used.
6. The prototypes of the base class version of a virtual function
and all the derived class versions must be identical. If two functions
with the same name have different prototypes ,C++ considers them
as overloaded functions and the virtual function mechanism is
ignored.
1. We cannot have virtual constructors ,but we can have virtual
destructors.
2. While a base pointer can point to any kind of derived object ,the
reverse is not true.
9. If a virtual function is defined in the base class , it need not be
necessarily redefined in the derived class. In such cases,calls will
invoke the base function.

Virtual functions employ late binding by allocating memory space


during execution time and not during compilation time.
Pointer Expressions Output :-
void main( ) Address of i = 6485
{int i =3; Address of i = 6485
int *j; Address of j = 3276
j = &i; Value of j = 6485
cout<<“\nAddress of i= ”<<&i; Value of i = 3
cout<<“\nAddress of i=”<<j; Value of i = 3
cout<<“\nAddress of j=”<<&j; Value of i = 3
cout<<“\nValue of j = ”<<j; i Location name
cout<<“\nValue of i = ”<<i; 3 Value at location
cout<<“\nValue of i = ”<<*(&i)); 6485 Address
cout<<“\nValue of i = ”<<*j;
}
j

6485

3276
int i = 3;
int *j;
int **k;
j = &i;
k = &j;

i j k

3 6485 3276

6485 3276 7234


void main( ) Output :-
{ int i = 3; Address of i = 6485
int *j; Address of i = 6485
int **k; Address of i = 6485
j = &i; Address of j = 3276
k = &j; Address of j = 3276
cout<<“\nAddress of i =“<<&i ; Address of k = 7234
cout<<“\nAddress of i =“<<j; Value of j = 6485
cout<<“\nAddress of i =“<<*k; Value of k =3276
cout<<“\nAddress of j =“<<&j; Value of i = 3
cout<<“\nAddress of k =“<<&k; Value of i = 3
cout<<“\n\nValue of j =“<<j; Value of i = 3
cout<<“\nValue of k =“<<k; Value of i = 3
cout<<“\nValue of i =“<<i; 4
cout<<“\nValue of i =“<<*(&i); ++*j increments the value
cout<<“\nValue of i =“<<*j; pointed by j.
cout<<“\nValue of i =“<<**k;
cout<<++*j;
#include <iostream>
using namespace std;
int main(){
int a[6]={8,5,6,9,10,11}; 8 5 6 9 10 11

int *p,*q; 101 103 105 107 109 111


p=&a[0]; Possible Output:-
q=&a[5];
101
p=p+2;
cout<<p<<endl; 111
q=q-1; 105
cout<<q<<endl; 109
cout<<p-q<<endl;
4
}
Why does an array always start
with index 0 in C++.
Array name is a constant
pointer pointing to the base
address ofvthe memory
allocated.When we use arr[i]
the compiler manipulates it as
*(arr+i).Since arr is the
address of the first element the
value of i must be 0 for
accessing it. Hence all arrays
begin with index of 0.
#include<iostream> Output :-
using namespace std; 8
int main() 0x7fff46df2390
{ int a[ ] ={7,6,9,10};
0x7fff46df2394
int *ptr=a;
cout<<++*ptr<<endl; 6
cout<<ptr<<endl; 9
cout<<++ptr<<endl;
10
cout<<*ptr++<<endl;
All the unary operations must be read from
cout<<*ptr; right to left.
++*ptr –>take data and increment data
cout<<*++ptr;
*++ptr->move ptr to next and read data
return 0; *ptr++ ->read data and move ptr to next
}
Allowable pointer arithmetic operations:-
1)Pointer Increment p++
2)Pointer Decrement p--
3)Constant Addition p=p+k
4)Constant Subtraction p=p-k
5)Subtraction of two pointers l=q-p
Not allowed pointer operations between two pointers
or pointer and constant they are meaningless:-
1)p+q
2)p*q
3)2*p
4)
int main( ) { cout<<cptr<<endl;
int a=7;
cout<<fptr<<endl;
char ch='A’;
float f=5.68; fptr=fptr+1;
int *iptr=&a; cout<<fptr<<endl;
char *cptr=&ch; }
float *fptr=&f; /* int pointer gets incremented
cout<<sizeof(iptr)<<endl; by 2 bytes,char pointer gets
cout<<sizeof(cptr)<<endl; incemented by 1 byte ,float
pointer gets incremented by 4
cout<<sizeof(fptr)<<endl;
bytes depending on size of data
cout<<iptr<<endl; type*/
iptr=iptr+1;
cout<<iptr<<endl;
cout<<cptr<<endl;
#include <iostream>
using namespace std;

int main(){
int a[][3]={{1,2,3},
{ 2,4,8},{3,5,6}};
cout<<a<<endl;
cout<<*a<<endl;
Output:-
cout<<*a+1;
101
cout<<a+1<<endl; 101
cout<<*(a+1)<<endl; 103
cout<<a[1]; 107
cout<<a[1]+2; 107
107
cout<<*(a+2)<<endl;
cout<<**a<<endl; 111
113
cout<<*(*(a+1)+2);
1
}
8
#include<stdio.h>
main()
{int x=0,y=0;
int matrix[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(x=2;x>=0;x--)
for(y=2;y>=0;y--)
cout<<*(*(matrix+y)+x));
}
Array name is nothing but the address of the starting
element of the array.For n dimension arrays use of
*(dereferencing operator) upto n-1
times denote pointer itself.

int ****arr;
then *arr,*arr,***arr all denote pointers .All of these will
actually point to the starting element.
int main() (a)#include<stdio.h>
{int a[5]={5,4,3,2,1}; int main()
cout<<*a+1-*a+3;
{int a,b;
}
charch,str[30]=“UNIVERSITY”;
Output:- 4
for(a=0,b=strlen(str);a<b;a++)
#include<iostream>
{ch=str[a];
using namespace std;
str[a]=str[b-a];
int main()
{char str1[]={‘J’,’i’,’t’,’e’,’n’,’d’,’e’,’r’};
str[b-a]=ch;
char str2[]=“Kumar”; }
puts(str1); cout<<str;
puts(str2); }
} Output:-
Output:- Jitender
NULL STRING
Kumar
(b#include <iostream> (c#include <iostream>
using namespace std; using namespace std;
int main() int main()
{int a,b; {int a,b;
char ch,str[30]=“UNIVERSITY”; char ch,str[30]=“UNIVERSITY”;
for(a=0,b=strlen(str)-1;a<b;a++) for(a=0,b=strlen(str)-1;a<=b;a++)
{ch=str[a]; {ch=str[a];
str[a]=str[b-a]; str[a]=str[b-a];
str[b-a]=ch; str[b-a]=ch;
} }
puts(str); puts(str);
} }
Output:- Output:-
YNIVERSITU UNIVERSITY
(d) #include <iostream> #include<iostream>
#include<cstring> using namespace std;
using namespace std; int main()
int main() {chat str[10]=“Krishna”,*ptr;
{int a,b; ptr=str;
char ch,str[30]=“UNIVERSITY”; while(*ptr!=‘\0’)
for(a=0,b=strlen(str)-1;a<b;a++,b--) ++*ptr++;
{ch=str[a]; cout<<str<<ptr;
str[a]=str[b-a]; }
str[b-a]=ch; Output:-Lsjtiob
}
puts(str);
}
Output:-
YERVIISNTU
void main ( ) In the above program only the address of i would be
{ printed and the value of i would not be printed as when the
control come back from fun( ) i dies. So even if we have
int *p;
address of i in p we cant access its value since i is dead.
int * fun ( );
p = fun( ); # include<stdio.h>
cout<<p; main( )
cout<<*p; {
int a , b = 5;
}
a=b + NULL;
cout<<a;
int *fun( ) }
{ Output
int i =20; 5
because NULL has been defined in stdio.h as follows
return (&i);
#define NULL 0.
}
int * number; # include<stdio.h>
char * character; void main( )
float * greatnumber;
{
These are three declarations of cout<<sizeof(NULL)<<sizeof(“ “);
pointers. Each one is intended to
point to a different data type, but }
in fact all of them are pointers and Output:-
all of them will occupy the same
amount of space in memory (the 1 1
size in memory of a pointer
depends on the platform where
the code is going to run). Explanation
Nevertheless, the data to which While finding out size of NULL , we are
they point to do not occupy the finding out size of 0 which is 2 bytes
same amount of space nor are of Even though the string “ “ is empty it still
the same type: the first one points
to an int, the second one to a char contains the character , ’\0’ .Hence its
and the last one to a float. size turns out to be 1 byte.
Therefore, although these three
example variables are all of them
pointers which occupy the same
size in memory, they are said to
have different types: int*, char*
and float* respectively, depending
on the type they point to.
#include<iostream.h> Output:-
#include<conio .h> i=-5
void junk(int , int *); j= 4
void main( ) i j
{clrscr( );
Binary Eq of - 5 Binary Eq of -2
int i = -5 ,j = -2;
junk ( i ,&j ); 101 103
cout<<i<<j;
getch( );
} i *j
void junk (int i , int *j) Binary Eq of 25 103
{
i = i * i; 501 503
j = *j * *j ;
}
Suppose we have an array:-
int num[ ] = {23 , 34 , 12 , 44, 56 , 17 };
The following figure shows how they are located in memory:-

Values: 23 34 12 44 56 17

Address: 4001 4003 4005 4007 4009 4011

On mentioning the name of the array we get the base address


If we write *num we get 23
If we write *(num + 0) then also we get 23.

Thus num[ i ] , * ( num + i) , *( i + num ) and i [num] all means the


same
void main( ) Output:-
{ Address = 4001 Element = 24
Address = 4003 Element = 34
int num [ ] = {24,34,12,44, 56,17}; Address = 4005 Element = 12
int i = 0; Address = 4007 Element = 44
while (i<=5) Address = 4009 Element = 56
{cout << “\nAddress = “ Address = 4011 Element = 17
<< & num [ i ] ;
cout <<“Element = “<< num[ i ] ;
i++;
}
Another method to access Output:-
array elements using Address = 4001 Element = 24
pointers :- Address = 4003 Element = 34
void main( ) Address = 4005 Element = 12
{ Address = 4007 Element = 44
int num [ ] = {24,34,12,44, Address = 4009 Element = 56
56,17}; Address = 4011 Element = 17
int i = 0 , * j ;
j = &num[0];
while (i<=5)
{cout << “\nAddress = “
<< & num [ i ] ;
cout <<“Element = “<< * j ;
i++ ;
j+ + // increments pointer
}
}
void main( ) Output:-
{ Address = 4001 Element = 24
int num [ ] = {24,34,12,44, 24 24 24
56,17}; Address = 4003 Element = 34
int i = 0 ;
34 34 34 34
Address = 4005 Element = 12
while (i<=5)
{ 12 12 1 2
cout << “\nAddress = “ Address = 4007 Element = 44
<< & num [ i ] ; 44 44 44
cout <<“Element = “<<num[ i ] ; Address = 4009 Element = 56
cout << * (num + i ) ; 56 56 56
cout<< * (i + num ); Address = 4011 Element = 17
cout<< i [ num ] ; 17 17 17
i++;
}
}
int student [ 4 ][2] = {
{ 1234 , 56 },
{ 1213 , 33 },
{ 1434, 80 },
{ 1312, 78 },
}
stud [ i ] or * (stud + i) would give base address of i th
1-D array.
1234 56 1212 33 1434 80 1312 78
1 4003 4005 4007 4009 4011 4013 4015
In memory elements are stored in one continuous
chain .1234 is stored in student[0][0] and 56 is
stored in student[0][1].
# include<iostream.h> Output:-
#include<conio.h> 1 56
void main ( )
2 33
{clrscr( );
int student [ 4 ][2] = {
3 80
{ 1234 , 56 }, 4 78
{ 1213 , 33 }, 1203 75
{ 1434, 80 },
{ 1312, 78 },
};
int i , j ;
for( i = 0 ; i< = 4; i ++)
{cout<<“\n”;
for( j= 0 ; j < = 1 ; j++)
cout<< *(*(stud + i ) + j) );
}
}
#include<stdio.h> #include<stdio.h>
int main() int main()
{int a=20,b=5,c; {int a=20,b=5,c;
int *p1,*p2; int *p1,*p2;
p1=&a; p1=&a;
p2=&b; p2=&b;
c=*p1/*p2; c=*p1/ *p2;
cout<<c cout<<c
} }
/*The first program does not The program is correct
because a comment gets becaude of space between /
started because of /* and *.
symbol.But the comment does
not get ended.

You might also like