0% found this document useful (0 votes)
146 views103 pages

Sairam Oops

The document provides an index of 37 C++ programs with brief descriptions. Each program is numbered and includes the program name, date, page number and sign. The programs cover topics such as arrays, matrices, calculators, type casting, structures, classes, inheritance, exceptions, file handling and more.

Uploaded by

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

Sairam Oops

The document provides an index of 37 C++ programs with brief descriptions. Each program is numbered and includes the program name, date, page number and sign. The programs cover topics such as arrays, matrices, calculators, type casting, structures, classes, inheritance, exceptions, file handling and more.

Uploaded by

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

INDEX

S. Name of Program Date Page Sign


No.
No.
1 Write a C++ program to display one 3
dimensional array and add all of its elements.
2 Write a C++ program to display 2-D array and 6
add all diagonal elements of that matrix.
3 Write a C++ program to create a calculator 10
using switch case.
4 Write a C++ program to implement both 14
implicit and explicit type casting.
5 Write a C++ program to read more than one 16
student details and display them using array of
objects.
6 Write a C++ program to read , more than one 20
student details and display them using
structures.
7 Write a C++ program to read time in seconds 25
and convert it into hr:min:sec using class
8 Write a C++ program to check whether the 27
given number is prime or not using constructors.
9 Write a C++ program to swap two numbers 30
without using third variable with class.
10 Write a C++ program to multiply finite numbers 32
using the concept of default arguments.
11 Write a cpp program to calculate the area of 34
triangle, rectangle and square using function
overloading
12 Write a cpp program to display the various 37
values of same variables declared at different
scope levels
13 Write a Cpp program to find area and perimeter 39
of a circle using inline functions
14 Write a cpp program to allocate memory for a 41
single dimensional array and read the elements
from the keyboard and display all the elements
and after use delete array using new and delete
operators
15 Write a cpp program to display the student 43
details like name, rollno, branch using
constructor overloading
16 Write a C++ program to create copy constructor 46
and show the difference between normal
constructor and copy constructor.
17 Write a C++ program to display employee name 49
and employee id with the use of this pointer.

JNTUHCEH Page 1
18 Write a C++ program containing a friend 52
function which swaps the private data values of
two objects of two different classes.
19 Write a C++ program to implement single level 55
inheritance(constructor).
20 Write a C++ program to implement multilevel 58
inheritance(constructor).
21 Write a C++ program to display the student 61
details (name, rollno, total marks, average)
using multiple inheritance (constructor).
22 Write a C++ program to demonstrate the 64
concept of hybrid inheritance that contains
virtual base class.
23 Write a C++ program to implement hierarchical 67
inheritance.
24 Write a C++ program to demonstrate method 69
overriding.
25 Write a C++ program to implement virtual 71
functions.
26 Write a C++ program to display the two 73
different employee salary in 2 subclasses with
each employee in each subclass using pure
virtual function.
27 Write a C++ program to overload the arithmetic 76
operator ‘+’ so that it can be used for
concatenation of two strings.
28 Write a C++ program to implement unary 79
operator overloading using member function.
29 Write a C++ program to implement unary 82
operator overloading using friend function.
30 Write a C++ program to add and subtract two 85
complex numbers using friend function which
overloads a binary operator.
31 Write a C++ program to handle the divide by 88
zero exception.
32 Write a C++ program to explain how to use 90
multiple catch blocks.
33 Write a C++ program to implement 93
“rethrowing an exception”.
34 Write a C++ program to perform read/write 95
operations on a file.
35 Write a C++ program to copy the contents of one 97
file into another.
36 Write a C++ program to illustrate the use of 100
member functions (tellg,seekg) to obtain the size
of a file.
37 Write a C++ program to count the number of 102
blank spaces present in a text file.

JNTUHCEH Page 2
1. Write a C++ program to display one dimensional array and add
all of its elements.
#include<iostream>
using namespace std;
int main()
{
int arr[100];
int size,i,sum=0;
cout<<"ENTER SIZE OF ARRAY :"<<endl;
cin>> size;
cout<<"==========================================="<<e
ndl;
cout<<"ENTER ARRAY ELEMENTS :\n";
for(i=0 ; i<size ; i++)
{
cout<<"ENTER A VALUE :";
cin>>arr[i];
}
cout<<"\n***** ARRAY ELEMENTS ARE *****"<<endl;
for(i=0 ; i<size ; i++)
{
cout<<arr[i] <<endl;
cout<<"--------------"<<endl;
}
for(i=0 ; i<size ; i++)
{
sum=sum+arr[i];
}

JNTUHCEH Page 3
cout<<"\n***** SUM OF ARRAY ELEMENTS IS :"<< sum <<endl;
return 0;
}

JNTUHCEH Page 4
OUTPUT:
ENTER SIZE OF ARRAY :
5
===========================================
ENTER ARRAY ELEMENTS :
ENTER A VALUE :11
ENTER A VALUE :21
ENTER A VALUE :31
ENTER A VALUE :41
ENTER A VALUE :51

***** ARRAY ELEMENTS ARE *****


11
--------------

21
--------------
31
-------------
41
--------------
51
--------------

***** SUM OF ARRAY ELEMENTS IS :155

JNTUHCEH Page 5
2. Write a C++ program to display 2-D array and add all diagonal
elements of that matrix.
#include<iostream>
using namespace std;
int main()
{
int rows,col,i,j,sum=0,sum1=0;
int arr[30][30];
cout<<"ENTER ROWS AND COLUMNS OF 2-D ARRAY:\n";
cin>>rows>>col;
cout<<"ENTER ELEMENTS OF THE ARRAY :\n";
for(i=0;i<rows;i++)
{
for(j=0;j<col;j++)
{
cout<<"ENTER A VALUE :";
cin>>arr[i][j];
}
}
cout<<"\nELEMENTS OF THE ARRAY : \n";
for(i=0;i<rows;i++)
{
for(j=0;j<col;j++)
{
cout<<arr[i][j];
cout<<"\n---------------\n";
}

JNTUHCEH Page 6
}
cout<<"\n===========================\n";
if(rows == col)
{
for(i=0;i<rows;i++)
{
for(j=0;j<col;j++)
{
if(i==j)
{
sum=sum+arr[i][j];
}
}
}
cout<<"SUM OF PRINCIPAL DIAGONAL ELEMENTS IS :"<<sum;
cout<<"\n===========================\n";
for(i=0 ; i<rows ; i++)
{
for(j=0 ; j<col ; j++)
{
if(i+j==rows-1)
{
sum1=sum1+arr[i][j];
}
}
}
cout<<"SUM OF SECONDARY DIAGONAL ELEMENTS IS
:"<<sum1;

JNTUHCEH Page 7
cout<<"\n===========================\n";
}
else
{
cout<<"\nTHE ARRAY IS NOT A SQUARE MATRIX";
}
return 0;}

JNTUHCEH Page 8
OUTPUT :
ENTER ROWS AND COLUMNS OF 2-D ARRAY:
3
3
ENTER ELEMENTS OF THE ARRAY :
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2
ENTER A VALUE :2

ELEMENTS OF THE ARRAY :


2
---------------
2
---------------
2
--------------
2
---------------
2
---------------
2

JNTUHCEH Page 9
---------------
2
---------------
2
--------------
2
---------------

===========================
SUM OF PRINCIPAL DIAGONAL ELEMENTS IS : 6
===========================
SUM OF SECONDARY DIAGONAL ELEMENTS IS : 6
===========================

JNTUHCEH Page 10
3. Write a C++ program to create a calculator using switch case.
#include<iostream>
using namespace std;
int main()
{
cout<<"*************CALCULATOR
OPERATIONS*******************\n";
int a,b;
cout<<"\nENTER TWO NUMBERS:\n";
cin>> a >> b;
cout<<"=========================================\n";
cout<<"\n ENTER YOUR CHOICE \n +.ADD \n -.SUBTRACT \n
*.PRODUCT \n /.DIVISION \n %.MODULO\n";
char ch;
cin>>ch;
cout<<"=========================================\n";
switch(ch)
{
case '+':cout<<"SUM OF "<< a <<" AND "<< b <<"IS :
"<<a+b<<endl;
break;
case '-':cout<<"DIFFERENCE OF "<< a <<" AND "<< b <<" IS : "<<
a-b <<endl;
break;
case '*':cout<<"PRODUCT OF "<< a <<" AND "<< b <<" IS : "<<
a*b <<endl;
break;
case '/':cout<<"DIVISION OF "<< a <<" AND "<< b <<" IS : "<<
a/b<<endl;

JNTUHCEH Page 11
break;
case '%':cout<<"MODULO OF "<< a <<" AND "<< b <<" IS : "<<
a%b <<endl;
break;
default:printf("OOPS !!! \n YOUR CHOICE IS WRONG ");
}
printf("\n============================================\n
");
return 0;
}

JNTUHCEH Page 12
OUTPUT:
*************CALCULATOR OPERATIONS*******************

ENTER TWO NUMBERS:


10
20
=========================================

ENTER YOUR CHOICE


+.ADD
-.SUBTRACT
*.PRODUCT
/.DIVISION
%.MODULO
+
=========================================
SUM OF 10 AND 20 IS : 30

============================================

JNTUHCEH Page 13
4. Write a C++ program to implement both implicit and explicit
type casting.
#include<iostream>
using namespace std;
int main()
{
cout<<"** IMPLICIT TYPE CASTING **\n";
int x=10;
char y='a';
x=x+y;
float z=x+1.0;
cout<<"x ="<< x <<endl;
cout<<"y ="<< y <<endl;
cout<<"z ="<< z <<endl;
cout<<endl<<"============================="<<endl;

cout<<"** EXPLICIT TYPE CASTING **\n";


double num=1.2;
int sum=(int)num+1;
cout<<"SUM IS :"<< sum;
cout<<endl<<"============================="<<endl;
return 0;
}

JNTUHCEH Page 14
OUTPUT:
** IMPLICIT TYPE CASTING **
x =107
y =a
z =108

=============================
** EXPLICIT TYPE CASTING **
SUM IS :2
=============================

JNTUHCEH Page 15
5. Write a C++ program to read more than one student details and
display them using array of objects.
#include<iostream>
#include<string>
using namespace std;
class student
{
string name;
int age;
string rollno;
public:
void getdata()
{
cout<<"ENTER STUDENT NAME :"<<endl;
cin>> name;
cout<<"ENTER STUDENT AGE :"<<endl;
cin>> age;
cout<<"ENTER STUDENT ROLL NUMBER :"<<endl;
cin>>rollno;
}
void putdata()
{
cout<<"STUDENT NAME :"<< name <<endl;
cout<<"STUDENT AGE :"<<age<<endl;
cout<<"STUDENT ROLL NUMBER :"<<rollno<<endl;
}

JNTUHCEH Page 16
};
int main()
{
student s[10];
int size;
cout<<"ENTER NUMBER OF STUDENTS :"<<endl;
cin>> size;
for(int i=0 ; i<size ; i++)
{
cout<<"FOR STUDENT :"<< i+1 <<endl;
s[i].getdata();
cout<<"\n==============================="<<endl<<endl;
}
for(int i=0 ; i<size ; i++)
{
cout<<"FOR STUDENT :"<< i+1 <<endl;
s[i].putdata();
cout<<"\n==============================="<<endl;
}
return 0;
}

JNTUHCEH Page 17
OUTPUT:
ENTER NUMBER OF STUDENTS :
3
FOR STUDENT : 1
ENTER STUDENT NAME :
Sairam
ENTER STUDENT AGE :
17
ENTER STUDENT ROLL NUMBER :
08

===============================

FOR STUDENT : 2
ENTER STUDENT NAME :
sravan
ENTER STUDENT AGE :
18
ENTER STUDENT ROLL NUMBER :
18

===============================

FOR STUDENT : 3
ENTER STUDENT NAME :
k.p
ENTER STUDENT AGE :

JNTUHCEH Page 18
19
ENTER STUDENT ROLL NUMBER :
15
===============================
FOR STUDENT : 1
STUDENT NAME :sairam
STUDENT AGE :17
STUDENT ROLL NUMBER :08

===============================
FOR STUDENT : 2
STUDENT NAME :sravan
STUDENT AGE :18
STUDENT ROLL NUMBER : 18

===============================
FOR STUDENT : 3
STUDENT NAME :k.p
STUDENT AGE :19
STUDENT ROLL NUMBER :15

===============================

JNTUHCEH Page 19
6. Write a C++ program to read , more than one student details
and display them using structures.
#include<iostream>
#define MAX 3 // max is macro that can be changed according to the required
no.of students
using namespace std;
struct student{
char sname[30],dept[10];
int sroll,syear;
float cgpa;
}s[MAX];

int main(){
int i;
cout<<"STUDENT DETAILS"<<endl;
cout<<"==============="<<endl;
for(i=0;i<MAX;i++){
cout<<"Enter details of student "<<i+1<<endl;
cout<<"Enter name"<<endl;
cin>>s[i].sname;
cout<<"Enter roll no."<<endl;
cin>>s[i].sroll;
cout<<"Enter dept"<<endl;
cin>>s[i].dept;
cout<<"Enter year"<<endl;
cin>>s[i].syear;
cout<<"Enter CGPA"<<endl;
cin>>s[i].cgpa;

JNTUHCEH Page 20
}
for(i=0;i<MAX;i++){
cout<<"Details of studenT"<<i+1<<endl;
cout<<"Name : "<<s[i].sname<<endl;
cout<<"Roll no.: "<<s[i].sroll<<endl;
cout<<"Dept : "<<s[i].dept<<endl;
cout<<"Year : "<<s[i].syear<<endl;
cout<<"CGPA : "<<s[i].cgpa<<endl;
}
return 0;
}

JNTUHCEH Page 21
OUTPUT:
STUDENT DETAILS
===============
Enter details of student 1
Enter name
Sairam
Enter roll no.
508
Enter dept
CSE
Enter year
2018
Enter CGPA
9.5
Enter details of student 2
Enter name
VENKAT
Enter roll no.
506
Enter dept
CSE
Enter year
3
Enter CGPA
9.1
Enter details of student 3
Enter name

JNTUHCEH Page 22
SID
Enter roll no.
520
Enter dept
ECE
Enter year
2
Enter CGPA
9.1
Details of student1
Name : KP
Roll no.: 515
Dept : CSE
Year : 2
CGPA : 9.5
===========
Details of student2
Name : VENKAT
Roll no.: 506
Dept : CSE
Year : 3
CGPA : 9.1
==========
Details of student3
Name : SID
Roll no.: 521
Dept : ECE

JNTUHCEH Page 23
Year : 2
CGPA : 9.1

JNTUHCEH Page 24
7. Write a C++ program to read time in seconds and convert it into
hr:min:sec using class
#include <iostream>
using namespace std;
class time{
public:
int hr,minute,sec;
void displayTime(){
cout<<"time in HH:MM:SS"<<endl;
cout<<hr<<":"<<minute<<":"<<sec;}
};
int main()
{ long input;
time t;
cout<<"Enter seconds"<<endl;
cin>>input;
t.hr=input/3600;
input=input%3600;
t.minute=input/60;
input=input%60;
t.sec=input;
t.displayTime();
return 0;

JNTUHCEH Page 25
OUTPUT:
Enter seconds
3722
time in HH:MM:SS
1:2:2

JNTUHCEH Page 26
8. Write a C++ program to check whether the given number is
prime or not using constructors.
#include<iostream>
#include<conio.h>
using namespace std;
class Prime {
int a, k, i;
public:
Prime(int x) {
a = x;
k = 1;
{
for (i = 2; i<= a / 2; i++)
if (a % i == 0) {
k = 0;
break;
} else {
k = 1;
}
}
}

void show() {
if (k == 1)
cout<< a << " is Prime Number.";
else
cout<< a << " is Not Prime Numbers.";

JNTUHCEH Page 27
}
};
int main() {
int a;
cout<< "Simple Parameterized Constructor For Prime Number Example
Program In C++\n";
cout<< "\nEnter the Number:";
cin>>a;
Prime obj(a);
obj.show();
getch();
return 0;
}

JNTUHCEH Page 28
OUTPUT:
Simple Parameterized Constructor For Prime Number Example Program In C++
Enter the Number:5
5 is Prime Number.

JNTUHCEH Page 29
9. Write a C++ program to swap two numbers without using third
variable with class.
#include<iostream>
using namespace std;
class swapping{ //swap is pre defined function in cpp hence swapping is
used
public:
int a,b;
void swapMethod(){
cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap a= "<<a<<" b= "<<b<<endl;
}
};

int main(){
swapping s;
cout<<"Enter a, b"<<endl;
cin>>s.a>>s.b;
s.swapMethod();
return 0;
}

JNTUHCEH Page 30
OUTPUT:
Enter a, b
15
10
Before swap a= 15 b= 10
After swap a= 10 b= 15

JNTUHCEH Page 31
10. Write a C++ program to multiply finite numbers using the
concept of default arguments.
#include<iostream>
using namespace std;
int multiply(int x, int y=1, int z=1, int w=1)
{
return (x * y * z * w);
}
int main()
{ int a,b,c,d;
cout<<"Enter a,b,c,d"<<endl;
cin>>a>>b>>c>>d;
cout<<"Multiplication of a,b is "<< multiply(a, b) <<endl;
cout<<"Multiplication of a,b,c is "<<multiply(a, b, c) <<endl;
cout<< "Multiplication of a,b,c is "<<multiply(a, b, c, d) <<endl;
return 0;
}

JNTUHCEH Page 32
OUTPUT:
Enter a,b,c,d
10
20
30
40
Multiplication of a,b is 200
Multiplication of a,b,c is 600
Multiplication of a,b,c,d is 2400

JNTUHCEH Page 33
11. Write a cpp program to calculate the area of triangle, rectangle
and square using function overloading
#include <iostream>
#include<cmath>
using namespace std;
float area(int s) {
return s*s; //area of sqare of side s
}
float area(intx,inty,int z) {
int p = (x+y+z)/2;
intsquareOfArea = p*(p-x)*(p-y)*(p-z);
int area = sqrt(squareOfArea);
return area; //area of triangle of 3 sides x,y,z
}
float area(intl,int b) {
return l*b; //area of rectangle of length l and breadth b
}
int main()
{ ints,l,breadth,x,y,z;
cout<<"enter three sides of a triangle"<<endl;
cin>>x>>y>>z;
cout<<endl<<"enter length and breadth of a rectange"<<endl;
cin>>l>>breadth;
cout<<endl<<"enter side of a sqare"<<endl;
cin>>s;
cout<<"the area of triangle of sides "<<x<<" "<<y<<" "<<z<<" is
"<<area(x,y,z)<<endl;

JNTUHCEH Page 34
cout<<"the area of rectangle of length "<<l<<" and breadth "<<breadth<<" is
"<<area(l,breadth)<<endl;
cout<<"the area of sqare of side "<<s<<"is "<<area(s)<<endl;
return 0;
}

JNTUHCEH Page 35
OUTPUT:
enter three sides of a triangle
6 8 10
enter length and breadth of a rectangle
24
enter side of a square
16
the area of triangle of sides 6 8 10 is 240
the area of rectangle of length and breadth 1is 2
the area of square of side 16 is 256

JNTUHCEH Page 36
12. Write a cpp program to display the various values of same variables
declared at different scope levels
#include <iostream>
using namespace std;
intnum = 10;
class Demo{
public:
staticconstintnum = 40;
};
int main()
{ intnum = 50;
cout<<"global num: "<<::num<<endl;
cout<<"num in main: "<<num<<endl;
cout<<"num in class Demo: "<<Demo::num;

return 0;
}

JNTUHCEH Page 37
OUTPUT:
globalnum: 10
num in main: 50
num in class Demo: 40

JNTUHCEH Page 38
13. Write a Cpp program to find area and perimeter of a circle
using inline functions
#include <iostream>
#include<cmath>
using namespace std;
intnum = 100;
class Demo{
public:
staticconstintnum = 4;
};
inline double area(int r) {
return M_PI*r*r;
}
inline double perimeter(int r) {
return M_PI*r*2;
}
int main()
{ int r;
cout<<"enter radius of circle"<<endl;
cin>>r;
cout<<"the area of circle of radius "<<r<<" is "<<area(r)<<endl;
cout<<"the perimeter of circle of radius "<<r<<" is "<<perimeter(r);
return 0;
}

JNTUHCEH Page 39
OUTPUT:
enter radius of circle
6
thearea of circle of radius 6 is 113.097
the perimeter of circle of radius 6 is 37.6991

JNTUHCEH Page 40
14. Write a cpp program to allocate memory for a single
dimensional array and read the elements from the keyboard and
display all the elements and after use delete array using new and
delete operators
#include <iostream>
using namespace std;
int main()
{ int n;
cout<<"enter size of array";
cin>>n;
int *p = new int[n];
for(int i = 0;i<n; i++) {
cout<<"enter element"<<endl;
cin>>p[i];
}
cout<<"array "<<endl;
for(int i=0; i<n;i++) {
cout<<p[i]<<"\t";
}
delete[]p;
}

JNTUHCEH Page 41
OUTPUT:
enter size of array
3
enter element
10
enter element
20
enter element
30
array
10 20 30

JNTUHCEH Page 42
15. Write a cpp program to display the student details like
name,rollno,branch using constructor overloading
#include <iostream>
#include<cstring>
using namespace std;
class Student{
string name;
string roll;
string branch;
int age;
public:
Student();
Student(string,string,string,int);
void display();
};
Student::Student(){
cout<<"inside no argumented constructor"<<endl;
cout<<"enter name"<<endl;
cin>>name;
cout<<"enter roll"<<endl;
cin>>roll;
cout<<"enter branch"<<endl;
cin>>branch;
cout<<"enter age"<<endl;
cin>>age;}
Student::Student(string name,stringroll,stringbranch,int age){
cout<<"inside argumented constructor"<<endl;

JNTUHCEH Page 43
this->name = name;
this->roll = roll;
this->branch = branch;
this->age = age;
}
void Student::display() {
cout<<"Student Info"<<endl;
cout<<"name "<<name<<endl
<<"roll "<<roll<<endl
<<"branch "<<branch<<endl
<<"age "<<age<<endl;
}
int main()
{ int age;
stringname,roll,branch;
cout<<"enter name, roll, branch, and age of student1(for constructing object
using argumented constructor)";
cin>>name>>roll>>branch>>age;
Student s1(name,roll,branch,age);
s1.display();
Student s2;
s2.display();
}

JNTUHCEH Page 44
OUTPUT:
enter name, roll, branch, and age of student1(for constructing object using
argumented constructor)
Sairam
08
Cse
18
insideargumented constructor
Student Info
name sairam
roll 08
branch cse
age 18
insideno-argumented constructor
enter name
preethi
enter roll
41
enter branch
civil
enter age
18
Student Info
Name preethi
roll 41
branch cse
age 18

JNTUHCEH Page 45
16. Write a C++ program to create copy constructor and show the
difference between normal constructor and copy constructor.
#include<iostream>
using namespace std;
class Sample
{
int n1,n2;
public:
Sample()//default (normal) constructor
{
n1=10;
n2=20;
}
Sample(int a,int b)//parameterized (normal) constructor
{
n1=a;
n2=b;
}
Sample(Sample &S1)//copy constructor
{
n1=S1.n1;
n2=S1.n2;
}
void display();
};
void Sample :: display()
{

JNTUHCEH Page 46
cout<<"n1="<<n1<<endl;
cout<<"n2="<<n2<<endl;
}
int main()
{
Sample S1;//default constructor is called
cout<<"FOR OBJECT S1 :"<<endl;
S1.display();
cout<<"--------------------------\n";
Sample S2(1,2);//parameterized constructor is called
cout<<"FOR OBJECT S2 :"<<endl;
S2.display();
cout<<"--------------------------\n";
Sample S3(S2);//copy constructor is called
cout<<"FOR OBJECT S3 :"<<endl;
S3.display();
cout<<"--------------------------\n";
return 0;
}

JNTUHCEH Page 47
OUTPUT:
FOR OBJECT S1:
n1=10
n2=20
-----------------------
FOR OBJECT S2:
n1=1
n2=2
-----------------------
FOR OBJECT S3:
n1=1
n2=2
-----------------------

JNTUHCEH Page 48
17. Write a C++ program to display employee name and employee
id with the use of this pointer.
#include<iostream>
#include<string>
using namespace std;
class Employee
{
string emp_name;
string emp_ID;
public:
void input(string &emp_name,string &emp_ID)
{
this->emp_name=emp_name;
this->emp_ID=emp_ID;
}
void show_data();
};
void Employee :: show_data()
{
cout<<"\n\nEMPLOYEE DETAILS\n-----------------------\n";
cout<<"EMPLOYEE NAME :"<<emp_name<<endl;
cout<<"EMPLOYEE ID :"<<emp_ID<<endl;
}
int main()
{
Employee E1;
cout<<"ENTER NAME OF THE EMPLOYEE:";

JNTUHCEH Page 49
string name;
cin>>name;
cout<<"ENTER EMPLOYEE ID:";
string ID;
cin>>ID;
E1.input(name,ID);
E1.show_data();
return 0;
}

JNTUHCEH Page 50
OUTPUT:
ENTER NAME OF THE EMPLOYEE : Preethi
ENTER EMPLOYEE ID : 41

EMPLOYEE DETAILS
--------------------------
EMPLOYEE NAME : Preethi
EMPLOYEE ID : 41

JNTUHCEH Page 51
18. Write a C++ program containing a friend function which swaps
the private data values of two objects of two different classes.
#include<iostream>
using namespace std;
class Two; //Forward Declaration
class One
{
int x;
public:
One(int a)
{
x=a;
}
friend void swap(One ,Two);
};
class Two
{
int y;
public:
Two(int b)
{
y=b;
}
friend void swap(One ,Two);
};
void swap(One O1,Two T1)
{

JNTUHCEH Page 52
cout<<"BEFORE SWAP :\n";
cout<<"------------\n";
cout<<"VALUE IN CLASS One : x="<<O1.x<<endl;
cout<<"VALUE IN CLASS Two : y="<<T1.y<<endl;
cout<<"----------------------------------\n";
int temp;
temp=O1.x;
O1.x=T1.y;
T1.y=temp;
cout<<"AFTER SWAP \n";
cout<<"------------\n";
cout<<"VALUE IN CLASS One : x="<<O1.x<<endl;
cout<<"VALUE IN CLASS Two : y="<<T1.y<<endl;
cout<<"----------------------------------\n";

}
int main()
{
One obj1(1);
Two obj2(2);
swap(obj1,obj2);
return 0;
}

JNTUHCEH Page 53
OUTPUT:
BEFORE SWAP :
--------------------
VALUE IN CLASS One : x= 1
VALUE IN CLASS Two : y=2
-----------------------------------------
AFTER SWAP :
--------------------
VALUE IN CLASS One : x= 2
VALUE IN CLASS Two : y=1
-----------------------------------------

JNTUHCEH Page 54
19. Write a C++ program to implement single level
inheritance(constructor).
#include<iostream>
using namespace std;
class Parent
{
protected:
int x;
public:
Parent(int a)
{
x=a;
}
};
class Child:public Parent
{
int y;
public:
Child(int a,int b): Parent(a)
{
y=b;
}
void sum();
};
void Child::sum()
{
cout<<"VALUE IN PARENT CLASS :x="<<x<<endl;

JNTUHCEH Page 55
cout<<"VALUE IN CHILD CLASS :y="<<y<<endl;
cout<<"SUM OF VALUES ="<<(x+y)<<endl;
}
int main()
{
Child C(100,200);
C.sum();
return 0;
}

JNTUHCEH Page 56
OUTPUT:
VALUE IN PARENT CLASS : x=100
VALUE IN CHILD CLASS : y=200
SUM OF VALUES = 300

JNTUHCEH Page 57
20. Write a C++ program to implement multilevel
inheritance(constructor).
#include<iostream>
using namespace std;
class One
{
protected:
int x;
public:
One(int a)
{
x=a;
}
};
class Two
{
protected:
int y;
public:
Two(int b)
{
y=b;
}
};
class Three:public One,public Two
{
int z;

JNTUHCEH Page 58
public:
Three(int a,int b,int c): One(a),Two(b)
{
z=c;
}
void sum();
};
void Three::sum()
{
cout<<"VALUE IN CLASS One :x="<<x<<endl;
cout<<"VALUE IN CLASS Two :y="<<y<<endl;
cout<<"VALUE IN CLASS Three:z="<<z<<endl;
cout<<"SUM OF VALUES ="<<(x+y+z)<<endl;
}
int main()
{
Three T(11,21,31);
T.sum();
return 0;
}

JNTUHCEH Page 59
OUTPUT:
VALUE IN CLASS One : x=11
VALUE IN CLASS Two : y=21
VALUE IN CLASS Three : z=31
SUM OF VALUES=63

JNTUHCEH Page 60
21. Write a C++ program to display the student details (name,
rollno, total marks, average) using multiple inheritance
(constructor).

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

class student {
protected:
int rno, m1, m2;
public:

void get() {
cout << "Enter the Roll no :";
cin>>rno;
cout << "Enter the two marks :";
cin >> m1>>m2;
}
};

class sports {
protected:
int sm; // sm = Sports mark
public:

void getsm() {
cout << "\nEnter the sports mark :";
cin>>sm;

}
};

class statement : public student, public sports {


int tot, avg;
public:

JNTUHCEH Page 61
void display() {
tot = (m1 + m2 + sm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << rno << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
int main() {

statement obj;
obj.get();
obj.getsm();
obj.display();
return 0;
}

JNTUHCEH Page 62
OUTPUT:
Enter the Roll no: 08
Enter two marks
91
81
Enter the Sports Mark: 91
Roll No: 08
Total : 263
Average: 86.7

JNTUHCEH Page 63
22. Write a C++ program to demonstrate the concept of hybrid inheritance
that contains virtual base class.
#include<iostream>
#include<conio.h>
using namespace std;
class student {
int rno;
public:
void getnumber() {
cout << "Enter Roll No:";
cin>>rno;
}

void putnumber() {
cout << "\n\n\tRoll No:" << rno << "\n";
}
};

class test : virtual public student {


public:
int part1, part2;

void getmarks() {
cout << "Enter Marks\n";
cout << "Part1:";
cin>>part1;
cout << "Part2:";
cin>>part2;
}

void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};

JNTUHCEH Page 64
class sports : public virtual student {
public:
int score;

void getscore() {
cout << "Enter Sports Score:";
cin>>score;
}

void putscore() {
cout << "\n\tSports Score is:" << score;
}
};

class result : public test, public sports {


int total;
public:

void display() {
total = part1 + part2 + score;
putnumber();
putmarks();
putscore();
cout << "\n\tTotal Score:" << total;
}
};

int main() {
result obj;

obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
return 0;
}

JNTUHCEH Page 65
OUTPUT:

input
6
Enter Roll No:508
Enter Marks
Part1:26
Part2:46
Enter Sports Score:26

Roll No:508
Marks Obtained
Part1:26
Part2:46
Sports Score is:26
Total Score:98

JNTUHCEH Page 66
23. Write a C++ program to implement hierarchical inheritance.

#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

class Car: public BUS


{

};

class Bus: public BUS


{

};

int main()
{
Car obj1;
Bus obj2;
return 0;
}

JNTUHCEH Page 67
OUTPUT:
This is a BUS
This is a BUS

JNTUHCEH Page 68
24. Write a C++ program to demonstrate method overriding.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
BaseClass obj = DerivedClass();
obj.disp();
return 0;
}

JNTUHCEH Page 69
OUTPUT:
Function of Parent Class

JNTUHCEH Page 70
25. Write a C++ program to implement virtual functions.

#include<iostream>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print ()
{ cout<< "print the derived class" <<endl; }

void show ()
{ cout<< "show the derived class" <<endl; }
};

int main()
{
base *bptr;
derived d;
bptr = &d;

bptr->print();

bptr->show();

JNTUHCEH Page 71
OUTPUT:
Print the derived class
Show the base class

JNTUHCEH Page 72
26. Write a C++ program to display the two different employee salary in 2
subclasses with each employee in each subclass using pure virtual function.
#include<iostream>
using namespace std;
class employee
{
public:long amount;
virtual void salary()=0;
};
class employee1:public employee
{
public:employee1(long m)
{
amount=m;
}
void salary()
{
cout<<"\nSalary of 1st employee is "<<amount;
}
};
class employee2:public employee
{
public:employee2(long m)
{
amount=m;
}
void salary()
{

JNTUHCEH Page 73
cout<<"\nSalary of 2nd employee is "<<amount;
}
};
int main(
{
employee1 e1(500000);
employee2 e2(200000);
e1.salary();
e2.salary();
}

JNTUHCEH Page 74
OUTPUT:
Salary of 1st employee is 500000
Salary of 2nd employee is 200000

JNTUHCEH Page 75
27. Write a C++ program to overload the arithmetic operator ‘+’
so that it can be used for concatenation of two strings.
#include <iostream>
#include <string.h>
using namespace std;
class strings
{
public: char str[100];
strings() {}
strings(char str[])
{
strcpy(this->str, str);
}
strings operator+(strings& S2)
{
strings S3;
strcat(this->str, S2.str);
strcpy(S3.str, this->str);
return S3;
}
};
int main()
{
char str1[100],str2[100];
cout<<"\nEnter 1st string:";
gets(str1);
cout<<"\nEnter 2nd string:";

JNTUHCEH Page 76
gets(str2);
strings a1(str1),a2(str2),a3;
a3 = a1 + a2;
cout<< "\nConcatenation: " << a3.str;
return 0;
}

JNTUHCEH Page 77
OUTPUT:
Enter 1st string: Sairam

Enter 2nd string: Balu

Concatenation: Sairam Balu

JNTUHCEH Page 78
28. Write a C++ program to implement unary operator
overloading using member function.
#include <iostream>
using namespace std;
class sample
{
int n1,n2;
public : sample ( ) { }
sample (int x , int y)
{
n1 = x;
n2 = y;
}
void show ( );
sample operator + ( int );
};
void sample :: show()
{
cout<< "\nn1=" << n1;
cout<< "\nn2=" << n2;
}
sample sample :: operator + ( int x )
{
sample s1;
s1.n1=n1+x;
s1.n2=n2+x;
return(s1);

JNTUHCEH Page 79
}
int main()
{
sample s2(100,200);
sample s3 = s2.operator + (5) ;
cout<< "\nFor s2";
s2.show ( );
cout<< "\nFor s3" ;
s3.show ( );
}

JNTUHCEH Page 80
OUTPUT:
For s2
n1=100
n2=200

For s3
n1=105
n2=205

JNTUHCEH Page 81
29. Write a C++ program to implement unary operator
overloading using friend function.
#include<iostream>
using namespace std;
class space
{
intx,y,z;
public:voidgetdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void display()
{
cout<<"\nx="<<x;
cout<<"\ny="<<y;
cout<<"\nz="<<z;
}
friend void operator -(space &s);
};
void operator -(space &s)
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}

JNTUHCEH Page 82
int main()
{
space s1,s2;
s1.getdata(15,10,5);
s1.display();
-s1;
s1.display();
return 0;
}

JNTUHCEH Page 83
OUTPUT:
x=15
y=10
z=5

x=-15
y=-10
z=-5

JNTUHCEH Page 84
30. Write a C++ program to add and subtract two complex
numbers using friend function which overloads a binary operator.
#include<iostream>
using namespace std;
class complex
{
float x,y;
public:complex(){}
complex(float real,float imag)
{
x=real;
y=imag;
}
friend complex operator +(complex ,complex);
friend complex operator -(complex ,complex);
void display()
{
cout<<"("<<x<<")"<<"+"<<"("<<y<<")"<<"j"<<"\n";
}
};
complex operator +(complex a,complex b)
{
complex temp;
temp.x=a.x+b.x;
temp.y=a.y+b.y;
return temp;
}

JNTUHCEH Page 85
complex operator -(complex a,complex b)
{
complex temp;
temp.x=a.x-b.x;
temp.y=a.y-b.y;
return temp;
}
int main()
{
complex c1(5.0,5.5),c2(10.0,10.5),c3,c4;
c3=c1+c2;
c4=c1-c2;
cout<<"\nNUM1=";
c1.display();
cout<<"\nNUM2=";
c2.display();
cout<<"\nSUM=";
c3.display();
cout<<"\nDIFFERENCE=";
c4.display();
}

JNTUHCEH Page 86
OUTPUT:
NUM1=(15)+(5.5)j

NUM2=(1)+(10.5)j

SUM=(16)+(16)j

DIFFERENCE=(14)+(-5)j

JNTUHCEH Page 87
31. Write a C++ program to handle the divide by zero exception.
Note : inputs are given by user.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero exception raised”;
}
return (a/b);
}
int main ()
{
int x ;
int y ;
cout<<”enter the numerator and denominator value”;
cin>>x>>y;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}

JNTUHCEH Page 88
OUTPUT:
enter the numerator and denominator value
81
9
result = 9

enter the numerator and denominator value


18
0
Division by zero Exception raised

JNTUHCEH Page 89
32. Write a C++ program to explain how to use multiple catch
blocks.
#include<iostream>
using namespace std;
void func(int a)
{
try{
if(a==0)
throw a;
else if(a>0)
throw ‘b’;
else if(a<0)
throw .0;
}
}
catch(char d)
{
cout<<”Caught positive value”<<endl;
}
catch(int e)
{
cout<<”Caught a null value”<<endl;
}
catch(double f)
{
cout<<”Caught a negative value”;
}
Cout<<”Multiple catch blocks”<<endl;
}
int main()
{
int input;

JNTUHCEH Page 90
cout<<”Enter input value”;
cin>>input;
func(input);
return 0;
}

JNTUHCEH Page 91
OUTPUT:
Enter input value -9
Caught a negative value
Multiple catch blocks

Enter input value 9


Caught a positive value
Multiple catch blocks

Enter input value 0


Caught a null value
Multiple catch blocks

JNTUHCEH Page 92
33. Write a C++ program to implement “rethrowing an exception”.

#include <iostream>
using namespace std;
void myFunction()
{
try {
throw "hello"; // throw a char *
}
catch(const char *)
{
cout << "Caught char * inside myFunction\n";
throw ; // rethrow char * out of function
} // myFunction
}
int main()
{
cout << "Start\n";
try{
myFunction();
}
catch(const char *)
{
cout << "Caught char * inside the main\n";
}
cout << "End";
return 0;
}

JNTUHCEH Page 93
OUTPUT:

Start
Caught char * inside my Function
Caught char * inside the main
End

JNTUHCEH Page 94
34. Write a C++ program to perform read/write operations on a
file.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char input[75];
ofstream of;
of.open("text_file.txt");
cout <<"Writing to a text file:" << endl;
cout << "Please Enter your name: ";
cin.getline(input, 100);
of << input << endl;
cout << "Please Enter your age: ";
cin >> input;
of << input << endl;
of.close();
ifstream ifs;
string line;
ifs.open("testout.txt");
cout << "Reading from a text file:" << endl;
while (getline (ifs,line))
{
cout << line << endl;
}
ifs.close();
return 0;
}

JNTUHCEH Page 95
OUTPUT:
Writing to a text file:
Please Enter your name: Sairam Balu
Please Enter your age: 18
Reading from a text file:
Sairam Balu
18

JNTUHCEH Page 96
35. Write a C++ program to copy the contents of one file into
another.
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
int main()
{
ifstream fs;
ofstream ft;
char ch, fname1[20], fname2[20];
cout<<"Enter Source File Name With Extension : ";
gets(fname1);
fs.open(fname1);
if(!fs)
{
cout<<"Error In Opening Source File..!!";
getch();
exit(1);
}
cout<<"Enter Destination File Name With Extension : ";
gets(fname2);
ft.open(fname2);
if(!ft)
{
cout<<"Error In Opening Target File..!!";
fs.close();
getch();
exit(2);
}
while(fs.eof()==0)
{
fs>>ch;

JNTUHCEH Page 97
ft<<ch;
}
cout<<"File Copied Successfully..!!";
fs.close();
ft.close();
getch();
}

JNTUHCEH Page 98
OUTPUT:
Enter Source File Name With Extension : textout.txt
Enter Destination File Name With Extension : text_file.txt
File Copied Successfully..!!

The contents of the text file named textout are copied to the file with name
text_file.

JNTUHCEH Page 99
36. Write a C++ program to illustrate the use of member functions
(tellg,seekg) to obtain the size of a file.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
long begin,end;
ifstream ifs("test.txt");
begin=ifs.tellg();
ifs.seekg(0,ios::end);
end=ifs.tellg();
ifs.close();
cout<<"size is : "<<(end-begin)<<"bytes"<<endl;
return 0;
}

JNTUHCEH Page 100


OUTPUT:
Let us consider the file test contains the data of “hi sai”, then the output is
Size is : 6 bytes

JNTUHCEH Page 101


37. Write a C++ program to count the number of blank spaces
present in a text file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream fin;
fin.open(“blankspace.txt");
char ch;
int count=0;
while(!fin.eof())
{
fin.get(ch);
if(ch==' ')
count++;
}
cout<<"Number of blank spaces in file are "<<count;
fin.close();
}

JNTUHCEH Page 102


OUTPUT:
Let us take a file with text “hi C++ how are you sairam” then output will be
as follows

Number of blank spaces in file are 6

JNTUHCEH Page 103

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy