0% found this document useful (0 votes)
109 views58 pages

C++ Record For II-IV Sem 123

practical record

Uploaded by

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

C++ Record For II-IV Sem 123

practical record

Uploaded by

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

1.

C++ Program to Reverse an Integer


#include <iostream>
using namespace std;
int main()
{
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Output
Enter an integer: 12345
Reversed number = 54321

2. Adding two number using class (C++)

#include<iostream.h>
#include<conio.h>
class add
{
private:
int a,b,c;
public:
void read()
{
cout<<"enter Two Number "<<endl;
cin>>a>>b;
}
void display()
{
cout<<" A = "<<a<<endl;
cout<<" B = "<<b<<endl;
cout<<"Sum = "<<c<<endl;
}
void sum()
{
c= a+b;
}
};
void main()
{
add x; // x is a object off add
clrscr();
x.read();
x.sum();
x.display();
getch();
}

2. C++ addition program using class


#include <iostream>

using namespace std;

class Mathematics {
int x, y;

public:
void input() {
cout << "Input two integers\n";
cin >> x >> y;
}

void add() {
cout << "Result: " << x + y;
}

};

int main()
{
Mathematics m; // Creating an object of the class

m.input();
m.add();

return 0;
}

3 . Check whether number is prime number or not


To understand this program you should have the knowledge of for loop, if-else, break
statement in C++.
#include <iostream>
using namespace std;
int main(){
int num;
bool flag = true;
cout<<"Enter any number(should be positive integer): ";
cin>>num;

for(int i = 2; i <= num / 2; i++) {


if(num % i == 0) {
flag = false;
break;
}
}
if (flag==true)
cout<<num<<" is a prime number";
else
cout<<num<<" is not a prime number";
return 0;
}
Output:
Enter any number(should be positive integer): 149
149 is a prime number

4. Scope resolution operator in class


#include <iostream>
using namespace std;

class programming {
public:
void output(); //function declaration
};

// function definition outside the class

void programming::output() {
cout << "Function defined outside the class.\n";
}

int main() {
programming x;
x.output();

return 0;
}
Output of program:

5. Check if a year is leap year or not


#include <iostream>
using namespace std;

int main()
{
int year;

cout << "Enter a year: ";


cin >> 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;
}
Output
Enter a year: 2014
2014 is not a leap year.

6. Program to add two numbers using function in C++


#include <iostream>
using namespace std;

//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
add=addition(num1,num2);

//print addition
cout<<"Addition is: "<<add<<endl;

return 0;
}

//function definition
int addition(int a,int b)
{
return (a+b);
}
Output
Enter first number: 100
Enter second number: 200
Addition is: 300

7. C++ program to display student information using class


BY BIKASH CHANDRA PRUSTY · SEPTEMBER 20, 2015

1 #include<iostream>
2 using namespace std;
3 class student
4 {
5 private:
6
7 char
8 name[20],regd[10],branch[10];
9 int sem;
1 public:
0 void input();
1 void display();
1
1
2 };
1 void student::input()
3 {
1 cout<<"Enter Name:";
4 cin>>name;
1 cout<<"Enter Regdno.:";
5 cin>>regd;
1 cout<<"Enter Branch:";
6 cin>>branch;
1 cout<<"Enter Sem:";
7 cin>>sem;
1 }
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5 void student::display()
2 {
6 cout<<"\nName:"<<name;
2 cout<<"\nRegdno.:"<<regd;
7 cout<<"\nBranch:"<<branch;
2 cout<<"\nSem:"<<sem;
8 }
2 int main()
9 {
3 student s;
0 s.input();
3 s.display();
1 }
3
2
3
3
3
4
3
5
3
6
3
7
3
8

Sample Input
Enter Name:Bikash
Enter Regdno.:123
Enter Branch:CS
Enter Sem:5
Sample Output
Name:Bikash
Regdno.:123
Branch:CS
Sem:5

8. C++ Program For Store Book Details Using Structure


Solution:-

#include<iostream>
#include<iomanip>
using namespace std;

struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};

int main()
{
int i, n;

/*Visit www.programmingwithbasics.com*/

cout<<"\nEnter The Number of Employee\n\n";


cin>>n;

Employee Emp[n]; // Structure object created emp

for(i=0;i<n;i++)
{

cout << "\nEnter details of " << i+1 << " Employee"<<endl;

cout <<setw(5)<< "\nEnter Employee Id : ";


cin >> Emp[i].Id;
cout <<setw(5)<< "\nEnter Employee Name : ";
cin >> Emp[i].Name;

cout <<setw(5)<< "\nEnter Employee Age : ";


cin >> Emp[i].Age;

cout <<setw(5)<< "\nEnter Employee Salary : ";


cin >> Emp[i].Salary;

cout<<"\n\n------------------------------------------------------------\n";
cout << "Details of Employees";
cout<<"\n------------------------------------------------------------\n\n";

cout << "ID" <<setw(15)<<"Name" <<setw(10)<<"Age"


<<setw(10)<<"Salary";
cout<<endl;
for(i=0;i<n;i++)
{

cout << "\n"<< Emp[i].Id <<setw(15)<< Emp[i].Name <<setw(10)<<


Emp[i].Age <<setw(10)<< Emp[i].Salary;
}
cout<<"\n\n------------------------------------------------------------\n";

Output:-
9.

Write a C++ program to count the lines, words and characters in a given text.

#include(iostream.h)
#include(conio.h)
#include(stdio.h)
void main( )
{
char ch;
int sp=0, ct=0, line=0;
clrscr( );
cout<<"Enter the required lines of text:";
while((ch=getchar())!=EOF)
{
ct++;
if((ch==' ')
sp++;
if(ch=='\n')
line++;
}
cout<<"Total Lines:"<< line;
cout<<"Total words:"<< sp+line;
cout<<"Total Characters:"<< ct;
getch( );
}

Output:- Enter the required lines of text:


Where are you
Come fast
^z

Total Lines: 2
Total words: 5

10. Write a C++ program to compare two strings using string functions.

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char str1[100], str2[100];
cout<<"\n Enter First String : ";
gets(str1);
cout<<"\n Enter Second String : ";
gets(str2);
if(strcmp(str1, str2)==0) //strcmp() is a library function, used to
compare the two strings.
{
cout<<"\n Strings are Equal!!!";
}
else
{
cout<<"\n Strings are Not Equal!!!";
}
return 0;
}

Output:

11.

Write a C++ program to find the GCD of two numbers

Find GCD using while loop


#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;
}
Output
Enter two numbers: 78
52
HCF = 26

12. Write a C++ program to calculate the area of rectangle, square using function overloading
#include<iostream>
#include<cstdlib>
using namespace std;

float area(float r)
{
return(3.14 * r * r);
}
float area(float b,float h)
{
return(0.5 * b * h);
}
float area(float l,float b)
{
return (l * b);
}
int main()
{
float b,h,r,l;
int ch;

do
{
cout<<"\n\n *****Menu***** \n";
cout<<"\n 1. Area of Circle";
cout<<"\n 2. Area of Triangle";
cout<<"\n 3. Area of Rectangle";
cout<<"\n 4. Exit";
cout<<"\n\n Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"\n Enter the Radius of Circle : ";
cin>>r;
cout<<"\n Area of Circle : "<<area(r);
break;
}
case 2:
{
cout<<"\n Enter the Base & Height of Triangle : ";
cin>>b>>h;
cout<<"\n Area of Triangle : "<<area(b,h);
break;
}
case 3:
{
cout<<"\n Enter the Length & Bredth of Rectangle : ";
cin>>l>>b;
cout<<"\n Area of Rectangle : "<<area(l,b);
break;
}
case 4:
exit(0);
default:
cout<<"\n Invalid Choice... ";
}
}while(ch!=4);
return 0;
}

Output:

1. Area of Circle

2. Area of Triangle
3. Area of Rectangle

13.

Write a C++ program to add two numbers using pointers

1. /ADDITION OF TWO NUMBERS USING POINTERS


2.
3. #include<iostream.h>
4. #include<conio.h>
5. void main()
6. {
7. int f,s,*p,*q,sum;
8. cout<<"Enter two integers to add\n";
9. cin>>f>>s;
10. p= &f;
11. q=&s;
12. sum= *p + *q;
13. cout<<"Sum of 2 numbers="<< sum;
14. getch();
15. }

14.

Write a C++ program to find the factorial of a given number.


Example: Find Factorial of a given number
#include <iostream>
using namespace std;

int main()
{
unsigned int n;
unsigned long long factorial = 1;

cout << "Enter a positive integer: ";


cin >> n;
for(int i = 1; i <=n; ++i)
{
factorial *= i;
}

cout << "Factorial of " << n << " = " << factorial;
return 0;
}
Output
Enter a positive integer: 12
Factorial of 12 = 479001600

15.Write a C++ program to search for an element using binary search


/* C++ Program - Binary Search */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, arr[50], search, first, last, middle;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" number :";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;

}
else if(arr[middle] == search)
{
cout<<search<<" found at location
"<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the
list.";
}
getch();
}
When the above C++ program is compile and executed, it will produce the following
result. Above C++ Programming Example Output (Element found):

Above C++ Programming Example Output (Element Not found):

16. Write a C++ program to sort an array in ascending order


C++ Program to Sort Elements of Array in Ascending Order

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

void main()
{
int i,a[10],temp,j;
clrscr();
cout<<"Enter any 10 num in array: \n";
for(i=0;i<=10;i++)
{
cin>>a[i];
}
cout<<"\nData before sorting: ";
for(j=0;j<10;j++)
{
cout<<a[j];
}
for(i=0;i<=10;i++)
{
for(j=0;j<=10-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
cout<<"\nData after sorting: ";
for(j=0;j<10;j++)
{
cout<<a[j];
}
getch();
}

Download Code
Output

Enter any 10 num in array:


2 5 1 7 5 3 8 9 11 4
Data After Sorting: 1 2 3 4 5 7 8 9 11

Output
17. Write a C++ program to find the factorial of a given number using recursion
Calculate Factorial Using Recursion
#include<iostream>
using namespace std;

int factorial(int n);

int main()
{
int n;

cout << "Enter a positive integer: ";


cin >> n;

cout << "Factorial of " << n << " = " << factorial(n);

return 0;
}

int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
Output
Enter an positive integer: 6
Factorial of 6 = 720
18. Write a C++ program to check whether a given number is even or odd.
Example 1: Check Whether Number is Even or Odd using if else
#include <iostream>
using namespace std;

int main()
{
int n;

cout << "Enter an integer: ";


cin >> n;

if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";

return 0;
}
Output
Enter an integer: 23
23 is odd.

19. Write a C++ program to demonstrate the usage of Inline function.

#include <iostream>
using namespace std;
class operation
{
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation :: get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}

inline void operation :: sum()


{
add = a+b;
cout << "Addition of two numbers: " << a+b
<< "\n";
}

inline void operation :: difference()


{
sub = a-b;
cout << "Difference of two numbers: " << a-
b << "\n";
}

inline void operation :: product()


{
mul = a*b;
cout << "Product of two numbers: " << a*b
<< "\n";
}

inline void operation ::division()


{
div=a/b;
cout<<"Division of two numbers: "<<a/b<<"\
n" ;
}

int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
Run on IDE
Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3

20. Write a C++ program to demonstrate parameter passing mechanism using pass by value
method.
Passing by Pointer:
// C++ program to swap two numbers using
// pass by pointer.
#include <iostream>
using namespace std;

void swap(int* x, int* y)


{
int z = *x;
*x = *y;
*y = z;
}

int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\
n";

swap(&a, &b);

cout << "After Swap with pass by pointer\


n";
cout << "a = " << a << " b = " << b << "\
n";
}
Run on IDE
Output:
Before Swap
a = 45 b = 35
After Swap with pass by pointer
a = 35 b = 45
Passing by Reference:
// C++ program to swap two numbers using
// pass by reference.

#include <iostream>
using namespace std;
void swap(int& x, int& y)
{
int z = x;
x = y;
y = z;
}

int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\
n";
swap(a, b);

cout << "After Swap with pass by


reference\n";
cout << "a = " << a << " b = " << b << "\
n";
}
Run on IDE
Output:

Before Swap
a = 45 b = 35
After Swap with pass by reference
a = 35 b = 45

21. Write a C++ program to demonstrate parameter passing mechanism using pass by address
method.

C Program to swap two numbers using pass by reference


#include<stdio.h>
#include<conio.h>

void swap(int *num1, int *num2);

void main() {
int x, y;

printf("\nEnter First number : ");


scanf("%d", &x);

printf("\nEnter Second number : ");


scanf("%d", &y);

printf("\nBefore Swaping x = %d and y = %d", x, y);


swap(&x, &y); // Function Call - Pass By Reference

printf("\nAfter Swaping x = %d and y = %d", x, y);


getch();
}

void swap(int *num1, int *num2) {


int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;
}
Output :
Enter First number : 12
Enter Second number : 21

Before Swaping x = 12 and y = 21


After Swaping x = 21 and y = 12

22. Write a C++ program to demonstrate the usage of a constructor and destructor in a class.

Types of Constructors
1. Default Constructors: Default constructor is the constructor which
doesn’t take any argument. It has no parameters.
// Cpp program to illustrate the
// concept of Constructors
#include <iostream>
using namespace std;

class construct
{
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called
automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<<
c.b;
return 1;
}
2. Run on IDE
3. Output:
4.

5. a: 10
6. b: 20

Destructors don’t take any argument and don’t return anything


class String
{
private:
char *s;
int size;
public:
String(char *); // constructor
~String(); // destructor
};

String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}

String::~String()
{
delete []s;
}

23. Write a C++ program to demonstrate simple inheritance.

#include<iostream>
#include<conio.h>
using namespace std;

class staff
{
private:
char name[50];
int code;
public:
void getdata();
void display();
};

class typist: public staff


{
private:
int speed;
public:
void getdata();
void display();
};

void staff::getdata()
{
cout<<"Name:";
gets(name);
cout<<"Code:";
cin>>code;
}
void staff::display()
{
cout<<"Name:"<<name<<endl;
cout<<"Code:"<<code<<endl;
}

void typist::getdata()
{
cout<<"Speed:";
cin>>speed;
}

void typist::display()
{
cout<<"Speed:"<<speed<<endl;
}

int main()
{
typist t;
cout<<"Enter data"<<endl;
t.staff::getdata();
t.getdata();
cout<<endl<<"Display data"<<endl;
t.staff::display();
t.display();
getch();
return 0;
}

24. Write a C++ program to calculate volume of cube, cylinder and rectangle using function
overloading

C++ program to find volume of cube, cylinder, sphere by function overloading


BY BIKASH CHANDRA PRUSTY · SEPTEMBER 22, 2015

1 #include<iostream>
2 using namespace std;
3 float vol(int,int);
4 float vol(float);
5 int vol(int);
6
7 int main()
8 {
9 int r,h,a;
1 float r1;
0 cout<<"Enter radius and height of a
1 cylinder:";
1 cin>>r>>h;
1 cout<<"Enter side of cube:";
2 cin>>a;
1 cout<<"Enter radius of sphere:";
3 cin>>r1;
1 cout<<"Volume of cylinder is"<<vol(r,h);
4 cout<<"\nVolume of cube is"<<vol(a);
1 cout<<"\nVolume of sphere is"<<vol(r1);
5 return 0;
1 }
6 float vol(int r,int h)
1 {
7 return(3.14*r*r*h);
1 }
8 float vol(float r1)
1 {
9 return((4*3.14*r1*r1*r1)/3);
2 }
0 int vol(int a)
2 {
1 return(a*a*a);
2 }
2
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
3
3

Sample Input
Enter radius and height of a cylinder:8 12
Enter side of cube:2
Enter radius of sphere:3
Sample Output
Volume of cylinder is2411.52
Volume of cube is8
Volume of sphere is113.04

25. Write a C++ program to demonstrate the usage of friend function in a class.

Working of friend Function


/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;

class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};

// friend function definition


int addFive(Distance d)
{
//accessing private data from non-member function
d.meter += 5;
return d.meter;
}

int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}

Output
Distance: 5

26. Write a C++ program to demonstrate the usage of endl and setw manipulators.

#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"USING setw() ..............\n";
cout<< setw(10) <<11<<endl;
cout<< setw(10) <<2222<<endl;
cout<< setw(10) <<33333<<endl;
cout<< setw(10) <<4<<endl;

cout<<"USING setw() & setfill() [type- I]...\n";


cout<< setfill('0');
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type-II]...\n";


cout<< setfill('-')<< setw(10) <<11<<"\n";
cout<< setfill('*')<< setw(10) <<2222<<"\n";
cout<< setfill('@')<< setw(10) <<33333<<"\n";
cout<< setfill('#')<< setw(10) <<4<<"\n";
return 0;
}
Output
USING setw() ..............
11
2222
33333
4
USING setw() & setfill() [type- I]...
0000000011
0000002222
0000033333
0000000004
USING setw() & setfill() [type-II]...
--------11
******2222
@@@@@33333
#########4

27. Write a C++ program to display employee information using multiple inheritance

Multiple inheritance program in C++.


/* C++ program to read and print employee information using
multiple inheritance.*/

#include <iostream>
#include <stdio.h>
using namespace std;

//Base Class - basicInfo


class basicInfo
{
protected:
char name[30];
int empId;
char gender;
public:
void getBasicInfo(void)
{
cout << "Enter Name: ";
cin.getline(name,30);
cout << "Enter Emp. Id: ";
cin >> empId;
cout << "Enter Gender: ";
cin >> gender;
}
};

//Base Class - deptInfo


class deptInfo
{
protected:
char deptName[30];
char assignedWork[30];
int time2complete;
public:
void getDeptInfo(void)
{
cout << "Enter Department Name: ";
cin.ignore(1);
cin.getline(deptName,30);
cout << "Enter assigned work: ";
fflush(stdin);
cin.getline(assignedWork,30);
cout << "Enter time in hours to complete work: ";
cin >> time2complete;
}
};

/*final class (Derived Class)- employee*/


class employee:private basicInfo, private deptInfo
{
public:
void getEmployeeInfo(void){
cout << "Enter employee's basic info: " << endl;
//call getBasicInfo() of class basicInfo
getBasicInfo(); //calling of public member
function
cout << "Enter employee's department info: " << endl;
//call getDeptInfo() of class deptInfo
getDeptInfo(); //calling of public member
function
}
void printEmployeeInfo(void)
{
cout << "Employee's Information is: " << endl;
cout << "Basic Information...:" << endl;
cout << "Name: " << name << endl;
//accessing protected data
cout << "Employee ID: " << empId << endl;
//accessing protected data
cout << "Gender: " << gender << endl <<
endl;//accessing protected data

cout << "Department Information...:" << endl;


cout << "Department Name: " << deptName
<< endl; //accessing protected data
cout << "Assigned Work: " << assignedWork
<< endl; //accessing protected data
cout << "Time to complete work: " <<
time2complete<< endl; //accessing protected data
}
};

int main()
{
//create object of class employee
employee emp;

emp.getEmployeeInfo();
emp.printEmployeeInfo();

return 0;
}
Output
Enter employee's basic info:
Enter Name: Mickey
Enter Emp. Id: 1121
Enter Gender: F
Enter employee's department info:
Enter Department Name: Testing
Enter assigned work: Test Game OEM
Enter time in hours to complete work: 70
Employee's Information is:
Basic Information...:
Name: Mickey
Employee ID: 1121
Gender: F
Department Information...:
Department Name: Testing
Assigned Work: Test Game OEM
Time to complete work: 70

28. Write a C++ program to demonstrate multilevel inheritance.

#include<iostream>
#include<conio.h>
class Father
{
protected:
int a;
public:
Father()
{
a = 5;
};
};
class Son : public Father
{
protected:
int b;
public:
Son() : Father()
{
b = 9;
};
};
class GrandSon : public Son
{
protected:
int c;
public:
GrandSon() :Son()
{
c = 0;
c = a + b;
}
void Show()
{
std::cout << " a + b = " << c<<"\n"<<"\n"<<"\n";
}
};
main()
{
GrandSon obj;
obj.Show();
getch();
}
29. Write a C++ program to create a file.

Creating a file using file stream.


//C++ program to create a file.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}

cout<<"File created successfully.";

//closing the file


file.close();

return 0;
}
Output
File created successfully.

30. Write a C++ program to check whether a given number is a palindrome or not.

Check Palindrome Number


#include <iostream>
using namespace std;

int main()
{
int n, num, digit, rev = 0;

cout << "Enter a positive number: ";


cin >> num;

n = num;
do
{
digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10;
} while (num != 0);

cout << " The reverse of the number is: " << rev << endl;

if (n == rev)
cout << " The number is a palindrome";
else
cout << " The number is not a palindrome";

return 0;
}
Output
Enter a positive number: 12321
The reverse of the number is: 12321
The number is a palindrome

Enter a positive number: 12331


The reverse of the number is: 13321
The number is not a palindrome

31. Write a C++ program to generate the Fibonacci series using while loop.

Fibonacci Series up to n number of terms


#include <iostream>
using namespace std;

int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter the number of terms: ";


cin >> n;

cout << "Fibonacci Series: ";

for (int i = 1; i <= n; ++i)


{
// Prints the first two terms.
if(i == 1)
{
cout << " " << t1;
continue;
}
if(i == 2)
{
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;

cout << nextTerm << " ";


}
return 0;
}
Output
Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

32. Write a C++ program to overload + operator to add two complex numbers.

C++ program to add two complex number by using the concept of operator overloading using
member function

1 #include<iostream>
2 using namespace std;
3
4 class A
5 {
6 int a,b;
7 public:
8 A(){};
9 A(int i,int j)
1 {
0 a=i;
1 b=j;
1
1 }
2 void show()
1 {
3 cout<<a<<"+i"<<b;
1 }
4 A operator +(A);
1 };
5 A A::operator +(A obj)
1 {
6 A temp;
1 temp.a=a+obj.a;
7 temp.b=b+obj.b;
1 return(temp);
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
}
2
int main()
6
{
2
A c1(5,6),c2(7,8),c3;
7
cout<<"The 1st no. is:";
2
c1.show();
8
cout<<"\nThe 2nd no. is:";
2
c2.show();
9
c3=c1+c2;
3
cout<<"\nSum is:";
0
c3.show();
3
}
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8

Sample Output
The 1st no. is:5+i6
The 2nd no. is:7+i8
Sum is:12+i14

33. Write a C++ program to search for a given element in an array using linear search.

Linear Search in C++ Program Example Code

#include<iostream>
using namespace std;

int main() {
cout<<"Enter The Size Of Array: ";
int size;
cin>>size;

int array[size], key,i;

// Taking Input In Array


for(int j=0;j<size;j++){
cout<<"Enter "<<j<<" Element: ";
cin>>array[j];
}

//Your Entered Array Is


for(int a=0;a<size;a++){
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}

cout<<"Enter Key To Search in Array";


cin>>key;

for(i=0;i<size;i++){
if(key==array[i]){
cout<<"Key Found At Index Number : "<<i<<endl;
break;
}
}

if(i != size){
cout<<"KEY FOUND at index : "<<i;
}
else{
cout<<"KEY NOT FOUND in Array ";
}
return 0;
}

Sample Output:

What is Linear Search In C++ Code Example


Sample Output

34. Write a C++ program to read a text file.

Read/Write Class Objects from/to File in C++


Given a file “Input.txt” in which every line has values same as instance
variables of a class.
Read the values into the class’s object and do necessary operations.
Theory :
The data transfer is usually done using '>>'
and <<' operators. But if you have
a class with 4 data members and want
to write all 4 data members from its
object directly to a file or vice-versa,
we can do that using following syntax :

To write object's data members in a file :


// Here file_obj is an object of ofstream
file_obj.write((char *) & class_obj, sizeof(class_obj));

To read file's data members into an object :


// Here file_obj is an object of ifstream
file_obj.read((char *) & class_obj, sizeof(class_obj));
Examples:
Input :
Input.txt :
Micheal 19 1806
Kemp 24 2114
Terry 21 2400
Operation : Print the name of the highest
rated programmer.

Output :
Terry
// C++ program to demonstrate read/write of
class
// objects in C++.
#include <iostream>
#include <fstream>
using namespace std;

// Class to define the properties


class Contestant {
public:
// Instance variables
string Name;
int Age, Ratings;

// Function declaration of input() to


input info
int input();

// Function declaration of
output_highest_rated() to
// extract info from file Data Base
int output_highest_rated();
};

// Function definition of input() to input


info
int Contestant::input()
{
// Object to write in file
ofstream file_obj;

// Opening file in append mode


file_obj.open("Input.txt", ios::app);

// Object of class contestant to input


data in file
Contestant obj;
// Feeding appropriate data in variables
string str = "Micheal";
int age = 18, ratings = 2500;

// Assigning data into object


obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;

// Writing the object's data in file


file_obj.write((char*)&obj, sizeof(obj));

// Feeding appropriate data in variables


str = "Terry";
age = 21;
ratings = 3200;

// Assigning data into object


obj.Name = str;
obj.Age = age;
obj.Ratings = ratings;

// Writing the object's data in file


file_obj.write((char*)&obj, sizeof(obj));

return 0;
}

// Function definition of
output_highest_rated() to
// extract info from file Data Base
int Contestant::output_highest_rated()
{
// Object to read from file
ifstream file_obj;

// Opening file in input mode


file_obj.open("Input.txt", ios::in);

// Object of class contestant to input


data in file
Contestant obj;

// Reading from file into object "obj"


file_obj.read((char*)&obj, sizeof(obj));

// max to store maximum ratings


int max = 0;

// Highest_rated stores the name of


highest rated contestant
string Highest_rated;

// Checking till we have the feed


while (!file_obj.eof()) {
// Assigning max ratings
if (obj.Ratings > max) {
max = obj.Ratings;
Highest_rated = obj.Name;
}

// Checking further
file_obj.read((char*)&obj,
sizeof(obj));
}

// Output is the highest rated contestant


cout << Highest_rated;
return 0;
}

// Driver code
int main()
{
// Creating object of the class
Contestant object;

// Inputting the data


object.input();

// Extracting the max rated contestant


object.output_highest_rated();

return 0;
}
Run on IDE
Output:
Terry

35. Write a C++ program to find the sum of natural numbers using for loop

Sum of Natural Numbers using loop


#include <iostream>
using namespace std;

int main()
{
int n, sum = 0;

cout << "Enter a positive integer: ";


cin >> n;

for (int i = 1; i <= n; ++i) {


sum += i;
}

cout << "Sum = " << sum;


return 0;
}
Output
Enter a positive integer: 50
Sum = 1275

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>
#include <string>
using namespace std;

class Account{
private:
string firstname;
string lastname;
string FullName;
int accountnumber;
double balance;
public:
Account(){
firstname = "Raaj";
lastname = "Lokanathan";
FullName = "Raaj Lokanathan";
accountnumber = 5671;
balance = 0.0;
}
Account(string fName,string lName,int accno,double
bal);
void setFullName(string fullname);
void setaccountnumber(int accno);
void setbalance(double bal);
void setwithdraw(int wdraw);
void setdeposit(int dep);
string getFullName();
int getaccountnumber();
double getbalance();
void display();

};

Account::Account(string fName,string lName,int accno,double bal){


firstname = fName;
lastname = lName;
accountnumber = accno;
balance = bal;
}

void Account::setFullName(string fullname){


FullName = fullname;
}

void Account::setaccountnumber(int accno){


accountnumber = accno;
}

void Account::setbalance(double bal){


balance = bal;
}

void Account::setwithdraw(int wdraw){


wdraw=balance-wdraw;
}

void Account::setdeposit(int dep){


dep=dep+balance;
}

string Account::getFullName(){
return FullName;
}

int Account::getaccountnumber(){
return accountnumber;
}

double Account::getbalance(){
return balance;
}

void Account::display(){
cout<<"First Name: "<<firstname<<endl;
cout<<"Last Name: "<<lastname<<endl;
cout<<"Account Number: "<<accountnumber<<endl;
cout<<"Current Balance: "<<balance<<endl;
}

int main(){
Account Acc;
Acc.setFullName("Raaj Lokanathan");
Acc.setaccountnumber(5671);
Acc.setbalance(0.0);
Acc.display();
Account acc[50];
string full_name;
int acc_no;
double bAl;
int i;
for(i=0;i<50;i++){
cout<<"Please enter the details for the customer:
"<<i+1<<endl;
cout<<"Please enter your full name: ";
getline(cin,full_name);
cout<<"Please enter your account number: ";
cin>>acc_no;
cout<<"Please enter your current balance: ";
cin>>bAl;
acc[i].setFullName(full_name);
acc[i].setaccountnumber(acc_no);
acc[i].setbalance(bAl);
}
for(i=0;i<50;i++){
cout<<"Detail for the bank customers"<<i+1<<endl;
acc[i].display();
}

system("pause");

return 0;

37. Write a C++ program to demonstrate dynamic memory allocation in c++.

// C++ program to illustrate dynamic


allocation
// and deallocation of memory using new and
delete
#include <iostream>
using namespace std;

int main ()
{
// Pointer initialization to null
int* p = NULL;

// Request memory for the variable


// using new operator
p = new int;
if (!p)
cout << "allocation of memory failed\
n";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}

// Request block of memory


// using new operator
float *r = new float(75.25);

cout << "Value of r: " << *r << endl;

// Request block of memory of size n


int n = 5;
int *q = new int[n];

if (!p)
cout << "allocation of memory failed\
n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;

cout << "Value store in block of


memory: ";
for (int i = 0; i < n; i++)
cout << q[i] << " ";
}

// freed the allocated memory


delete p;
delete r;

// freed the block of allocated memory


delete[] q;

return 0;
}
Run on IDE
Output:
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5

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' provides common interface for 'rectangle'


and 'triangle' class */
class shape {
protected :
int width, height;
public :
shape() { }
// this function is inherited by the derived classes
void setParams(int a, int b) {
width = a;
height = b;
}
// this function is re-defined in the derived classes
virtual void getArea() {
cout << "No shape selected" << endl;
}
};

class rectangle : public shape {


public :
rectangle() { }
void getArea() {
float area = width * height;
cout << "\nLength : " << height << " Breadth : " << width;
cout << "\nArea of Rectangle : " << area << endl;
}
};

class triangle : public shape {


public :
triangle() { }
void getArea() {
float area = 0.5 * width * height;
cout << "\nBase : " << width << " Height : " << height;
cout << "\nArea of Triangle : " << area << endl;
}
};

int main() {
shape *ptr; // pointer to the 'shape' class
rectangle rect;
triangle tr;

/* select any object at run time */


ptr = &rect; // 'rectangle' object selected
ptr->setParams(5,7);
ptr->getArea();

ptr = &tr; // 'triangle' object selected


ptr->setParams(9,3);
ptr->getArea();
return 0;
}

39. Write a C++ program using Switch case to add, subtract, multiply and divide two numbers.

Simple Calculator using switch statement


# include <iostream>
using namespace std;

int main()
{
char op;
float num1, num2;

cout << "Enter operator either + or - or * or /: ";


cin >> op;

cout << "Enter two operands: ";


cin >> 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;
}
Output
Enter operator either + or - or * or divide : -
Enter two operands:
3.4
8.4
3.4 - 8.4 = -5.0

This program takes an operator and two operands from user.

40. Write a C++ program using class to implement basic operations on a stack using arrays
#include<iostream>
#include<stdlib.h>

using namespace std;

class twoStacks
{
int *arr;
int size;
int top1, top2;
public:
twoStacks(int n) // constructor
{
size = n;
arr = new int[n];
top1 = -1;
top2 = size;
}

// Method to push an element x to stack1


void push1(int x)
{
// There is at least one empty space for new element
if (top1 < top2 - 1)
{
top1++;
arr[top1] = x;
}
else
{
cout << "Stack Overflow";
exit(1);
}
}

// Method to push an element x to stack2


void push2(int x)
{
// There is at least one empty space for new element
if (top1 < top2 - 1)
{
top2--;
arr[top2] = x;
}
else
{
cout << "Stack Overflow";
exit(1);
}
}

// Method to pop an element from first stack


int pop1()
{
if (top1 >= 0 )
{
int x = arr[top1];
top1--;
return x;
}
else
{
cout << "Stack UnderFlow";
exit(1);
}
}

// Method to pop an element from second stack


int pop2()
{
if (top2 < size)
{
int x = arr[top2];
top2++;
return x;
}
else
{
cout << "Stack UnderFlow";
exit(1);
}
}
};

/* Driver program to test twStacks class */


int main()
{
twoStacks ts(5);
ts.push1(5);
ts.push2(10);
ts.push2(15);
ts.push1(11);
ts.push2(7);
cout << "Popped element from stack1 is " << ts.pop1();
ts.push2(40);
cout << "\nPopped element from stack2 is " << ts.pop2();
return 0;
}
Output:
Popped element from stack1 is 11
Popped element from stack2 is 40

41. Write a C++ program to display the sizes of various data types in c++ language.

Find Size of a Variable


#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;
}
Output
Size of char: 1 byte
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes

42. Write a C++ program to accept and display employee details using structures.

C++ Program to Store Information of an Employee in a Structure


// C++ program to store data of an employee in a structure
1 variable
2 #include <iostream>
3 using namespace std;
4
struct Employee {
5
char name[50];
6
int salary;
7
int employeeCode;
8
char dept[5];
9
};
10
11 int main() {
12 Employee e;
13
14 cout << "Enter name of employee : ";
15 cin.getline(e.name, 50);
16 cout << "Enter department : ";
17 cin.getline(e.dept, 5);
18 cout << "Enter salary of employee : ";
19 cin >> e.salary;
20 cout << "Enter employee code : ";
21 cin >> e.employeeCode;
22
23 // Printing employee details
24 cout << "\n*** Employee Details ***" << endl;
25 cout << "Name : " << e.name << endl << "Salary : " <<
26 e.salary << endl;
27 cout << "Employee Code : " << e.employeeCode << endl <<
28 "Department : " << e.dept;
29 return 0;
}
Output
Enter name of employee : Jason Donald
Enter department : CSE
Enter salary of employee : 53463
Enter employee code : 1234

*** Employee Details ***


Name : Jason Donald
Salary : 53463
Employee Code : 1234
Department : CSE

43. Write a C++ program to find the length of a given string using string functions

Length of String Object


#include <iostream>
using namespace std;

int main()
{
string str = "C++ Programming";

// you can also use str.length()


cout << "String Length = " << str.size();

return 0;
}
Output
String Length = 15
Length of C-style string
To get the length of a C-string string, strlen() function is used.
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
char str[] = "C++ Programming is awesome";

// you can also use str.length()


cout << "String Length = " << strlen(str);

return 0;
}
Output
String Length = 26

44. Write a C++ program to print the ASCII value of a user entered character
Program to Print ASCII Value
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");

// Reads character input from the user


scanf("%c", &c);

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
return 0;
}
Output
Enter a character: G
ASCII value of G = 71

45. Write a C++ program to add two dimensional matrices


#include <iostream>
using namespace std;

int main()
{
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

cout << "Enter number of rows (between 1 and 100): ";


cin >> r;

cout << "Enter number of columns (between 1 and 100): ";


cin >> c;

cout << endl << "Enter elements of 1st matrix: " << endl;

// Storing elements of first matrix entered by user.


for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}

// Storing elements of second matrix entered by user.


cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << "Enter element b" << i + 1 << j + 1 << " : ";
cin >> b[i][j];
}
// Adding Two matrices
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.


cout << endl << "Sum of two matrix is: " << endl;
for(i = 0; i < r; ++i)
for(j = 0; j < c; ++j)
{
cout << sum[i][j] << " ";
if(j == c - 1)
cout << endl;
}

return 0;
}
Output
Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2

Enter elements of 1st matrix:


Enter element a11: -4
Enter element a12: 5
Enter element a21: 6
Enter element a22: 8

Enter elements of 2nd matrix:


Enter element b11: 3
Enter element b12: -9
Enter element b21: 7
Enter element b22: 2

Sum of two matrix is:


-1 -4
13 6

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 string::operator+(string ob)


{
size = size+ob.size;
s = new char[size];
strcat(s,ob.s);
cout<<"\nConcatnated String is: "<<s;
}

void main()
{
string ob1, ob2;
char *string1, *string2;
clrscr();

cout<<"\nEnter First String:";


cin>>string1;

ob1.getstring(string1);

cout<<"\nEnter Second String:";


cin>>string2;

ob2.getstring(string2);

//Calling + operator to Join/Concatenate strings


ob1+ob2;
getch();
}
Output:
47. Write a C++ program to find the sum of elements in a given array
C++ program to Find Sum of an Array Elements

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

void main()
{
int arr[20],i,n,sum=0;
clrscr();
cout<<"How many elements you want to enter: ";
cin>>n;
cout<<"Enter any "<<n<<" elements in Array: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Sum of all Elements are: ";

for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
}
cout<<sum;
getch();
}

Download Code
Output

How many elements you want to enter : 5


Enter any 5 elements in Array:
14275
Sum of all Elements are: 19

48. Write a C++ program to find the largest of 3 numbers.


Find Largest Number Using if Statement
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

if(n1 >= n2 && n1 >= n3)


{
cout << "Largest number: " << n1;
}

if(n2 >= n1 && n2 >= n3)


{
cout << "Largest number: " << n2;
}

if(n3 >= n1 && n3 >= n2) {


cout << "Largest number: " << n3;
}

return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

49. Write a C++ program to demonstrate exception handling by dividing a number with zero.
Exception Handling Divide by zero Example Program

#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();
}
Sample Output

Enter the value for a: 20


Enter the value for b: 20
Enter the value for c: 40

50. Write a C++ program to convert a binary number to a decimal number.


C++ Program to convert binary number to decimal
#include <iostream>
#include <cmath>

using namespace std;

int convertBinaryToDecimal(long long);

int main()
{
long long n;

cout << "Enter a binary number: ";


cin >> n;

cout << n << " in binary = " << convertBinaryToDecimal(n) <<


"in decimal";
return 0;
}

int convertBinaryToDecimal(long long n)


{
int decimalNumber = 0, i = 0, remainder;
while (n!=0)
{
remainder = n%10;
n /= 10;
decimalNumber += remainder*pow(2,i);
++i;
}
return decimalNumber;
}
Output
Enter a binary number: 1111
1111 in binary = 15

You might also like