C++ Programming Examples and Solutions
C++ Programming Examples and Solutions
#include <iostream>
using namespace std;
int main()
{
int n, reverse=0, rem;
cout<<"Enter a number: ";
cin>>n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
cout<<"Reversed Number: "<<reverse<<endl;
return 0;
}
int main()
{
int a, b, c;
c = a + b;
cout <<"Sum of the numbers: " << c << endl;
return 0;
}
1
3. Write a C++ program to check whether a given number is prime.
#include <iostream>
int main() {
char c = 'b'; //local variable
return 0;
}
2
5. Write a C++ program to check whether a given year is leap year or not.
#include <iostream>
using namespace std;
int main()
{
int year;
if (year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
cout << year << " is a leap year.";
else
cout << year << " is not a leap year.";
}
else
cout << year << " is a leap year.";
}
else
cout << year << " is not a leap year.";
return 0;
}
//function declaration
int addition(int a,int b);
int main()
{
int num1; //to store first number
int num2; //to store second number
int add; //to store addition
//read numbers
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
//call function
3
add=addition(num1,num2);
//print addition
cout<<"Addition is: "<<add<<endl;
return 0;
}
//function definition
int addition(int a,int b)
{
return (a+b);
}
7. Write a C++ program to accept and display the details of a student using class.
#include<iostream>
using namespace std;
class student
{
private:
char name[20],regd[10],branch[10];
int sem;
public:
void input();
void display();
};
void student::input()
{
cout<<"Enter Name:";
cin>>name;
cout<<"Enter Regdno.:";
cin>>regd;
cout<<"Enter Branch:";
cin>>branch;
cout<<"Enter Sem:";
cin>>sem;
}
void student::display()
{
cout<<"\nName:"<<name;
cout<<"\nRegdno.:"<<regd;
cout<<"\nBranch:"<<branch;
cout<<"\nSem:"<<sem;
}
int main()
{
student s;
s.input();
s.display();
}
4
8. Write a C++ program to accept and display the details of an employee using a
class.
#include<iostream.h>
#include<conio.h>
class employee
{
int emp_no;
char emp_name[20];
float emp_sal;
public:
void get();
void dis();
};
void employee::get()
{
cout<<"Enter employee number:";
cin>>emp_no;
cout<<"Enter employee name:";
cin>>emp_name;
cout<<"Enter salary:";
cin>>emp_sal;
}
void employee::dis()
{
cout<<"\n\tEmployee Details";
cout<<"\n\t Number : "<<emp_no;
cout<<"\n\t Name : "<<emp_name;
cout<<"\n\t Salary : "<<emp_sal;
}
void main()
{
clrscr();
employee e;
e.get();
e.dis();
getch();
}
5
9. Write a C++ program to count the number of words and characters in a given text.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50];
int count = 0, i;
cout << "Enter a string : ";
gets(str);
for (i = 0; str[i] != '\0';i++)
{
if (str[i] == ' ')
count++;
}
cout << "Number of words in the string are: " << count + 1;
return 0;
}
10. Write a C++ program to compare two strings using string functions.
#include<iostream.h>
#include<string.h>
using namespace std;
int main ()
{
char str1[50], str2[50];
cout<<"Enter string 1 : ";
gets(str1);
cout<<"Enter string 2 : ";
gets(str2);
if(strcmp(str1, str2)==0)
cout << "Strings are equal!";
else
cout << "Strings are not equal.";
return 0;
}
6
11. Write a C++ program to find the GCD of two numbers.
#include <iostream>
using namespace std;
int main()
{
int n1, n2;
cout << "Enter two numbers: ";
cin >> n1 >> n2;
while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
cout << "HCF = " << n1;
return 0;
}
12. Write a C++ program to calculate the area of rectangle, square using function
overloading.
#include<iostream.h>
#include<conio.h>
class over
{
float l,b,r,area;
public:
void volume(float,float);
void volume(float);
};
void over::volume(float l, float b)
{
cout<<"Area of rectangle = "<<l*b;
void over::volume(float r)
{
cout<<"Area of circle = "<<3.14*r*r;
}
void main()
{
over o;
clrscre():
float r,l,b;
cout<<"\nEnter radius: ";
cin>>r;
o.volume(r);
cout<<"\n\nEnter lenght and breadth: ";
cin>>l>>b;
o.volume(l,b);
getch();
}
7
13. Write a C++ program to add two numbers using pointers.
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
p = &first;
q = &second;
sum = *p + *q;
return 0;
}
8
15. Write a C++ program to search for an element using binary search.
#include <iostream>
using namespace std;
int main()
{
int count, i, arr[30], num, first, last, middle;
cout<<"how many elements would you like to enter?:";
cin>>count;
}
else if(arr[middle] == num)
{
cout<<num<<" found in the array at the location "<<middle+1<<"\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<num<<" not found in the array";
}
return 0;
}
9
16. Write a C++ program to sort an array in ascending order.
#include <iostream>
using namespace std;
int main()
{
int arr[100];
int size, i, j, temp;
return 0;
}
10
17. Write a C++ program to find the factorial of a given number using recursion.
#include <iostream>
using namespace std;
int fact(int n) {
if ((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main() {
int n = 4;
cout<<"Factorial of "<<n<<" is "<<fact(n);
return 0;
}
18. Write a C++ program to check whether a given number is even or odd.
#include<iostream>
using namespace std;
int main()
{
int number, remainder;
return 0;
}
return 0;
}
11
20. Write a C++ program to demonstrate parameter passing mechanism using pass
by value method.
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
using std::cout;
using std::endl;
void addToInt(int);
int main()
{
int num = 5;
cout << "In main(), value of num is " << num << endl << endl;
addToInt(num);
cout << "In main(), value of num is now " << num << endl << endl;
return 0;
}
num += 10;
cout << "In addToInt(), value of num is now " << num << endl << endl;
}
12
22. Write a C++ program to demonstrate the usage of a constructor and destructor in
a class.
#include <iostream.h>
#include<conio.h>
class MyClass
{
public:
int x;
MyClass(); // constructor
~MyClass(); // destructor
};
// Implement MyClassconstructor.
MyClass::MyClass()
{
x = 10;
}
// Implement MyClass destructor.
MyClass::~MyClass()
{
cout<< "Destructing ...\n";
}
void main()
{
clrscr();
MyClass ob1;
MyClass ob2;
cout <<ob1.x<< " " <<ob2.x<<"\n";
getch();
}
class emp {
public:
int eno;
char name[20], des[20];
void get() {
cout << "Enter the employee number:";
cin>>eno;
cout << "Enter the employee name:";
cin>>name;
cout << "Enter the designation:";
cin>>des;
}
};
void get1() {
cout << "Enter the basic pay:";
cin>>bp;
cout << "Enter the Humen Resource Allowance:";
cin>>hra;
cout << "Enter the Dearness Allowance :";
cin>>da;
cout << "Enter the Profitablity Fund:";
cin>>pf;
}
void calculate() {
np = bp + hra + da - pf;
}
void display() {
cout << eno << "\t" << name << "\t" << des << "\t" << bp << "\t" << hra << "\
t" << da << "\t" << pf << "\t" << np << "\n";
}
};
void main() {
int i, n;
char ch;
salary s[10];
clrscr();
cout << "Enter the number of employee:";
cin>>n;
for (i = 0; i < n; i++) {
s[i].get();
s[i].get1();
s[i].calculate();
}
cout << "\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for (i = 0; i < n; i++) {
s[i].display();
}
getch();
}
14
24. Write a C++ program to calculate volume of cube, cylinder and rectangle
using function overloading. 25. Write a C++ program to demonstrate the
usage of friend function in a class
#include<iostream.h>
using namespace std;
float vol(int,int);
float vol(float);
int vol(int);
int main()
{
int r,h,a;
float r1;
cout<<"Enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"Enter side of cube:";
cin>>a;
cout<<"Enter radius of sphere:";
cin>>r1;
cout<<"Volume of cylinder is"<<vol(r,h);
cout<<"\nVolume of cube is"<<vol(a);
cout<<"\nVolume of sphere is"<<vol(r1);
return 0;
}
float vol(int r,int h)
{
return(3.14*r*r*h);
}
float vol(float r1)
{
return((4*3.14*r1*r1*r1)/3);
}
int vol(int a)
{
return(a*a*a);
}
25. Write a C++ program to demonstrate the usage of endl and stew
manipulators.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int num;
cout<<"Enter your roll number: ";
cin>>num;
cout<<"Hello roll number "<<num<<endl;
cout<<"Welcome to your new class!!";
getch();
return 0;
}
15
26. Write a C++ program to display employee information using multiple
inheritance.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
//create object of class employee
employee emp;
emp.getEmployeeInfo();
emp.printEmployeeInfo();
return 0;
}
17
27. Write a C++ program to display employee information using multiple
inheritance.
#include<iostream>
using namespace std;
class person {
string name, gender;
int age;
public:
person(string desig) {
cout << "Enter details a " << desig << endl;
cout << "Name:" << endl;
cin >> name;
cout << "Age:" << endl;
cin >> age;
cout << "Gender:" << endl;
cin >> gender;
}
class employee {
int emp_id;
float salary;
string designation;
public:
employee() {
cout << "Employee Id:" << endl;
cin >> emp_id;
cout << "Salary:" << endl;
cin >> salary;
}
void display() {
cout << "Employee Id: " << emp_id << endl;
18
cout << "Salary: " << salary << endl;
cout << "Designation: " << designation << endl;
cout << "\n<------------------------------>\n" << endl;
}
};
public:
public:
19
/* Call two constructor "person" & "employee" */
service_man() : person("Service Man"), employee() {
string desig;
cout << "Designation:" << endl;
cin >> desig;
get_designation(desig);
cout << "\n<------------------------------>\n" << endl;
}
inline void display() {
/* Call display() from class 'person' */
person :: display("Service Man");
/* Call display() from class 'employee' */
employee :: display();
}
};
int main() {
scientist s1 = scientist();
programmer p1 = programmer();
service_man sm1 = service_man();
int main()
{
fstream file; //object of fstream class
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
return 0;
}
30. Write a C++ program to check whether a given number is a palindrome or not.
#include<iostream>
using namespace std;
void palindrome(int num) {
int rev=0,val;
val = num;
while(num > 0) {
rev = rev * 10 + num % 10;
num = num / 10;
}
if(val==rev)
cout<<val<<" is a palindrome"<<endl;
else
cout<<val<<" is not a palindrome"<<endl;
}
int main() {
palindrome(12321);
palindrome(1234);
return 0;
}
21
31. Write a C++ program to generate the Fibonacci series using while loop.
#include<stdio.h>
#include<conio.h>
main()
{
int f1=0,f2=1,f3,i=3,len;
printf("enter length of the fibonacci series:");
scanf("%d",&len);
printf("%d\t%d",f1,f2); // It prints the starting two values
while(i<=len) // checks the condition
{
f3=f1+f2; // performs add operation on previous two values
printf("\t%d",f3); // It prints from third value to given length
f1=f2;
f2=f3;
i=i+1; // incrementing the i value by 1
}
getch();
}
32. Write a C++ program to overload + operator to add two complex numbers.
#include<iostream.h>
#include<conio.h<
Class sample
{
Private:
Int x, y;
Public:
Void getdata ()
{
Cout<<”\n Enter value of x and y of complex number”;
Cin>>x>>y;
}
Sample operator + (sample obj)
{
Obj.y = x+obj.x;
Obj.y =y +obj.y;
Return (obj);
}
Void display ()
{
Cout<<”\n Additional of two complex numbers”;
Cout<<x<<”+I”<<y;
}
};
Void main ()
{
Sample obj1, obj2, obj3;
Obj1. Getdata ();
Obj2.getdat ();
Obj3=obj1+obj2;
22
Obj3.display ();
getch ();
}
33. Write a C++ program to search for a given element in an array using linear
search.
#include <stdio.h>
int main()
{
int array[100], search, c, n;
return 0;
}
23
34. Write a C++ program to read a text file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ch;
const char *fileName="test.txt";
//declare object
ifstream file;
//open file
file.open(fileName,ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return -1; //return from main
}
return 0;
}
35. Write a C++ program to find the sum of natural numbers using for loop.
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
24
36. Write a C++ program to create a simple class named Account and write methods
to deposit and withdraw amount from the account.
#include<iostream>
using namespace std;
class Account
{
int acc_no;
int balance;
int wdraw;
public:
Account()
{
acc_no = 123;
balance = 0;
wdraw = 0;
}
if(num == acc_no)
{
cout<<"\nI am depositing money...";
cout<<"\nEnter the amount you want to deposit : ";
cin>>balance;
}
else
cout<<"\nIncorrect account number.";
else
cout<<"\nIncorrect account number.";
}
};
int main()
{
Account acc;
int num;
cout<<"\nENter the account number : ";
cin>>num;
acc.deposit(num);
acc.display(num);
acc.withdraw(num);
cout<<endl;
return 0;
}
int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable
return 0;
}
26
38. Write a C++ program to demonstrate polymorphism by calculating area of
rectangle and triangle using a shape class.
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
27
// store the address of Triangle
shape = &tri;
return 0;
}
39. Write a C++ program using Switch case to add, subtract, multiply and divide two
numbers.
# include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}
28
40. Write a C++ program using class to implement basic operations on a stack using
arrays.
#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
29
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}
41. Write a C++ program to display the sizes of various data types in c++ language.
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
return 0;
}
42. Write a C++ program to accept and display employee details using structures.
#include <iostream>
using namespace std;
struct Employee {
char name[50];
int salary;
int employeeCode;
char dept[5];
};
int main() {
Employee e;
43. Write a C++ program to find the length of a given string using string functions.
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50];
int len;
cout << "Enter an array or string : ";
gets(str);
len = strlen(str);
cout << "Length of the string is : " << len;
return 0;
}
44. Write a C++ program to print the ASCII value of a user entered character.
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
}
31
45. Write a C++ program to add two dimensional matrices.
#include<iostream>
main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of rows and columns of matrix ";
cin >> m >> n;
cout << "Enter the elements of first matrix\n";
return 0;
}
32
46. Write a C++ program to overload + (plus) operator to perform concatenation of
two strings.
#include<conio.h>
#include<string.h>
#include<iostream.h>
class string {
public:
char *s;
int size;
void getstring(char *str)
{
size = strlen(str);
s = new char[size];
strcpy(s,str);
}
void operator+(string);
};
void main()
{
string ob1, ob2;
char *string1, *string2;
clrscr();
ob1.getstring(string1);
ob2.getstring(string2);
33
47. Write a C++ program to find the sum of elements in a given array.
#include<iostream>
using namespace std;
int main ()
{
int arr[10], n, i, sum = 0, pro = 1;
cout << "Enter the size of the array : ";
cin >> n;
cout << "\nEnter the elements of the array : ";
for (i = 0; i < n; i++)
cin >> arr[i];
for (i = 0; i < n; i++)
{
sum += arr[i];
pro *= arr[i];
}
cout << "\nSum of array elements : " << sum;
cout << "\nProduct of array elements : " << pro;
return 0;
}
void main()
{
int num1, num2, num3;
34
49. Write a C++ program to demonstrate exception handling by dividing a number
with zero.
#include<iostream.h>
#include<conio.h>
void main() {
int a, b, c;
float d;
clrscr();
cout << "Enter the value of a:";
cin>>a;
cout << "Enter the value of b:";
cin>>b;
cout << "Enter the value of c:";
cin>>c;
try {
if ((a - b) != 0) {
d = c / (a - b);
cout << "Result is:" << d;
} else {
throw (a - b);
}
} catch (int i) {
cout << "Answer is infinite because a-b is:" << i;
}
getch();
}