C++s Slides DEC 20 19 Uverted
C++s Slides DEC 20 19 Uverted
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.
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.
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 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
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;
}
{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.
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
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
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’.
6485
3276
int i = 3;
int *j;
int **k;
j = &i;
k = &j;
i j k
3 6485 3276
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