0% found this document useful (0 votes)
71 views35 pages

OOPS C++ Practical Records Key

The document contains a series of C++ programming exercises covering various topics such as reversing a number, checking for prime numbers, demonstrating class usage, and implementing functions for addition and sorting. Each exercise includes a code snippet that illustrates the concept being taught, such as function overloading, recursion, and inheritance. The document serves as a comprehensive guide for learning fundamental C++ programming techniques.

Uploaded by

Garima Agrawal
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)
71 views35 pages

OOPS C++ Practical Records Key

The document contains a series of C++ programming exercises covering various topics such as reversing a number, checking for prime numbers, demonstrating class usage, and implementing functions for addition and sorting. Each exercise includes a code snippet that illustrates the concept being taught, such as function overloading, recursion, and inheritance. The document serves as a comprehensive guide for learning fundamental C++ programming techniques.

Uploaded by

Garima Agrawal
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/ 35

1. Write a C++ program to reverse a given number.

#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;
}

2. Write a C++ program to add two numbers using class.


#include <iostream>

using namespace std;

int main()
{
int a, b, c;

cout << "Enter two integers to add\n";


cin >> a >> b;

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>

using namespace std;


int main ()
{
int num, i, count = 0;
cout << "Enter the number to be checked : ";
cin >> num;
if (num == 0)
{
cout << "\n" << num << " is not prime";
exit(1);
}
else {
for(i=2; i < num; i++)
if (num % i == 0)
count++;
}
if (count > 1)
cout << "\n" << num << " is not prime.";
else
cout << "\n" << num << " is prime.";
return 0;
}

4. Write a C++ program to demonstrate the usage of scope resolution operator.


#include <iostream>

using namespace std;

char c = 'a'; // global variable

int main() {
char c = 'b'; //local variable

cout << "Local variable: " << c << "\n";


cout << "Global variable: " << ::c << "\n"; //using scope resolution operator

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;

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;
}

6. Write a C++ program to add two numbers using functions.


#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
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;

printf("Enter two integers to add\n");


scanf("%d%d", &first, &second);

p = &first;
q = &second;

sum = *p + *q;

printf("Sum of the numbers = %d\n", sum);

return 0;
}

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


#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
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;

for (i=0; i<count; i++)


{
cout<<"Enter number "<<(i+1)<<": ";
cin>>arr[i];
}
cout<<"Enter the number that you want to search:";
cin>>num;
first = 0;
last = count-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < num)
{
first = middle + 1;

}
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;

// Reading the size of the array


cout<<"Enter size of array: ";
cin>>size;

//Reading elements of array


cout<<"Enter elements in array: ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
//Sorting an array in ascending order
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
//If there is a smaller element found on right of the array then swap it.
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//Printing the sorted array in ascending order
cout<<"Elements of array in sorted ascending order:"<<endl;
for(i=0; i<size; i++)
{
cout<<arr[i]<<endl;
}

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;

cout << "Enter the number : ";


cin >> number;
remainder = number % 2;
if (remainder == 0)
cout << number << " is an even integer " << endl;
else
cout << number << " is an odd integer " << endl;

return 0;
}

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


#include <iostream.h>

using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

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;
}

21. Write a C++ program to demonstrate parameter passing mechanism using


pass by address method
#include <iostream>

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;
}

void addToInt(int num)


{
cout << "In addToInt(), value of num is " << num << endl << endl;

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

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


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

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;
}
};

class salary : public emp {


float bp, hra, da, pf, np;
13
public:

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;

//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){
16
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;
}

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;
}

void display(string desig) {


cout << "Information of a " << desig << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}
};

class employee {
int emp_id;
float salary;
string designation;

public:
employee() {
cout << "Employee Id:" << endl;
cin >> emp_id;
cout << "Salary:" << endl;
cin >> salary;
}

inline void get_designation(string desig) {


designation = desig;
}

inline string put_designation() {


return designation;
}

void display() {
cout << "Employee Id: " << emp_id << endl;
18
cout << "Salary: " << salary << endl;
cout << "Designation: " << designation << endl;
cout << "\n<------------------------------>\n" << endl;
}
};

/* Inherit two parent class into one child class */


class scientist : person, employee {
public:

/* Call two constructor "person" & "employee" */


scientist() : person("Scientist"), employee() {
get_designation("Scientist");
cout << "\n<------------------------------>\n" << endl;
}

inline void display() {

/* Call display() from class 'person' */


person :: display(put_designation());

/* Call display() from class 'employee' */


employee :: display();
}
};

/* Inherit two parent class into one child class */


class programmer : person, employee {

public:

/* Call two constructor "person" & "employee" */


programmer() : person("Programmer"), employee() {
get_designation("Programmer");
cout << "\n<------------------------------>\n" << endl;
}

inline void display() {

/* Call display() from class 'person' */


person :: display(put_designation());

/* Call display() from class 'employee' */


employee :: display();
}
};

/* Inherit two parent class into one child class */


class service_man : person, employee {

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();

/* Call display() from derived class */


s1.display();
p1.display();
sm1.display();
return 0;
}

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


#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C obj;
obj.display();
return 0;
}
20
29. Write a 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;
}

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;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

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
}

//read and print file content


while (!file.eof())
{
file >> noskipws >> ch; //reading from file
cout << ch; //printing
}
//close the file
file.close();

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;

cout << "Enter a positive integer: ";


cin >> n;

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


sum += i;
}

cout << "Sum = " << sum;


return 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;
}

void deposit(int num)


{

if(num == acc_no)

{
cout<<"\nI am depositing money...";
cout<<"\nEnter the amount you want to deposit : ";
cin>>balance;
}

else
cout<<"\nIncorrect account number.";

void display(int num)


{
if(num == acc_no)
{
cout<<"\nThe current balance of your Account is : "<<balance - wdraw;
}
else
cout<<"\nIncorrect account number.";
}

void withdraw(int num)


{
if(num == acc_no)
{
cout<<"\nI am withdrawing money...";
cout<<"\nEnter the amount to withdraw : ";
25
cin>>wdraw;
cout<<"\n Transaction was successful";
}

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;
}

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


#include <iostream>
using namespace std;

int main () {
double* pvalue = NULL; // Pointer initialized with null
pvalue = new double; // Request memory for the variable

*pvalue = 29494.99; // Store value at allocated address


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

delete pvalue; // free up the memory.

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);
}
};

class Triangle: public Shape {


public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

27
// store the address of Triangle
shape = &tri;

// call triangle area.


shape->area();

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;

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;
}
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;

cout << "Enter name of employee : ";


cin.getline(e.name, 50);
cout << "Enter department : ";
cin.getline(e.dept, 5);
cout << "Enter salary of employee : ";
cin >> e.salary;
cout << "Enter employee code : ";
cin >> e.employeeCode;
30
// Printing employee details
cout << "\n*** Employee Details ***" << endl;
cout << "Name : " << e.name << endl << "Salary : " << e.salary << endl;
cout << "Employee Code : " << e.employeeCode << endl << "Department : "
<< e.dept;
return 0;
}

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>

using namespace std;

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";

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
cin >> first[c][d];

cout << "Enter the elements of second matrix\n";

for ( c = 0 ; c < m ;c++ )


for ( d = 0 ; d < n ; d++ )
cin >> second[c][d];

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];

cout << "Sum of entered matrices:-\n";

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
cout << sum[c][d] << "\t";

cout << endl;


}

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

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;
}

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


#include <stdio.h>

void main()
{
int num1, num2, num3;

printf("Enter the values of num1, num2 and num3\n");


scanf("%d %d %d", &num1, &num2, &num3);
printf("num1 = %d\tnum2 = %d\tnum3 = %d\n", num1, num2, num3);
if (num1 > num2)
{
if (num1 > num3)
{
printf("num1 is the greatest among three \n");
}
else
{
printf("num3 is the greatest among three \n");
}
}
else if (num2 > num3)
printf("num2 is the greatest among three \n");
else
printf("num3 is the greatest among three \n");
}

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

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


#include<iostream>
using namespace std;
int main ()
{
int num, rem, temp, dec = 0, b = 1;
cout << "Enter the binary number : ";
cin >> num;
temp = num;
while (num > 0)
{
rem = temp % 10;
dec = dec + rem * b;
b *= 2;
temp /= 10;
}
cout << "The decimal equivalent of " << num << " is " << dec;
return 0;
}
35

You might also like