You are on page 1of 61

Variable, Operator and Expression

[SET – 1]
1Write a program to print HELLO WORLD on screen. solution

#include<iostream.h>
#include<conio.h>

int main()
{
cout<<"Hello world";
getch();
return 0;
}

2Write a program to display the following output using a single cout statement.

Subject Marks
Mathematics 90
Computer 77
Chemistry 69 solution

#include<iostream.h>
#include<conio.h>

int main()
{
cout<<"subject " <<"\tmarks"<<"\nmathematic\t"
<<90<<"\ncomputer\t"<<77<<"\nchemistry\t"<<69;

getch();
return 0;
}

3Write a program which accept two numbers and print their sum. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a,b,c;
cout<< "\nEnter first number : ";
cin>>a;
cout<<"\nEnter second number : ";
cin>>b;
c=a+b;
cout<<"\nThe Sum is : "<<c;

getch();
return 0;
}

4Write a program which accept temperature in Farenheit and print it in centigrade. solution

#include<iostream.h>
#include<conio.h>

int main()
{
float F,C;
cout<< "\nEnter temperature in Farenheit : ";
cin>>F;
C=5*(F-32)/9;
cout<<"Temperature in celcius is : "<<C;

getch();
return 0;
}

5Write a program which accept principle, rate and time from user and print the simple interest.
solution

#include<iostream.h>
#include<conio.h>

int main()
{
int p,r,t,i;
cout<<"Enter Principle : ";
cin>>p;
cout<<"Enter Rate : ";
cin>>r;
cout<<"Enter Time : ";
cin>>t;
i=(p*r*t)/100;
cout<<"Simple interest is : "<<i;

getch();
return 0;
}
6Write a program which accepts a character and display its ASCII value. solution

#include<iostream.h>
#include<conio.h>

int main()
{
char ch;
cout<< "\nEnter any character : ";
cin>>ch;
cout<<"ASCII equivalent is : "<<(int)ch;

getch();
return 0;
}

7Write a program to swap the values of two variables. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a,b,temp;
cout<<"\nEnter two numbers : ";
cin>>a>>b;
temp=a;
a=b;
b=temp;
cout<<"\nAfter swapping numbers are : ";
cout<<a<<" "<<b;

getch();
return 0;
}

8Write a program to calculate area of circle. solution

#include<iostream.h>
#include<conio.h>

int main()
{
float r,area;
cout<< "\nEnter radius of circle : ";

cin>>r;
area = 3.14*r*r;
cout<<"Area of circle : "<<area;

getch();
return 0;
}

9Write a program to check whether the given number is positive or negative (using ? : ternary
operator ) solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a;
cout<<"Enter any non-zero Number : ";
cin>>a;
(a>0)?cout<<"Number is positive":cout<<"Number is negative";

getch();
return 0;
}
Variable, Operator and Expression
[SET – 2]
1 Write a program to swap value of two variables without using third variable.
solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a,b;
cout<<"\nEnter two numbers : ";
cin>>a>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"\nAfter swapping numbers are : ";
cout<<a<<" "<<b;

getch();
return 0;
}

2 Write a program which input three numbers and display the largest number using
ternary operator. solution

#include <iostream.h>
#include <conio.h>

int main()
{
int a,b,c,greatest;
cout<<"Enter three numbers : ";
cin>>a>>b>>c;
greatest=(a>b&&a>c)?a:(b>c)?b : c;
cout<<"Greatest number is "<<greatest;

getch();
return 0;
}

3 Write a program which accepts amount as integer and display total number of Notes
of Rs. 500, 100, 50, 20, 10, 5 and 1.
For example, when user e
#include<iostream.h>
#include<conio.h>
int main()
{
int amt,R500,R100,R50,R20,R10,R5,R1;
cout<<"Enter amount : ";
cin>>amt;
R500=amt/500;
amt=amt%500;
R100=amt/100;
amt=amt%100;
R50=amt/50;
amt=amt%50;
R20=amt/20;
amt=amt%20;
R10=amt/10;
amt=amt%10;
R5=amt/5;
amt=amt%5;
R1=amt;
cout<<"Rs.500 : "<<R500<<"\nRs.100 : "<<R100<<"\nRs. 50 : "<<R50<<
"\nRs. 20 : "<<R20<<"\nRs. 10 : "<<R10<<"\nRs. 5 :
"<<R5<<"\nRe. 1 : "<<R1;

getch();
return 0;
}
4 Write a program which accepts a character and display its next character. solution

#include<iostream.h>
#include<conio.h>

int main()
{
char ch;
cout<< "\nEnter any character : ";
cin>>ch;
ch++;
cout<<"Next character is : "<<ch;

getch();
return 0;
}

5 Write a program which accepts days as integer and display total number of years, months and
days in it.
for example : If user input as 856 days the output should be 2 years 4 months 6 days. solution

#include<iostream.h>
#include<conio.h>
int main()
{
int days,y,m,d;
cout<<"Enter no. of days : ";
cin>>days;
y=days/365;
days=days%365;
m=days/30;
d=days%30;
cout<<"Years : "<<y<<"\nMonths : "<<m<<"\nDays : "<<d;

getch();
return 0;
}

6 What is the output of following program?

int result = 4 + 5 * 6 + 2;
cout<<result;

int a = 5 + 7 % 2;
cout<<a;
7 What is the output of following program?

int x = 10,y; int x = 10,y; int x = 10;


y = x++; y = x++; x++;
cout<<y; cout<<x; cout<<x;
int x = 10,y; int x = 10; int x = 10;
y = ++x; cout<<++x; cout<<x++;
cout<<y;
8 What is the output of following program?

int x = 10; int x = 10; int x = 10;


cout<<x<<x++; cout<<++x<<x++<<x; cout<<x++<<x<<++x;
int x = 10,y; int x = 10,y; int x = 10,y;
y = x + x++; y = ++x + x++ + x; y = x++ + x + ++x;
cout<<y; cout<<y; cout<<y;

9 What is the output of following program?


cout << setw(10)<< 77;
10What is the output of following program?
float net=5689.2356;
cout <<"Employee's net pay is: ";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << net << endl;
Variable, Operator and Expression
[SET – 3]
1 Write a program that takes length as input in feet and inches. The program should
then convert the lengths in centimeters and display it on screen. Assume that the
given lengths in feet and inches are integers.

Based on the problem, you need to design an algorithm as follows:


1. Get the length in feet and inches.
2. Convert the length into total inches.
3. Convert total inches into centimeters.
4. Output centimeters.

To calculate the equivalent length in centimeters, you need to multiply the total
inches by 2.54. Instead of using the value 2.54 directly in the program, you will
declare this value as a named constant. Similarly, to find the total inches, you need
to multiply the feet by 12 and add the inches. Instead of using 12 directly in the
program, you will also declare this value as a named constant. Using a named
constant makes it easier to modify the program later.

To write the complete length conversion program, follow these steps:


1. Begin the program with comments for documentation.
2. Include header files, if any are used in the program.
3. Declare named constants, if any.
4. Write the definition of the function main. solution

Write a program that takes length as input in feet and inches. The program should then convert
the lengths in centimeters and display it on screen. Assume that the given lengths in feet and
inches are integers.

/********************************************************
Purpose :This program converts measurements
in feet and inches into centimeters.

@Author :cppforschool.com
********************************************************/

#include <iostream.h> //Header file

const double CENTIMETERS_PER_INCH = 2.54; //Named constants


const int INCHES_PER_FOOT = 12; //Named constants

int main ()
{
int feet, inches;
int totalInches;
double centimeter;
cout << "Enter two integers, one for feet and one for inches: ";
cin >> feet >> inches;
cout << endl;
cout << "The numbers you entered are " << feet << " for feet and " <<
inches << " for inches. " << endl;
totalInches = INCHES_PER_FOOT * feet + inches;
cout << "The total number of inches = " << totalInches << endl;
centimeter = CENTIMETERS_PER_INCH * totalInches;
cout << "The number of centimeters = " << centimeter << endl;
return 0;
}

10Write a program to check whether the given number is even or odd (using ? : ternary operator
) solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a;
cout<<"Enter the Number : ";
cin>>a;
(a%2==0)?cout<<"Number is even":cout<<"Number is odd";

getch();
return 0;
}
flow of control
[SET – 1]
1 Any integer is input by the user. Write a program to find out whether it is an odd
number or even number. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a;
cout<<"Enter any number : ";
cin>>a;

if(a%2==0)
cout<<"The number is even";
else
cout<<"The number is odd";

getch();
return 0;
}

SAMPLE RUN # 1

Enter any number : 68


The number is even

SAMPLE RUN # 2

Enter any number : 43


The number is odd

2 Find the absolute value of a number entered by the user. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int a;
cout<<"Enter any number:";
cin>>a;

if(a>0)
cout<<"The absolute value of number is:"<<a;
else
cout<<"The absolute value of number is:"<<-(a);

getch();
return 0;
}

SAMPLE RUN # 1

Enter any number:-57


The absolute value of number is:57

SAMPLE RUN # 2

Enter any number:50


The absolute value of number is:50

3 Write a program to calculate the total expenses. Quantity and price per item are
input by the user and discount of 10% is offered if the expense is more than 5000.
solution

#include<iostream.h>
#include<conio.h>

int main()
{
int totalexp, qty, price, discount;

cout<<"Enter quantity:";
cin>>qty;
cout<<"Enter price:";
cin>>price;

totalexp=qty*price;

if(totalexp>5000)
{
discount=(totalexp*0.1);
totalexp=totalexp-discount;
}

cout<<"Total Expense is Rs. "<<totalexp;

getch();
return 0;
}

SAMPLE RUN # 1

Enter quantity:14
Enter price:300
Total Expense is Rs.4200

SAMPLE RUN # 2

Enter quantity:50
Enter price:300
Total Expense is Rs. 13500

4 Write a program to determine whether the seller has made profit or incurred loss.
Also determine how much profit he made or loss he incurred. Cost price and selling
price of an item is input by the user. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int cp,sp,result;

cout<<"Enter cost price of item : ";


cin>>cp;
cout<<"Enter selling price of item : ";
cin>>sp;

result=sp-cp;

if(result>0)
cout<<"Profit : "<<result;
else
if(result<0)
cout<<"Loss : "<<-(result);
else
cout<<"No profit no loss";

getch();
return 0;
}

SAMPLE RUN # 1

Enter cost price of item : 800


Enter selling price of item : 950
Profit : 150

SAMPLE RUN # 2

Enter cost price of item : 800


Enter selling price of item : 600
Loss : 200

SAMPLE RUN # 3

Enter cost price of item : 800


Enter selling price of item : 800
No profit no loss

5 If the ages of Ram, Sulabh and Ajay are input by the user, write a program to
determine the youngest of the three. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int ram_age,sulabh_age,ajay_age;
cout<<"Enter Ram age:";
cin>>ram_age;
cout<<"Enter Sulabh age:";
cin>>sulabh_age;
cout<<"Enter Ajay age:";
cin>>ajay_age;

if (ram_age<sulabh_age && ram_age<ajay_age)


cout<<"Ram is youngest";
else if(sulabh_age<ram_age && sulabh_age<ajay_age)
cout<<"Sulabh is youngest";
else
cout<<"Ajay is youngest";

getch();
return 0;
}

SAMPLE RUN # 1

Enter Ram age:45


Enter Sulabh age:34
Enter Ajay age:22
Ajay is youngest

SAMPLE RUN # 2

Enter Ram age:45


Enter Sulabh age:34
Enter Ajay age:39
Sulabh is youngest
SAMPLE RUN # 3

Enter Ram age:25


Enter Sulabh age:34
Enter Ajay age:29
Ram is youngest

6 Write a program to check whether a triangle is valid or not, when the three angles of
the triangle are entered by the user. A triangle is valid if the sum of all the three
angles is equal to 180 degrees. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int angle1,angle2,angle3;
cout<<"Enter the three angles of triangle:";
cin>>angle1>>angle2>>angle3;

if (angle1+angle2+angle3==180)
cout<<"Triangle is valid";
else
cout<<"Triangle is not valid";

getch();
return 0;
}

SAMPLE RUN # 1

Enter the three angles of triangle:60 50 50


Triangle is not valid

SAMPLE RUN # 2

Enter the three angles of triangle:60 90 30


Triangle is valid

7 Any year is input by the user. Write a program to determine whether the year is a
leap year or not. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int year;
cout<<"Enter the year : ";
cin>>year;

if( (year%400==0 || year%100!=0) &&(year%4==0))


cout<<"It is a leap year";
else
cout<<"It is not a leap year";

getch();
return 0;
}

SAMPLE RUN # 1

Enter the year : 1996


It is a leap year

SAMPLE RUN # 2

Enter the year : 2011


It is not a leap year

SAMPLE RUN # 3

Enter the year : 1900


It is not a leap year

SAMPLE RUN # 4

Enter the year : 2000


It is a leap year

8 In a company an employee is paid as under:


If his basic salary is less than Rs. 1500, then HRA = 10% of basic salary and DA =
90% of basic salary.
If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA =
98% of basic salary.
If the employee's salary is input by the user write a program to find his gross salary.
solution

#include<iostream.h>
#include<conio.h>

int main()
{
float basic_salary, gross_salary, HRA, DA;
cout<<"Enter basic salary of Employee : ";
cin>>basic_salary;
if (basic_salary<1500)
{
HRA=0.1*basic_salary;
DA=0.9*basic_salary;
}
else
{
HRA=500;
DA=0.98*basic_salary;
}

gross_salary=basic_salary+HRA+DA;
cout<<"Gross salary is : "<<gross_salary;

getch();
return 0;
}

SAMPLE RUN # 1

Enter basic salary of Employee : 1300


Gross salary is : 2600

SAMPLE RUN # 2

Enter basic salary of Employee : 2500


Gross salary is : 5450

9 Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for upto 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int calls;
float bill;
cout<<"Enter number of calls : ";
cin>>calls;

if(calls<=100)
bill=200;
else if (calls>100 && calls<=150)
{
calls=calls-100;
bill=200+(0.60*calls);
}
else if (calls>150 && calls<=200)
{
calls=calls-150;
bill=200+(0.60*50)+(0.50*calls);
}
else
{
calls=calls-200;
bill=200+(0.60*50)+(0.50*50)+(0.40*calls);
}

cout<<" Your bill is Rs."<<bill;

getch();
return 0;
}

SAMPLE RUN # 1

Enter number of calls : 90


Your bill is Rs.200

SAMPLE RUN # 2

Enter number of calls : 145


Your bill is Rs.227

SAMPLE RUN # 3

Enter number of calls : 190


Your bill is Rs.250

SAMPLE RUN # 4

Enter number of calls : 390


Your bill is Rs.331

10 Write a program to find the roots of and quadratic equation of type ax2+bx+c where
a is not equal to zero. solution

#include<iostream.h>
#include<conio.h>
#include<math.h>

int main()
{
float a,b,c,d,root1,root2;
cout<<"Enter value of a, b and c : ";
cin>>a>>b>>c;
d=b*b-4*a*c;

if(d==0)
{
root1=(-b)/(2*a);
root2=root1;
cout<<"Roots are real & equal";
}
else if(d>0)
{
root1=-(b+sqrt(d))/(2*a);
root2=-(b-sqrt(d))/(2*a);
cout<<"Roots are real & distinct";
}
else
{
root1=(-b)/(2*a);
root2=sqrt(-d)/(2*a);
cout<<"Roots are imaginary";
}

cout<<"\nRoot 1= "<<root1<<"\nRoot 2= "<<root2;

getch();
return 0;
}

SAMPLE RUN # 1

Enter value of a, b and c : 1.0 -10.0 25.0


Roots are real & equal
Root 1= 5
Root 2= 5

SAMPLE RUN # 2

Enter value of a, b and c : 1.0 5.0 2.0


Roots are real & distinct
Root 1= -4.56155
Root 2= -0.438447

SAMPLE RUN # 3

Enter value of a, b and c : 1.0 2.0 5.0


Roots are imaginary
Root 1= -1
Root 2= 2

11 The marks obtained by a student in 5 different subjects are input by the user. The
student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Write a program to calculate the division obtained by the student. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int sub1,sub2,sub3,sub4,sub5,percentage;
cout<<"Enter marks of five subjects : ";
cin>>sub1>>sub2>>sub3>>sub4>>sub5;
percentage=(sub1+sub2+sub3+sub4+sub5)/5;

if(percentage>=60)
cout<<"Ist division";
else if(percentage>=50)
cout<<"IInd division";
else if(percentage>=40)
cout<<"IIIrd division";
else
cout<<"Fail" ;

getch();
return 0;
}

SAMPLE RUN # 1

Enter marks of five subjects : 34 54 67 78 45


II division

SAMPLE RUN # 2

Enter marks of five subjects : 76 64 67 78 53


I division

SAMPLE RUN # 3

Enter marks of five subjects : 34 44 57 38 42


III division

SAMPLE RUN # 4

Enter marks of five subjects : 14 15 26 38 34


Fail
12 Any character is entered by the user; write a program to determine whether the
character entered is a capital letter, a small case letter, a digit or a special symbol.
The following table shows the range of ASCII values for various characters.

Characters ASCII Values

A–Z 65 – 90

a–z 97 – 122

0–9 48 – 57

special symbols 0 - 47, 58 - 64, 91 - 96, 123 – 127

solution
#include<iostream.h>
#include<conio.h>

int main ()
{
char ch;
cout<<"Enter any character:";
cin>>ch;

if (ch>=65 && ch<=90)


cout<<"Character is a capital letter";
else if (ch>=97 && ch<=122)
cout<<"Character is a small letter";
else if (ch>=48 && ch<=57)
cout<<"Character is a digit";
else if ((ch>0 && ch<=47)||(ch>=58 && ch<=64)||
(ch>=91 && ch<=96)||(ch>=123 && ch<=127))
cout<<"Character is a special symbol";

getch();
return 0;
}

SAMPLE RUN # 1

Enter any character:B


Character is a capital letter

SAMPLE RUN # 2

Enter any character:d


Character is a small letter
SAMPLE RUN # 3

Enter any character:5


Character is a digit

SAMPLE RUN # 4

Enter any character:$


Character is a special symbol
flow of control
[SET – 2]
1 Write a program to print number from 1 to 10. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int i=1;

while(i<=10)
{
cout<<i<<"\n";
i++;
}

getch();
return 0;
}

1
2
3
4
5
6
7
8
9
10
2 Write a program to calculate the sum of first 10 natural number. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int i=1,sum=0;

while(i<=10)
{
sum+=i;
i++;
}

cout<<"Sum :"<<sum;

getch();
return 0;
}

Sum : 55

3 Write a program to find the factorial value of any number entered through the
keyboard. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,fact=1;
cout<<"Enter any number : ";
cin>>n;

while(n>=1)
{
fact*=n;
n--;
}

cout<<"Factorial :"<<fact;

getch();
return 0;
}

Enter any number : 7


Factorial : 5040

4 Two numbers are entered through the keyboard. Write a program to find the value
of one number raised to the power of another. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,p,r=1;
cout<<"Enter the base number and exponent ";
cin>>n>>p;

for(int i=1;i<=p;i++)
r=r*n;

cout<<"Result :"<<r;

getch();
return 0;
}
Enter the base number and exponent : 5 3
Result :125

5 Write a program to reveres any given integer number. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,t,r,rev=0;
cout<<"Enter any number : ";
cin>>n;
t=n;

while(t>0)
{
r=t%10;
t=t/10;
rev=rev*10+r;
}

cout<<"Reverse of number "<<n<<" is "<<rev;

getch();
return 0;
}

Enter any number : 6329


Reverse of number 6329 is 9236

6 Write a program to sum of digits of given integer number. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,t,r,sum=0;
cout<<"Enter any number : ";
cin>>n;
t=n;

while(t>0)
{
r=t%10;
sum+=r;
t=t/10;
}

cout<<"Sum of digits of number "<<n<<" is "<<sum;


getch();
return 0;
}

Enter any number : 7865


Sum of digits of number 7865 is 26

7 Write a program to check given number is prime or not. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,flag=0;
cout<<"Enter any number : ";
cin>>n;

for(int i=2;i<n;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}

if(flag==0 && n>1)


cout<<"Number is prime";
else
cout<<"Number is not prime";

getch();
return 0;
}

SAMPLE RUN # 1

Enter any number : 67


Number is prime

SAMPLE RUN # 2

Enter any number : 45


Number is not prime

8 Write a program to calculate HCF of Two given number. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int dividend, divisor, rem, hcf;
cout<<"Enter two numbers : ";
cin>>dividend>>divisor;

while(rem!=0)
{
rem=dividend%divisor;
if(rem==0)
hcf=divisor;
else
{
dividend=divisor;
divisor=rem;
}
}

cout<<"HCF is : "<<hcf;

getch();
return 0;
}

Enter two numbers : 30 105


HCF is : 15

9 Write a program to enter the numbers till the user wants and at the end it should
display the count of positive, negative and zeros entered. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n, sum_p=0, sum_n=0, sum_z=0;
char choice;

do
{
cout<<"Enter number ";
cin>>n;

if(n>0)
sum_p++;
else if(n<0)
sum_n++;
else
sum_z++;

cout<<"Do you want to Continue(y/n)? ";


cin>>choice;
}while(choice=='y' || choice=='Y');

cout<<"Positive Number :"<<sum_p<<"\nNegative Number


:"<<sum_n<<"\nZero Number :"<<sum_z;

getch();
return 0;
}

Enter number : 56
Do you want to Continue(y/n)? y
Enter number : -9
Do you want to Continue(y/n)? y
Enter number : 67
Do you want to Continue(y/n)? y
Enter number : 54
Do you want to Continue(y/n)? y
Enter number : -98
Do you want to Continue(y/n)? y
Enter number : -13
Do you want to Continue(y/n)? y
Enter number : 0
Do you want to Continue(y/n)? y
Enter number : -98
Do you want to Continue(y/n)? y
Enter number : 0
Do you want to Continue(y/n)? n
Positive Number :3
Negative Number :4
Zero Number :2

10 Write a program to enter the numbers till the user wants and at the end it should
display the maximum and minimum number entered. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n, max=0, min=32767;
char choice;

do
{
cout<<"Enter number : ";
cin>>n;

if(n>max)
max=n;
if(n<min)
min=n;

cout<<"Do you want to Continue(y/n)? ";


cin>>choice;

}while(choice=='y' || choice=='Y');

cout<<"Maximum Number :"<<max<<"\nMinimum Number :"<<min;

getch();
return 0;
}

Enter number : 34
Do you want to Continue(y/n)? y
Enter number : 88
Do you want to Continue(y/n)? y
Enter number : 3
Do you want to Continue(y/n)? y
Enter number : 54
Do you want to Continue(y/n)? y
Enter number : 41
Do you want to Continue(y/n)? y
Enter number : 20
Do you want to Continue(y/n)? n
Maximum Number :88
Minimum Number :3

11 Write a program to print out all Armstrong numbers between 1 and 500. If sum of
cubes of each digit of the number is equal to the number itself, then the number is
called an Armstrong number.
For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ) solution

#include<iostream.h>
#include<conio.h>

int main()
{
int n,digit1,digit2,digit3;

for(int i=1;i<=500;i++)
{
digit1=i/100;
digit2=i/10 - digit1*10;
digit3=i%10;

if(digit1*digit1*digit1 + digit2*digit2*digit2 +
digit3*digit3*digit3 == i)
cout<<i<<endl;
}

getch();
return 0;
}

1
153
370
371
407

12 Write a program to print Fibonacci series of n terms where n is input by user : 0 1 1


2 3 5 8 13 24 ..... solution

#include<iostream.h>
#include<conio.h>

int main()
{
int f=0,s=1,t,n;

cout<<"Enter Number of terms of Series : ";


cin>>n;

cout<<f<<" "<<s<<" ";

for(int i=3;i<=n;i++)
{
t=f+s;
cout<<t<<" ";
f=s;
s=t;
}

getch();
return 0;
}

Enter Number of terms of Series : 10


0 1 1 2 3 5 8 13 21 34

13 Write a program to calculate the sum of following series where n is input by user.
1 + 1/2 + 1/3 + 1/4 + 1/5 +…………1/n solution

#include<iostream.h>
#include<conio.h>
int main()
{
int i,n;
float sum=0;

cout<<"Enter the value of n ";


cin>>n;

for(i=1;i<=n;i++)
sum += 1.0/i;

cout<<"Sum : "<<sum;

getch();
return 0;
}

Enter the value of n 5


Sum : 2.28333

14 Compute the natural logarithm of 2, by adding up to n terms in the series


1 - 1/2 + 1/3 - 1/4 + 1/5 -... 1/n
where n is a positive integer and input by user. solution

#include<iostream.h>
#include<conio.h>

int main()
{
int i,n,sign=-1;
float sum=0;
cout<<"Enter the value of n ";
cin>>n;

for(i=1;i<=n;i++)
{
sign *= -1;
sum += sign*1.0/i;
}
cout<<"log 2 : "<<sum;

getch();
return 0;
}

SAMPLE RUN # 1

Enter the value of n 5


log 2 : 0.783333

SAMPLE RUN # 2

Enter the value of n 10000


log 2 : 0.693091
Flow of Control
[SET – 3]
1 Write a program to print following : solution
i) ********** ii)*
********** **
********** ***
********** ****
*****
iii) *
***
*****
*******
*********

//Solution of (i)
#include<iostream.h>
#include<conio.h>

int main()
{
int i,j;
for(i=1;i<=4;i++)
{

for(j=1;j<=10;j++)

cout<<'*';

cout<<endl;
}

getch();
return 0;
}

//Solution of (ii)
#include<iostream.h>
#include<conio.h>

int main()
{
int i,j;
for(i=1;i<=5;i++)
{

for(j=1;j<=i;j++)

cout<<'*';
cout<<endl;
}

getch();
return 0;
}

//Solution of (iii)
#include<iostream.h>
#include<conio.h>

int main()
{
int i,j,k;
for(i=1;i<=5;i++)
{

for(j=5;j>i;j--)

cout<<' ';

for(k=1;k<2*i;k++)

cout<<'*';

cout<<endl;
}

getch();
return 0;
}

2 Write a program to compute sinx for given x. The user should supply x and a positive
integer n. We compute the sine of x using the series and the computation should use
all terms in the series up through the term involving xn

sin x = x - x3/3! + x5/5! - x7/7! + x9/9! ........ solution

#include<iostream.h>
#include<conio.h>

int main()
{
int i,j,n,fact,sign=-1;
float x, p=1,sum=0;
cout<<"Enter the value of x : ";
cin>>x;
cout<<"Enter the value of n : ";
cin>>n;

for(i=1;i<=n;i+=2)
{
fact=1;
for(j=1;j<=i;j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum+=sign*p/fact;
}
cout<<"sin "<<x<<"="<<sum;

getch();
return 0;
}

Enter the value of x : 1


Enter the value of n : 10
sin 1 = 0.841471

3 Write a program to compute the cosine of x. The user should supply x and a positive
integer n. We compute the cosine of x using the series and the computation should use
all terms in the series up through the term involving xn

cos x = 1 - x2/2! + x4/4! - x6/6! ..... solution

#include<iostream.h>
#include<conio.h>

int main()
{
int i,j,n,fact,sign=-1;
float x, p=1,sum=0;
cout<<"Enter the value of x : ";
cin>>x;
cout<<"Enter the value of n : ";
cin>>n;

for(i=2;i<=n;i+=2)
{
fact=1;
for(j=1;j<=i;j++)
{
p=p*x;
fact=fact*j;
}
sum+=sign*p/fact;
sign=-1*sign;
}
cout<<"cos "<<x<<"="<<1+sum;

getch();
return 0;
}

Enter the value of x : 1


Enter the value of n : 5
cos 1 = 0.541667
MULTIPLE CHOICE QUESTIONS AND ANSWERS

1. Object _______ and operator _______ are used for reading.


a) cin >>
b) cout >>
c) cin <<
d) cout <<
e) none of the above

Answer: (a)

2. For reading with cin object, we need to include __________file.


a) conio.h
b) fstream.h
c) stdio.h
d) iostream.h
e) none of the above

Answer: (d)

3. Manipulators without parameters such as endl, hex, dec etc are defined in __________ file.
a) iomanip.h
b) conio.h
c) io.h
d) fstream.h
e) none of the above

Answer: (e)

4. Of the following, _________ is not a manipulator.


a) dec
b) scientific
c) endl
d) flush
e) hex

Answer: (b)

5. Of the following _________ is not an ios flag.


a) dec
b) showbase
c) hex
d) flush
e) None of these

Answer: (d)
6. Statement cin >> ch ; will start executing when we press _______ key.
a) any
b) any character
c) only character
d) escape
e) enter

Answer: (e)
Other C++ Interview Questions with answers

Question : Why main function is special in C++ ?

Answer : Whenever a C++ program is executed, execution of the program starts and ends at
main(). The main is the driver function of the program. If it is not present in a program, no
execution can take place.

Question : What is run-time error, logical error and syntax error?

Answer : Syntax error - The errors which are traced by the compiler during compilation, due to
wrong grammar for the language used in the program, are called syntax errors.
For example, cin<<a; // instead of extraction operator insertion operator is used.
Run time Error - The errors encountered during execution of the program, due to unexpected
input or output are called run-time error.
For example - a=n/0; // division by zero
Logical Error - These errors are encountered when the program does not give the desired
output, due to wrong logic of the program.
For example : remainder = a+b // instead of using % operator + operator is used.

Question : What is the role of #include directive in C++?

Answer : The preprocessor directive #include tells the complier to insert another file into your
source file. In effect, #include directive is replaced by the contents of the file indicated.

Question : What is compiler and linker?

Answer : Compiler - It is a program which converts the program written in a programming


language to a program in machine language.
Linker - It is a program which links a complied program to the necessary library routines, to
make it an executable program. more details

Question : Why is char often treated as integer data type in C++ ?

Answer : The memory implementation of char data type is in terms of the number code.
Therefore, it is said to be another integer data type.

Question : What is type conversion in C++ ?

Answer : When two operands of different data types are encountered in the same expression, the
variable of lower data type is automatically converted to the data tpes of variable with higher
data type, and then the expression is calculated.
For example: int a=98; float b=5; cout<<a/3.0; //converts to float type, since 3.0 is of float type.
cout<<a/b; // converts a temporarily to float type, since b is of float type, and gives the result
19.6.
Question : What is type casting in C++ ?

Answer : Type casting refers to the data type conversions specified by the programmer, as
opposed to the automatic type conversions. This can be done when the compiler does not do the
conversions automatically. Type casting can be done to higher or lower data type.
For example : cout<<(float)12/5; //displays 2.4, since 12 is converted to float type.

Question : What is the effect of absence of break in switch case in C++ ?

Answer : The break keyword causes the entire switch statement to exit, and the control is passed
to statement following the switch.. case construct. Without break, the control passes to the
statements for the next case. The break statement is optional in switch..case construct.

Question : In control structure switch-case what is the purpose of default in C++


?

Answer : This keyword gives the switch..case construct a way to take an action if the value of
the switch variable does not match with any of the case constants. No break statement is
necessary after default case, since the control is already at the end of switch..case construct. The
default is optional in case of switch..case construct.

Question : What is the difference between while and do-while loop?

Answer : While is an Entry Controlled Loop, the body of the loop may not execute even once if
the test expression evaluates to be false the first time, whereas in do..while, the loop is executed
at least once whether the condition holds true the first time or not. more details

Question : What is the difference between call by value and call by reference in a
user defined function in C++?

Answer : The value of the actual parameters in the calling function do not get affected when the
arguments are passed using call by value method, since actual and formal parameters have
different memory locations.
The values of the formal parameters affect the values of actual parameters in the calling function,
when the arguments are passed using call by reference method. This happens since the formal
parameters are not allocated any memory, but they refer to the memory locations of their
corresponding actual parameters. more details

Question : What is preprocessor directive?

Answer : A preprocessor directive is an instruction to the complier itself. A part of compiler


called preprocessor deals with these directives, before real compilation process. # is used as
preprocessor directive in C++.

Question : What is the difference between local variable and global variable?
Answer : Local variables are those variables which are declared within a function or a
compound statement and these variables can only be used within that function/scope. They
cannot be accessed from outside the function or a scope of it's declaration. This means that we
can have variables with the same names in different functions/scope. Local variables are local to
the function/scope in which they are declared.
Global variables are those variables which are declared in the beginning of the program. They
are not declared within a function. So, these variables can be accessed by any function of the
program. So, global variables are global to all the functions of the program.

Question : What is the role of #define in C++?

Answer : It is a preprocessor directive to define a macro in a C++ program. Macros provide a


mechanism for token replacement with or without a set of formal, function line parameters. For
example :
#define PIE 3.1416
#define AVG(A,B,C) (A+B+C)/3

Question : What are the major differences between Object Oriented


Programming and Procedural Programming?

Object Oriented Programming


*Emphasis on data
*Follow bottom up approach in program design
*Concept of Data hiding prevents accidental change in the data
*Polymorphism, inheritance, Data Encapsulation possible
Procedural Programming
*Emphasis on doing things (function)
*Follow top-down approach in program design
*Due to presence of global variables, there are possibilities of accidental change in data. more
details

Question : What are the basic concepts of OOP?

Answer :Data Abstraction, Data Hiding, Data Encapsulation, Inheritance and Polymorphism are
the basic concepts of OOP. more details

Question : How is OOP implement in C++?

Answer : A class binds together data and its associated function under one unit thereby
enforcing encapsulation.
The private and protected member remain hidden from outside world. Thus a class enforces data
hiding
The outside world is given only the essential information through public members, thereby
enforcing abstraction.

Question : What is abstract class?


Answer : A class with no instances (no objects) is known as abstract class.

Question : What is concrete class?

Answer : A class having objects is known as concrete class.

Question : What is a constructor? What are its features?

Answer : It is a member function of class with the following unique features.


It has same name as the name of the class they belong to.
It has no return type.
It is defined in public visibility mode.
It is automatically called & executed when an object is declared/created.
Constructor can be overloaded. more details

Question : What does a destructor do?

Answer : A destructor deinitializes an object and deallocates all allocated resources.

Question : Define inheritance.

Answer : Inheritance is a process of creating new classes (derived classes) from existing classes
(base classes). The derived classes not only inherit capabilities of the base class but also can add
new features of own. The most important aspect of inheritance is that it allows reusability of
code. more details

Question : Define Base class and derived class.

Answer : Base Class: A class from which another class inherits.


Derived Class: A class inheriting properties from another class.

Question : What are the different forms of inheritance in C++ ?

Answer : Single level inheritance, Multilevel inheritance, Hierarchical inheritance, Multiple


inheritance and Hybrid inheritance. more details

Question : What is virtual base class in C++ ? What is its significance?

Answer : Multipath inheritance may lead to duplication of inherited members from a


grandparent base class. This may be avoided by making the common base class a virtual base
class. When a class is made a virtual base class, C++ takes necessary care to see that only one
copy of that class is inherited. more details

Question : How are binary files different from text files in C++?
Answer : A text file store information in ASCII characters. In text files, each line of text is
terminated, with a special character known as EOL character.
A binary file store information in the same format in which the information is held in memory.
In binary file, there is no delimeter for a line.

Question : What is a stream? Name the streams generally used for file I/O.

Answer : A stream is a sequence of byte.


ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files. more details

Question : Difference between get() and getline().

Answer : get() does not extract the delimeter newline character from input stream. On the other
hand getline() does extract the delimeter newline character from the input stream so that the
stream is empty after getline() is over.

Question : Difference between ios::app and ios::out.

Answer : The ios::out is the default mode of ofstream. With the mode of the file does not exist, it
gets created but if the file exists then its existing contents get deleted.
The ios::app is output mode of ofstream. With the mode of the file does not exist, it gets created
but if the file exists then its existing contents are retained and new information is appended to it.
more details

Question : What is pointer?

Answer : Pointer is an address of a memory location. A variable, which holds an address of a


memory location, is known as a Pointer variable (or Simply Pointer). For example int *P; more
details

Question : What is pointer arithmetic ? How is it performed?

Answer : Some arithmetic operators can be used with pointers:


Increment and decrement operators ++, --
Integers can be added to or subtracted from pointers using the operators +, -, +=, and -=
Each time a pointer is incremented by 1, it points to the memory location of the next element of
its base type.
If "p" is a character pointer then "p++" will increment "p" by 1 byte.
If "p" were an integer pointer its value on "p++" would be incremented by 2 bytes.

Question : Differentiate between static and dynamic allocation of memory.

Answer : In the static memory allocation, the amount of memory to be allocated is predicted and
preknown. This memory is allocated during the compilation itself.
In the dynamic memory allocation, the amount of memory allocated is not known beforehead.
This memory is allocated during run time as and when required.

Question : What do you understand by memory leaks? How can memory leaks
be avoided?

Answer : Memory leak is a situation in which there lie so many orphaned memory blocks that
are still allocated but no pointers are referencing to them.

Question : What is this pointer? What is its Significance?

Answer : The this pointer is an object pointer which points to the currently calling object, The
this pointer is, by default, available to each called member function.

Question : What is the full form of LIFO? Give an example of LIFO list?

Answer : Full form of LIFO is LAST IN FIRST OUT. An example of LIFO list is stack. Stack is
a linear data structure in which insertion and deletion of elements takes place only one end
known as TOP.

Question : What is the full form of FIFO? What is FIFO list technically called?

Answer : Full form of FIFO is FIRST IN FIRST OUT. An example of FIFO list is Queue.
Queue is a linear data structure in which insertion and deletion of elements takes place from two
opposite ends rear and front respectively.

Question : What are the preconditions for Binary search to be performed on a


single dimensional array?

Answer : Precondition for Binary search to be performed on a single dimensional array is array
should be sorted.

1. What is C++

C++ is created by Bjarne Stroustrup of AT&T Bell Labs as an extension of C, C++ is an object-oriented
computer language used in the development of enterprise and commercial applications. Microsoft’s
Visual C++ became the premier language of choice among developers and programmers.

2. What are the basic concepts of object oriented programming?


It is necessary to understand some of the concepts used extensively in object oriented
programming.These include

 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message passing

3. Define inheritance?

The mechanism of deriving a new class (derived) from an old class (base class) is called inheritance. It
allows the extension and reuse of existing code without having to rewrite the code from scratch.
Inheritance is the process by which objects of one class acquire properties of objects of another
class.

4. Define polymorphism?

Polymorphism means one name, multiple forms. It allows us to have more than one function with
the same name in a program.It allows us to have overloading of operators so that an operation can
exhibit different behaviours in different instances.

5. What are the features of C++ different from C?

 All the features of C are similiar to C++ except some features, such as polymorphism,
operator overloading which are supported in C++ but not in C language.
 Both C and C++ language is similiar in their functionality but C++ provides with more tools
and options.

6. What is encapsulation?
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation. Encapsulation containing and hiding information about an object, such as
internal data structures and code.

7. What is message passing?


An object oriented program consists of a set of objects that communicate with each other.
Message passing involves specifying the name of the object, the name of the function and the
information to be sent.
8. What are tokens in C++?
The smallest individual units of a program is known as tokens. c++ has the following
tokens :

 Keywords
 Identifiers
 Constants
 Strings
 Operators

9. What is the use of enumerated data type?


An enumerated data type is another user defined type which provides a way for attaching
names to numbers thereby increasing comprehensibility of the code. The enum keyword
automatically enumerates a list of words by assigning them values 0,1,2, and so on.

10. What is the use of default constructor?


A constructors that accepts no parameters is called the default constructor.If no user-defined
constructor exists for a class A and one is needed, the compiler implicitly declares a default
parameterless constructor A::A(). This constructor is an inline public member of its class.
The compiler will implicitly define A::A() when the compiler uses this constructor to create
an object of type A. The constructor will have no constructor initializer and a null body.
11. Define Constructors?
A constructor is a member function with the same name as its class. The constructor is
invoked whenever an object of its associated class is created.It is called constructor because
it constructs the values of data members of the class.

12. How variable declaration in c++ differs that in c?


C requires all the variables to be declared at the beginning of a scope but in c++ we can
declare variables anywhere in the scope. This makes the programmer easier to understand
because the variables are declared in the context of their use.

13. Define destuctors?


A destructor is called for a class object when that object passes out of scope or is explicitly
deleted.A destructors as the name implies is used to destroy the objects that have been
created by a constructors.Like a constructor , the destructor is a member function whose
name is the same as the class name but is precided by a tilde.

14. What is a class?


A class is a collection of objects.

15. what is the difference between c & c++?


 C++ ia an object oriented programing but C is a procedure oriented programing.
 C is super set of C++.
 C can’t suport inheritance, function overloading, method overloading etc. but c++
can do this.
 In c program the main function could not return a value but in the c++ the main
function shuld return a value.

16. What are the few advantages of Inline function?


 It offers an improved macro facility.
 By using the inline functions, the user can split a large function with many nested
modules of statement blocks into many small inline functions.

17. What is copy constructor?


Copy constructor is a constructor function with the same name as the class and used to make
deep copy of objects.

18. What is default constructor?


A default constructor is a constructor that either has no parameters, or if it has parameters,
all the parameters have default values.

19. What is a scope resolution operator?


The scope resolution operator permits a program to reference an identifier in the global
scope that has been hidden by another identifier with the same name in the local scope.

20. What is the difference between Object and Instance?


 An instance of a user-defined type is called an object. We can instantiate many
objects from one class.
 An object is an instance of a class.

21. What is the difference between macro and iniine?


Inline follows strict parameter type checking, macros do not.
Macros are always expanded by preprocessor, whereas compiler may or may not replace the
inline definitions.

22. How variable declaration in c++ differs that in c?


C requires all the variables to be declared at the beginning of a scope but in c++ we can
declare variables anywhere in the scope. This makes the programmer easier to understand
because the variables are declared in the context of their use.

23. What is multiple inheritance?


A class can inherit properties from more than one class which is known as multiple
inheritance.

24. what is the use of virtual destructor in c++?


A destructor is automatically called when the object is destroyed. A virtual destructor in
C++ is used primarily to prevent resource leaks by performing a clean-up of the object.

25. What do you mean by reference variable in c++?


A reference variable provides an alias to a previously defined variable.
Data -type & reference-name = variable name
26. What is iterator class?
 Iterator class provides an access to the class which are inside the containers(it holds a
group of objects in an organized way).
 The containers include the data structure, class and abstract data type.

27. What are the types of declarations in C++?


There are so many types of declaration in C++ are :

 Variable declaration
 Constant declaration
 Function declaration
 Object declaration

28. What are Smart pointers?


Smart pointers are almost similar to pointers with additional features such as automatic
destruction of a variable when it becomes out of scope and the throwing of exceptions that
ensures the proper destruction of the dynamically allocated objects.

29. Explain function template?


Function template provides a means to write generic functions for different data types such
as integer, long, float or user defined objects.

30. Explain class template?


Class template provides a means to write a generic class for different types so that a class
can have members based on generic types that do not need to be defined at the moment of
creating the class or whose members use these generic types.
31. what is difference between function overloading and operator overloading?
A function is overloaded when same name is given to different function.
While overloading a function, the return type of the functions need to be the same.

32. What are the advantages of inheritance?


 Code reusability
 Saves time in program development.

33. What is a dynamic constructor?


The constructor can also be used to allocate memory while creating objects. Allocation of
memory to objects at the time of their construction is known as dynamic construction of
objects.The memory is allocated with the help of the new operator.

34. What is the difference between an Array and a List?


The main difference between an array and a list is how they internally store the data.
whereas Array is collection of homogeneous elements. List is collection of heterogeneous
elements.

35. What is the use of ‘using’ declaration?


A using declaration makes it possible to use a name from a namespace.
36. What is the difference between a template class and class template?
Template classA generic definition or a parameterized class not instantiated until the client
provides the needed information. It’s jargon for plain templates.
Class templateA class template specifies how individual classes can be constructed much
like the way a class specifies how individual objects can be constructed. It’s jargon for plain
classes.

37. What is friend function?


The function declaration should be preceded by the keyword friend.The function definitions
does not use either the keyword or the scope operator ::. The functions that are declared with
the keyword friend as friend function.Thus, a friend function is an ordinary function or a
member of another class.

38. What is a scope resolution operator?


A scope resolution operator (::), can be used to define the member functions of a class
outside the class.

39. What do you mean by pure virtual functions?


A pure virtual member function is a member function that the base class forces derived
classes to provide. Any class containing any pure virtual function cannot be used to create
object of its own type.

40. What is a conversion constructor?


A converting constructor is a single-parameter constructor that is declared without the
function specifier explicit. The compiler uses converting constructors to convert objects
from the type of the first parameter to the type of the converting constructor’s class.
41. What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A
container class acts as a generic holder. A container class has a predefined behavior and a
wellknown interface. A container class is a supporting class whose purpose is to hide the
topology used for maintaining the list of objects in memory. When a container class contains
a group of mixed objects, the container is called a heterogeneous container; when the
container is holding a group of objects that are all the same, the container is called a
homogeneous container.

42. What is Associative container?


Associative containers are designed to support direct access to elements using keys.
They are not sequential. There are four types of associatives containers :

 Set
 Multiset
 Map
 Multimap

43. What is an iterator?


Iterators are like pointers. They are used to access the elements of containers thus providing
a link between algorithms and containers. Iterators are defined for specific containers and
used as arguments to algorithms.

44. What are the defining traits of an object-oriented language?


The defining traits of an object-oriented langauge are :

 Encapsulation
 Inheritance
 Polymorphism

45. Name some pure object oriented languages?


 Smalltalk
 Java
 Eiffel
 Sather

46. What is this pointer?


It is a pointer that points to the current object. This can be used to access the members of the
current object with the help of the arrow operator.

47. What is encapsulation?


Encapsulation (or information hiding) is the process of combining data and functions into a
single unit called class.

48. What is problem with Runtime type identification?


The run time type identification comes at a cost of performance penalty. Compiler maintains
the class.

49. What are the differences between new and malloc?


 New initializes the allocated memory by calling the constructor. Memory allocated
with new should be released with delete.
 Malloc allocates uninitialized memory.
 The allocated memory has to be released with free.new automatically calls the
constructor while malloc(dosen’t)

50. What is conversion operator?


You can define a member function of a class, called a conversion function, that converts
from the type of its class to another specified type.
51. What do you mean by implicit conversion?
 Whenever data types are mixed in an expression then c++ performs the conversion
automatically.
 Here smaller type is converted to wider type.
 Example : in case of integer and float integer is converted into float type.

52. What are virtual functions?


 The virtual fuctions must be members of some class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.

53. What is the main purpose of overloading operators?


 The main purpose of operator overloading is to minimize the chances of occurance
of errors in a class that is using the overload operators.
 It also helps in redefining the functionalities of the operators to improve their
performance.
 Operator overloading also makes the program clearer, readable and more
understandable by using common operators, such as +, =, and [].

54. What is a friend?


Friends can be either functions or other classes. The class grants friends unlimited access
privileges.

55. What is stack unwinding?


Stack unwinding is a process in which a destructor is invoked in a particular program for
destroying all the local objects in the stack between throwing and catching of an exception.
56. What is the difference between class and structure?
 By default, the members ot structures are public while that tor class is private.
 structures doesn’t provide something like data hiding which is provided by the
classes.
 structures contains only data while class bind both data and member functions.

57. What are storage qualifiers in C++ ?


ConstKeyword indicates that memory once initialized, should not be altered by a program.
Volatile keyword indicates that the value in the memory location can be altered even though
nothing in the program.
Mutable keyword indicates that particular member of a structure or class can be altered even
if a particular structure variable, class, or class member function is constant.

58. What is virtual class and friend class?


Friend classes are used when two or more classes and virtual base class aids in multiple
inheritance.
Virtual class is used for run time polymorphism when object is linked to procedure call at
run time.

59. What is an abstract base class?


An abstract class is a class that is designed to be specifically used as a base class. An
abstract class contains at least one pure virtual function.

60. What is dynamic binding?


Dynamic binding (also known as late binding) means that the code associated with a given
procedure call is not known until the time of the call at run time.It is associated with
polymorphism and inheritance.
61. What are the benefits of object oriented programming(OOP)?
 Software reusability
 Code sharing
 Rapid prototyping
 Information hiding

62. What is the form of assignment statement?


Variable = expression ( or constant )

63. What is the main purpose of overloading operators?


The main purpose of operator overloading is to minimize the chances of occurrence of errors
in a class that is using the overloaded operators.

64. What is this pointer?


When a member function is invoked, the invoking objects pointer is passed implicitly as an
argument. This pointer is called this pointer.

65. What is scope resolution operator?


The Scope resolution operator(::) can be used to define the member functions of a program
outside the boundary of a class and not within the class specifier.
66. What are static members and static functions?
Static members are

 Created and initialized only once.


 Shared among all the class objects.

Static functions are

 Similar to the static variables and are associated with the class.
 Can only access static variables of a class.
 Can also be called using the scope resolution operator.

67. What are the components of a class?


A class consists of two components,

 Data members
 Methods

68. What is the advantage of using templates?


 Templates provide a means to write generic functions and classes for different data
types.
 Templates are sometimes called parameterized types.
 Templates can significantly reduce source code size and increase code flexibility
without reducing type safety.

69. Can a function overloading depend only on passing by value and passing by reference?
No, the reason is that whether a function is called the passing a parameter as a value or by
reference, it appears similar to the caller of the function.

70. Is it possible to use a new for the reallocation of pointers?


The reallocation of pointers cannot be done by using new. It can be done by using the
realloc() operator.

71. What are the types of storage qualifiers in C++?


C++ includes three storage qualifiers:

 Const : A const variable is one that the program may not modify except through
initialiazation when the variable is declared.
 Volatile: A volatile type qualifier tells the compiler that the program could change
the variable.
 Mutable: A const member function may modify a data member only if the data
member is declared with the mutable qualifier.

72. What are the advantages of using on iterator?


Iterator interfaces(API) are the same for all the containers. For example, a container list can
internally have doubly linked list or singly list, but its corresponding iterator interface that is
used to access its elements is always the same.
(iter->next)

73. What are data members?


Data members are variables of any type(in-built or user defined).

74. What are the types of statements in c++?


A program in any langauge basically consists of statements. Statements symbolize
instructions. There are many categories of statements.

 Expression statement
 Assignment statement
 Selection statement
 Iteration statement
 Jump statement

75. What is initialization?


Initialization is a process of assigning a value to a variable at the time of declaration.
76. What is the difference between a vector and a map?
A vector is a sequential container, i.e., all the elements are in a sequence, whereas a map is
an association container, i.e., all elements are stored in the form of a key value association
pair.

What are the advantages of using cin and cout compared to scanf(...) and printf(...),
77.
respectively?
 Compared to the standard C functions printf() and scanf(), the usage of the cin and
cout is more type safe.
 The format strings, which are used with printf() and scanf() can define wrong format
specifies for their arguments, for which the compiler does not warn.
 In contrast, argument checking with c in and cout is performed by the compiler.
 C in and Cout are stream classes that could be used to receive and print objects
respectively.

78. Explain copy constructor?


A copy constructor is a special type of constructor which initializes all the data members of
the newly created object by copying the contents of an existing object. The compiler
provides a default copy constructor.
Class_name new _ object ( existing object);

79. What are the advantages of operator overloading?


Operator overloading is used to provide some extra features, behaviors and abilities to the
users of a particular class. This feature in C++ helps in controlling the functions performed
by an operator and reduces the chance of occurrence of errors in a program.

80. What is a dangling pointer?


When the location of the deallocated memory is pointed by the pointer even after the
deletion or allocation of objects is done, without the modification in the value of the pointer,
then this type of pointer is called a dangling pointer.
81. What are shallow and deep copies?
A shallow copy is used to copy actual values of the data. It means, if the pointer points to
dynamically allocated memory, the new object’s pointer in the copy still points to items
inside the old objects and the returned object will be left pointing to items that are no longer
in scope.
A copy of the dynamically allocated objects is created with the help of deep copy. This is
done with the help of an assignment operator, which needs to be overloaded by the copy
constructor.

82. How can you return the current involving object from its member function?
return(*this);

83. What is the difference between prefix and postfix versions of operator++()?
 The prefix and postfix versions of operator ++() can be differentiated on the basis of
arguments defined.
 The postfix operator ++() consists of a dummy parameter of int datatype; whereas, a
dummy parameter is not found in the prefix operator ++().

84. Can a static member function access member variable of an object?


No, because to access the member variable of an object inside its member function, this
pointer is required. Since static functions are class functions, this pointer will not be passed
as its arguments.

85. What is the advantages of using the Inline function?


 An inline keyword before a function suggests the compiler to insert the complete
body of the function wherever that function is invoked.
 Inline expansion is typically used to eliminate the inherent cost involved in calling a
function.
 It is typically used for functions that need quick execution.

86. What are all the operators that cannot be overloaded?


 Direct member access operator
 De–reference pointer to class member operator.*
 Scope resolution operator::
 Conditional operator ?:
 Sizeof operator sizeof

87. Can a function be overloaded based on return types?


Function signature does not depend on the return type. So overloading cannot be resolved by
the return type alone.

88. What do you mean by a public member?


 A member declared as public is a public member.
 It can be accessed freely in a program.

89. Is recursion allowed in inline functions?


The recursion is allowed in inline fucntion but practically, the inline functions and their
properties do not remain inside the program. Moreover, the compiler is not sure about the
depth of the recursion at the time of compilation.

90. What is virtual function?


A virtual function is a member function that is declared within a base class and redefined by
a derived class .To create a virtual function, the function declaration in the base class is
preceded by the keyword virtual.
12345678910111
91. How can a struct in C++ differs from a struct in C?
The differences between struct in C++ and C are listed in the following points:

 In C and C++, the variables of the structures are public; however, in C, the variable
cannot be declared as private or protected. On the contrary, in C++, the variables can
be declared as private or protected.
 In C, the concept of inheritance is not supported. In C++, the concept of inheritance
is fully supported.
 On declaring a struct in C, the addition of the struct keyword is must. On the
contrary, there is no need of the struct keyword on declaring struct in C++.
 In C, the initialization cannot be done outside the scope of a structure. However, in
C++, the initialization can be done outside the scope of a structure.
 In C, structures do not have direct functions or methods.

92. How the keyword struct is different from the keyword class in C++?
In C++, a class is similar to a struct with the exception that, by default, all the members of a
class are private; while the members of a struct are public. Encapsulation is not supported by
structures but supported by classes.

93. Define pure virtual function?


Pure virtual function is defined as a virtual function in a base class. It is implemented in a
derived class. A program may not declare an instance of a class that has a pure virtual
function.

94. Define a conversion constructor?


A conversion constructor is a single argument constructor. It is used by the compiler to
ocnvert a type of objects as an argument to a class type.

95. What is a default constructor?


A zero argument constructor or a constructor in which all the arguments have default values
is called a default constructor.
96. What is difference between template and macro?
A template can be used to create a family of classes or function.A template describes a set of
related classes or set of related functions in which a list of parameters in the declaration
describe how the members of the set vary.
Identifiers that represent statements or expressions are called macros.

97. What is reference?


Reference is a name that acts as an alias, or alternative name, for a previously defined
variable or an object.

98. What are the access specifier in c++?


There are three types of access specifier in c++ . They are

 Public
 protected
 private

99. What is difference between C++ and Java?


 C++ has pointers Java does not.
 Java is the platform independent as it works on any type of operating systems.
 java has no pointers where c ++ has pointers.
 Java has garbage collection C++ does not.

100. What is namespace?


The C++ language provides a single global namespace.Namespaces allow to group entities
like classes, objects and functions under a name.
101. What is an explicit constructor?
A conversion constructor declared with the explicit keyword. The compiler does not use an
explicit constructor to implement an implied conversion of types. It’s purpose is reserved
explicitly for construction.Explicit constructors are simply constructors that cannot take
part in an implicit conversion.

102. What is the use of storage class specifiers?


A storage class specifier is used to refine the declaration of a variable, a function,
and parameters. The following are storage class specifiers :

 auto
 register
 static
 extern

103. what is assignment operator in c++?


Default assignment operator handles assigning one object to another of the same class.
Member to member copy (shallow copy).

104. Can destructor be private?


Yes destructors can be private. But according it is not advisable to have destructors to be
private.

105. What is strstream?


stringstream provides an interface to manipulate strings as if they were input/output
streams.
‹ strstream› to define several classes that support iostreams operations on sequences stored
in an allocated array of char object.
106 What are the types of STL containers?
 deque
 hash map
 hashmultimap
 hash_multiset
 hashset
 list
 map
 multimap
 multiset
 set
 vector

107. What is the difference between method overloading and method overriding?
Overloading a method (or function) in C++ is the ability for functions of the same name to
be defined as long as these methods have different signatures (different set of parameters).
Method overriding is the ability of the inherited class rewriting the virtual method of the
base class.

108. What do you mean by inline function?


An inline function is a function that is expanded inline when invoked.ie. the compiler
replaces the function call with the corresponding function code. An inline function is a
function that is expanded in line when it is invoked. That is the compiler replaces the
function call with the corresponding function code (similar to macro).

109. What is a template?


A template can be used to create a family of classes or function.A template describes a set
of related classes or set of related functions in which a list of parameters in the declaration
describe how the members of the set vary.

110. What is a copy constructor and when is it called?


A copy constructor is a method that accepts an object of the same class and copies it
members to the object on the left part of assignement.
111. What is the difference between a copy constructor and an overloaded assignment operator?
A copy constructor constructs a new object by using the content of the argument object. An
overloaded assignment operator assigns the contents of an existing object to another
existing object of the same class.
112. What is a virtual destructor?
The simple answer is that a virtual destructor is one that is declared with the virtual
attribute.

113. What do you mean by Stack unwinding?


It is a process during exception handling when the destructor is called for all local objects
between the place where the exception was thrown and where it is caught.

114. What is STL? and what are the components of stl?


A collection of generic classes and functions is called as Standard Template Library
(STL).The stl components are

 containers
 Algorithm
 Iterators

115. What is a modifier?


A modifier, also called a modifying function is a member function that changes the value
of at least one data member. In other words, an operation that modifies the state of an
object. Modifiers are also known as mutators.

116. What is an adaptor class or Wrapper class?


A class that has no functionality of its own. Its member functions hide the use of a third
party software component or an object with the non-compatible interface or a non-
objectoriented implementation.

117. What is a Null object?


It is an object of some class whose purpose is to indicate that a real object of that class does
not exist. One common use for a null object is a return value from a member function that
is supposed to return an object with some specified properties but cannot find such an
object.

118. What is class invariant?


A class invariant is a condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants must hold when an
object is created, and they must be preserved under all operations of the class. In particular
all class invariants are both preconditions and post-conditions for all operations or member
functions of the class.

119. What is the difference between the message and method?


Message : Objects communicate by sending messages to each other.A message is sent to
invoke a method.
Method : Provides response to a message and it is an implementation of an operation.

120. Is it possible to use a new for the reallocation of pointers?


The reallocation of pointers cannot be done by using new. It can be done by using the
realloc() operator.
121. How can we access protected and private members of a class?
In the case of members protected and private, these could not be accessed from outside the
same class at which they are declared. This rule can be transgressed with the use of the
friend keyword in a class, so we can allow an external function to gain access to the
protected and private members of a class.

122. What do you mean by late binding?


Late binding refers to function calls that are not resolved until run time. Virtual functions
are used to achieve late binding. When access is via a base pointer or reference, the virtual
function actually called is determined by the type of object pointed to by the pointer.

123. What do you mean by early binding?


Early binding refers to the events that occur at compile time. Early binding occurs when all
information needed to call a function is known at compile time. Examples of early binding
include normal function calls, overloaded function calls, and overloaded operators. The
advantage of early binding is efficiency.

You might also like