Sei sulla pagina 1di 87

Program 1: Write a simple program using functions “cout and cin”.

Solution:
#include<iostream>
using namespace std;

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

cout<<"ENTER VALUES\n";
cin>>a>>b;

sum=a+b;
cout<<"\n sum of values="<<sum;

return 0;
}

OUTPUT:
Program 2: WAP to add, multiply, divide numbers given by the user.
Solution: #include<iostream>
using namespace std;

int main()
{
int ch,y;
float a,b,res;

do{
cout<<"\nMENU DRIVEN \n 1.Addition\n 2.Multiplication\n
3.Division\n 4.Exit\n\n Enter your choice:";
cin>>ch;
cout<<"Enter two integer values\n";

cin>>a>>b;
switch(ch)
{
case 1: res=a+b;
cout<<"\n The required answer is: "<<res;
break;
case 2: res=a*b;
cout<<"\n The required answer is: "<<res;
break;
case 3: if(a>b)
res=a/b;
else
res=b/a;
cout<<"\n The required answer is: "<<res;
break;
default: break;//cout<<"Wrong choice";
}

cout<<"\nDo you want to continue? Press 1 if yes.";


cin>>y;
}while(ch!=4 && y==1);

return 0;
}
OUTPUT:
Program 3: WAP to find smallest number out of two inputs sing cin and cout.
Solution: #include<iostream>
using namespace std;

int main()
{
int a, b;

cout<<"enter the nos:";


cin>>a>>b;

if(a>b)
cout<<"Greater no. is"<<a;
else
cout<<"Greater no. is"<<b;
return 0;

OUTPUT:
Program 4: WAP in C++ to read the values of a,b,c and display the value of x where x= a/b-c
Solution: #include<iostream>
using namespace std;
int main()
{
int a,b,c;
float x;

cout<<"enter value of a: ";


cin>>a;

cout<<"enter value of b: ";


cin>>b;

cout<<"enter value of c: ";


cin>>c;

x=(a/b)-c;
cout<<"value of x : "<<x;
return 0;
}

OUTPUT:
Program 5: WAP a program that generates the following table
1990 135
1991 7290
1992 11300
1993 16200

Solution: #include<iostream>
using namespace std;

int main()
{
cout<<"1990\t135\n1991\t7290\n1992\t11300\n1993\t16200";
return 0;
}

OUTPUT:
Program 6: WAP that take input about you and produces output describing yourself. ( name,
gender, dob, phone, number, hobbies, quote).
Solution:
#include<iostream>
using namespace std;

int main()
{
char name[30],g[10],dob[20],hobb[30],quote[100];
int num;
cout<<"Enter your name :";
cin.get(name,20);
cin.ignore(1);
cout<<"Enter your gender :";
cin.get(g,10);
cin.ignore(1);
cout<<"Enter your dob :";
cin.get(dob,20);
cin.ignore(1);
cout<<"Enter your hobbies :";
cin.get(hobb,30);
cin.ignore(1);
cout<<"Enter your phone number :";
cin>>num;
cin.ignore(1);
cout<<"Enter your Quote :";
cin.get(quote,100);
cin.ignore(1);
return 0;
}

OUTPUT:
Program 7: WAP to create class ACCOUNT.
Solution: #include <iostream>
#include <conio.h>
using namespace std;
class account
{ char acc_name[20],name[20];
int amount;
public:
void getdata()
{ cout<<"enter name of account holder:";
cin>>name;
cout<<"enter account name: ";
cin>>acc_name;
cout<<"enter amount to be deposit: ";
cin>>amount;
}
void showdata()
{ cout<<"name of account holder: "<<name<<endl;
cout<<"name of account: "<<acc_name<<endl;
cout<<"amount to be deposited: "<<amount<<endl;
}
};

int main()
{ account a1;
a1.getdata();
a1.showdata();
return 0;
}

OUTPUT:
Program 8: WAP in c++ to print first 10 multiples of n integer where n is to be entered by the
user.
Solution: #include<iostream>

using namespace std;

int main()
{
int n,res;
cout<<"Enter number";
cin>>n;

for(int i=1;i<=10;i++)
{
res=n*i;
cout<<res<<endl;
}
return 0;
}

OUTPUT:
Program 9: Delhi Vidyut Board charges 0.75 paisa for st 100 units 0.90 paisa for next 100
unit and 0 paisa for rest. Additionlly, if the bill amount s moe than 200, surcharge of Rs.25 is
also added to the bill. WAP to get no. of units from user and display the bill amount.
Solution: #include<iostream>
using namespace std;
int main()
{
float a,b;
cout<<"Enter the units :";
cin>>a;

if(a<=100)
b=a*0.75;
else if(a>100 && a<=200)
b=75+((a-100)*0.9);
else if(a>200)
b=165+((a-200)*1.20);
if(b>200)
b=b+25;
cout<<endl<<b;
return 0;
}
OUTPUT:
Program 10: WAP in C++ to convert string to upper or lower case.
Solution : /*ASCII value of lowercase char a to z ranges from 97 to 122
ASCII value of uppercase char A to Z ranges from 65 to 92
For conversion we are subtracting 32 from the ASCII value of input char.*/

#include<iostream>
#include<string.h>

using namespace std;

int main()
{
char str[30];
int i,ch;
cout<<"St]TRING CONVERSION \n 1.Convert Lower to Upper \n 2.Convert Upper to Lower
\n\nEnter your Choice : ";
cin>>ch;

switch(ch)
{
case 1: cout<<"Enter the string in Lowercase\n";
cin>>str;

for(i=0;i<=strlen(str);i++)
{
if(str[i]>=97 && str[i]<=122)
str[i]-=32;
}

break;

case 2: cout<<"Enter the string in Uppercase\n";


cin>>str;

for(i=0;i<=strlen(str);i++)
{
if(str[i]>=65 && str[i]<=92)
str[i]+=32;
}
break;

default: cout<<"Wrong choice";


break;
}
cout<<"\nString is converted in Uppercase and is : "<<str;
return 0;
}
OUTPUT:
Program 11: Create a class employee which have name, age and address of the employee.
Include functions getdata() and showdata(). Showdata takes the input from the user and
display on the monitor Name:
Age:
Address:

Solution: #include<iostream>
#include<string>
//#include<conio>

using namespace std;


class employee
{
private:
char name[25], address[30];
int age;
public:
void getdata()
{

cout<<"\n Enter the name : ";

cin>>name;

cout<<"\n enter the address : ";

cin>>address;

cout<<"\n Enter the age : ";

cin>>age;

}
void showdata()
{

cout<<"\n name :\t"<<name;

cout<<"\n address :\t"<<address;

cout<<"\n age :\t"<<age;


}

};

int main ()
{

employee e1;

e1.getdata();

e1.showdata();

return 0;

OUTPUT:
Program 12: WAP having function with reference. (as in class).
Solution: #include<iostream>
using namespace std;

void swapnum ( int *var1, int *var2 )


{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}
int main()
{
int num1 = 35, num2 = 45 ;
cout<<"Before swapping:";
cout<<"\nnum1 value is %d"<<num1;
cout<<"\nnum2 value is %d"<<num2;

/*calling swap function*/


swapnum( &num1, &num2 );

cout<<"\nAfter swapping:";
cout<<"\nnum1 value is %d"<<num1;
cout<<"\nnum2 value is %d"<<num2;

return 0;
}

OUTPUT:
Program 13: Write programs to implement following:
(a)Inline Functions
(b)Destructors
(c)Copy Constructor to copy one string to another

Solution:

(a)Inline Functions

#include <iostream>

using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}

int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;

return 0;
}

OUTPUT:

(b)Destructors

#include<iostream>
using namespace std;

class Line
{
public:
void setLength(double len);
double getLength(void);
Line();
~Line();

sprivate:
double length;
};

Line::Line(void)
{
cout<<"Object is being created"<<endl;
}
Line::Line(void)
{
cout<<"Object is being deleted"<<endl;

}
void Line::setLength(double len)
{
length=len;
}
double Line::getLength(void)
{
return length;
}
int main()
{
Line line;
line.setLength(6.0);
cout<<"Length of line :"<<line.getLine()<<endl;

return 0;
}

OUTPUT:
Program 14: WAP to use static data member to keep track of count of object created and
destroyed.

Solution: #include<iostream>
using namespace std;
class student
{
static int num;
char name;
int age;

public:
student()
{
num++;
cout<<"\n Number of objects exists: "<<num;
}

~student()
{
num--;
cout<<"\n Number of objects exists:"<<num;
}
};
int student:: num=0;
int main()
{
student n1,n2,n3;

cout<<"\n Press any key to destroy object";

return 0;
}

OUTPUT:
Program 15: Define a class city which has name and pin code. Define another class address
which has house no. and city of type city. Define constructor and the destructor and print ()
which prints the address. Create an object of type address in main () and print it.

Solution: #include<iostream>
using namespace std;

class city {
public:
char *name;
int pin;

public:
city()
{

}
city(char nm[],int pn)
{
name=nm;
pin=pn;
}
};

class address
{
public: city houseno,cty;

address(char ct[],int hn)


{ cty.name=ct;
houseno.pin=hn;
}

void print()
{ cout<<"\nCity name is :"<<cty.name<<endl;
cout<<"\npincode is :"<<houseno.pin<<endl;
}
};

int main()
{
address ad("delhi",23),ad1("Rohini",85);
ad.print();
ad1.print();

return 0;
}
OUTPUT:
Program 16: WAP of function overloading of sum function. One function can take two
integer variables, second three integer variables and one for three float variables.

Solution: #include <iostream>


using namespace std;

int sum(int, int);


int sum(int, int, int);
float sum(float, float, float);

int main(){
int n1, n2, n3, n4, n5;
float a,b,c;

cout<<"Enter two integer numbers: ";


cin>>n1>>n2;

cout<<"Sum of the Entered numbers is : "<<sum(n1, n2)<< endl;

cout<<"Enter three integer numbers: ";


cin>>n3>>n4>>n5;

cout<<"Sum of the Entered numbers is : " <<sum(n3, n4, n5)<< endl;

cout<<"\nEnter three float numbers :";


cin>>a>>b>>c;

cout<<"Sum of the Entered numbers is : " <<sum(a, b, c)<< endl;


return 0;
}
int sum(int x, int y){
return x+y;
}

int sum(int x, int y, int z){


return x+y+z;
}

float sum(float x, float y, float z){


return x+y+z;
}
OUTPUT:
Program 17: WAP for temperature conversion using function overloading.

Solution: #include<iostream>
using namespace std;

class converter
{
float Far=0,Cel=0,temp=0;
public:
void c_temp(double Far)
{
Cel= ((Far-32)*5)/9;
temp=Cel;

cout<<"\n\nTemperature In Celsius is :"<<temp<<" degree C"<<endl;


temp=0;
}

void c_temp(int Cel)


{
Far=(Cel*1.8)+32;
temp=Far;

cout<<"\n\nTemperature In Farenhite is :"<<temp<<" degree F"<<endl;


}
};

int main()
{
converter c;
c.c_temp(50.2);
c.c_temp(50);
return 0;
}

OUTPUT:
Program 18: WAP of operator overloading for class distance having data members’ feet and
inches and overload +, +=, =, <, << operators.

a) Using Assignment operator (=):


#include <iostream>
using namespace std;

class Distance {
private:
int feet;
int inches;

public:

Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
void operator = (const Distance &D ) {
feet = D.feet;
inches = D.inches;
}

// method to display distance


void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;
}
};

int main() {
Distance D1(11, 10), D2(5, 11);

cout << "First Distance : ";


D1.displayDistance();
cout << "Second Distance :";
D2.displayDistance();

D1 = D2;
cout << "First Distance :";
D1.displayDistance();
return 0;
}

OUTPUT:

b) Using Input/Output Operators ( << / >> ):

#include <iostream>
using namespace std;

class Distance {
private:
int feet;
int inches;

public:

Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output, const Distance &D ) {
output << "F : " << D.feet << " I : " << D.inches;
return output;
}

friend istream &operator>>( istream &input, Distance &D ) {


input >> D.feet >> D.inches;
return input;
}
};

int main()
{
Distance D1(11, 10), D2(5, 11), D3;

cout << "Enter the value of object : " << endl;


cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;

return 0;
}

c) Using Relational Operator (<):


#include<iostream>
using namespace std;

class dist
{
int feet;
int inches;
public:
dist(int x, int y)
{
feet=x;
inches=y;
}
void display()
{
cout<<"Feet: "<<feet<<"Inches : "<<inches<<endl;
}

bool operator < (dist d)


{
if(feet<d.feet)
{
return true;
}
if(inches<d.inches)
{
return true;
}
return false;
}
};

int main()
{
dist d1(11, 10), d2(5, 11);
cout<<"First distance : "<<endl;
d1.display();

cout<<"Second distance : "<<endl;


d2.display();

if(d1<d2)
cout<<"D1 is less than D2"<<endl;
else
cout<<"D1 is greater than D2 "<<endl;
return 0;
}

OUTPUT:
d) Using Binary Operator (+):

#include <iostream>

using namespace std;

class Distance {
public:
int feet, inch;
Distance()
{
this->feet = 0;
this->inch = 0;
}

Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}

Distance operator+(Distance& d2)


{

Distance d3;
d3.feet = this->feet + d2.feet;
d3.inch = this->inch + d2.inch;

return d3;
}
};

int main()
{

Distance d1(8, 9);


cout<<" First distance : \n Feet:"<<d1.feet;
cout<<"\n Inches :"<<d1.inch;

Distance d2(10, 2);

Distance d3;

d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

OUTPUT:

e) Using Operator (+=):

#include<iostream>
using namespace std;

class Distance
{
int feet;
int inches;
public:
Distance()
{
feet=0;
inches=0;
}
Distance(int a, int b)
{
feet=a;
inches=b;
}
void display()
{
cout<<"Feet :"<<feet<<endl;
cout<<"\nInches :"<<inches<<endl;
}
void operator+=(Distance &d)
{
feet+=d.feet;
inches+=d.inches;
}
};

int main()
{
Distance d1(11,10), d2(5,11);
cout<<"First distance :"<<endl;
d1.display();
cout<<"Second Distance :"<<endl;
d2.display();

d1+=d2;
cout<<"First distance :"<<endl;
d1.display();
return 0;
}

OUTPUT:
Program 19: WAP of prefix/postfix increment and decrement operator.

Solution:
#include<iostream>
using namespace std;

class op
{
int x=10, y=6;
public:
void op1()
{
cout<<"Use Of Increment Operator :\n 1. Postfix Increment :"<< x++
<<"\n 2. Prefix Increment : "<< ++x <<endl;
}
void op2()
{
cout<<"Use Of Decrement Operator :\n 1. Postfix Decrement :"<< y--
<<"\n 2. Prefix Decrement : "<< --y <<endl;
}
};

int main()
{
op obj;
obj.op1();
cout<<"\n";
obj.op2();
return 0;
}

OUTPUT:
Program 20: WAP to declare array of distance class and overload subscript operator [].

Solution:
#include <iostream>
#include <stdlib.h>
using namespace std;

const int MAX=5;


class MyArray

{ private:
int Arr[MAX];
int size;
public:
MyArray(int s, int v)

{ if(s>MAX)
{ cout<<endl<<"This is beyond maximum size";
exit(1);
}

size = s;
for(int i=0;i<size;i++)
Arr[i] = v;
}
int& operator[](int i)
{

if( (i<0) || (i>=size) )


{
cout<<endl<<"Error: Array out of bound";
exit(1);
}
return Arr[i];
}
};

int main()
{
int i=0;
MyArray arr(3,0);

for(i=0;i<3;i++)
arr[i] = i*20;
cout<<"Array elements are:"<<endl;
for(i=0;i<3;i++)
{
int VAL = arr[i];
cout<<VAL<<endl;
}

return 0;
}

OUTPUT:
ASSIGNMENT 2
1. Write a program in C++ using the concept of
a) Multiple inheritance
b) Multilevel inheritance (Refer ques. 14.16 given in the official group of MCA).
c) Hierarchical inheritance
d) Multipath inheritance (Refer ques. 14.17 given in the official group of MCA).
e) Hybrid inheritance

Solution:

a) Multiple inheritance:
#include<iostream>
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 :\n 1. Marks of first subject :";
cin >> m1;
cout << "\n 2. Marks of second subject :";
cin >> m2;
}
};

class sports {
protected:
int smarks;
public:

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

}
};

class statement : public student, public sports {


int tot, avg;
public:

void display() {
tot = (m1 + m2 + smarks);
avg = tot / 3;
cout << "\n\nRoll No : " << rno << "\nTotal : " << tot;
cout << "\nAverage : " << avg<<endl;
}
};

int main() {

statement obj;
obj.get();
obj.getsmarks();
obj.display();

return 0;
}

OUTPUT:
b) Multilevel inheritance:
#include<iostream>
using namespace std;

class student
{
int roll;
char name[20],course[5];
public:
void getdetails()
{
cout<<"Enter roll :";
cin>>roll;
cout<<"Enter name :";
cin>>name;
cout<<"Enter course :";
cin>>course;
}

void showdetails()
{
cout<<"\nRoll : "<<roll;
cout<<"\nname : "<<name;
cout<<"\ncourse : "<<course;
}

};

class exam:public student


{
public:
int i,marks[4],tot=0;

void getdetails()
{
student::getdetails();
for(i=0;i<4;i++)
{
cout<<"\n\nSubject "<<i+1<<" Marks : ";
cin>>marks[i];
tot=tot+marks[i];
}
student::showdetails();
}
};
class result:public exam
{
public:

void getresult()
{
exam::getdetails();
cout<<"\nTotal marks"<<tot<<endl;
}
};

int main()
{
cout<<"Multilevel Inheritance\n\n";
cout<<"Student\n";
result r;
r.getresult();
return 0;
}

OUTPUT:
c) Hierarchical inheritance:
#include <iostream>
using namespace std;

class Number
{
private:
int num;
public:
void getNumber()
{
cout << "Enter an integer number: ";
cin >> num;
}

int returnNumber()
{
return num;
}
};

class Square:public Number


{
public:
int getSquare(void)
{
int num,sqr;
num=returnNumber(); //get number from class Number
sqr=num*num;
return sqr;
}
};

class Cube:public Number


{
private:

public:
int getCube(void)
{
int num,cube;
num=returnNumber(); //get number from class Number
cube=num*num*num;
return cube;
}
};
int main()
{
Square S;
Cube C;

S.getNumber();

cout << "Square of "<< S.returnNumber() << " is: " << S.getSquare() <<
endl;

C.getNumber();

cout << "Cube of "<< S.returnNumber() << " is: " << C.getCube() << endl;

return 0;
}

OUTPUT:
d) Multipath inheritance:
#include<iostream>
using namespace std;
class student
{
int roll;
char name[20],course[5];
public:
void getdetails()
{
cout<<"Enter roll : ";
cin>>roll;
cout<<"Enter name : ";
cin>>name;
cout<<"Enter course : ";
cin>>course;
}
void showdetails()
{
cout<<"\nRoll "<<roll;
cout<<"\nname "<<name;
cout<<"\ncourse "<<course;
}
};
class exam:public student
{
public:
int i,marks[3],tot=0;
void getdetails()
{
student::getdetails();
for(i=0;i<3;i++)
{
cout<<"\nSubject"<<i+1<<" Marks : ";
cin>>marks[i];
tot=tot+marks[i];
}

student::showdetails();
}
};
class sport:public student
{
int sw;
public:
void spweightage()
{
cout<<"\nEnter Weightage : ";
cin>>sw;
cout<<"\nSport Weightage : "<<sw;

}
};
class result:public exam,public sport
{
public:
void getresult()
{
exam::getdetails();
sport::spweightage();
cout<<"\ntotal marks are : "<<tot;
}
};
int main()
{
cout<<"Multipath Inheritance\n\n";
cout<<"Student\n";
result res;
res.getresult();
return 0;

}
OUTPUT:
e) Hybrid inheritance:

#include<iostream>
using namespace std;

class A
{
protected:
A() { cout << "A's constructor called" << endl; }
};
class B:public A
{
public:
B() { cout << "B's constructor called" << endl; }
};

class C:public A {
public:
C() { cout << "C's constructor called" << endl; }
};

class D: public B {
public:
D() { cout << "D's constructor called" << endl; }
};
class E: public B {
public:
E() { cout << "E's constructor called" << endl; }
};
class F: public D
{
public:
F() { cout << "F's constructor called" << endl; }
};

int main ()
{
cout<<"Hybride Inheritance\n\n";
F obj; return 0;

OUTPUT

:
Program 2: Implement the following class hierarchy. Define all the three classes and write
a program to create, update and display the information of each class. Assume attributes for
each class yourself.

PERSON

STUDENT EMPLOYEE

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

class Person {
int eno;
char name[20], des[20];
// Private members cannot call from outside class.
public:
void getPersonDetails() {
cout << "\nEnter the Person number:";
cin>>eno;
cout << "Enter the Person name:";
cin>>name;
cout << "Enter the Person designation:";
cin>>des;
}

void person_display() {
cout <<"\nPerson number:"<<eno;
cout <<"\nPerson name:"<<name;
cout <<"\nPerson designation:"<<des;
}
};

class Employee : private Person {


//Private Base Class, We cannot access outside the dervied Class
float bp, hra, da, pf, np;
public:

void getEmployeeDetails() {
getPersonDetails();
cout << "Enter the Basic pay:";
cin>>bp;
cout << "Enter the Humen Resource Allowance:";
cin>>hra;

calculate();
}

void calculate() {
np = bp + hra;
}

void employee_display() {
person_display();
cout <<"\nEmployee Basic pay:"<<bp;
cout <<"\nEmployee Humen Resource Allowance:"<<hra;

}
};

class Student : private Person {


char college[20], course[20];
public:
void getStudentDetails() {
getPersonDetails();
cout << "Enter the Student college Name:";
cin>>college;
cout << "Enter the Student course Name:";
cin>>course;
}

void student_display() {
person_display();
cout <<"\nStudent college Name:"<<college;
cout <<"\nStudent IFSC:"<<course<<endl;
}
};

int main() {
int i, n;
char ch;
Student s[10];
Employee e[10];
cout << "Simple Hierarchical Inheritance Example Program : Payroll System
\n";

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


cin>>n;
for (i = 0; i < n; i++) {
cout << "\nStudent Details # "<<(i+1)<<" : ";
s[i].getStudentDetails();
}

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


s[i].student_display();
}

cout << "\n\nEnter the number of Employee:";


cin>>n;
for (i = 0; i < n; i++) {
cout << "\nEmployee Details # "<<(i+1)<<" : ";
e[i].getEmployeeDetails();
}

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


e[i].employee_display();
}

return 0;
}
OUTPUT:
Program 3: WAP of Hybrid inheritance using virtual base class to remove ambiguity.
Solution: #include<iostream>
using namespace std;

class ClassA
{
public:
int a;
};

class ClassB : virtual public ClassA


{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};

class ClassD : public ClassB, public ClassC


{
public:
int d;
};

int main()
{

ClassD obj;

obj.a = 10; //Statement 3


obj.a = 100; //Statement 4

obj.b = 20;
obj.c = 30;
obj.d = 40;

cout<< "\n A : "<< obj.a;


cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d<<endl;
return 0;

}
OUTPUT:
Program 4:
a.) WAP of pure virtual function use pointer to objects too.
b.) WAP to store and concatenate two strings. Show the use of various string functions like
capacity, push_back, resize etc.

Solution:
a) #include<iostream>
using namespace std;

class Base
{
public:
virtual void show() = 0;
};
void Base :: show()
{
cout << "Pure Virtual definition\n";
}

class Derived:public Base


{
public:
void show()
{
cout << "\nImplementation of Virtual Function in Derived class\n\n";
}
};
int main()
{
Base *b;
Derived d;
b = &d;
b->show();

}
OUTPUT:
b) #include<iostream>
#include<string.h>

using namespace std;

int main()
{
string s1, s2, result;

cout << "Enter string s1: ";


getline (cin, s1);

cout << "\nEnter string s2: ";


getline (cin, s2);

result = s1 + s2;

cout << "\nConcatenation of the above two Strings = "<< result<<"\n\n";

cout<<"------Using Various String Functions--------";


cout<<" \n\n1. Length()";
cout<<"\n\n The length of the above string is : "<<result.length()<<endl;

cout<<" \n2. Capacity()";


cout<<"\n\n The capacity of the above string is :"<<result.capacity()<<endl;

cout<<" \n3. Push_back()";


result.push_back('!');
cout<<"\n\n"<<result<<endl;

cout<<" \n4. resize()";


unsigned s=result.size();

result.resize(s+2,'+');
cout<<"\n Increasing the size : "<<result;

result.resize(10);
cout<<"\n Decreasing the size :"<<result<<endl;
return 0;

}
OUTPUT:
Program 5: Write a program to read data from one file and display on the console. Also
calculate the length of the file.

Solution: #include<iostream>
#include<string.h>
#include<fstream>
using namespace std;

int main()
{
ifstream ifile;
int length;
char s[100], fname[20];
cout<<"Enter file name to read and display its content (like file.txt) : ";
cin>>fname;
ifile.open(fname);
if(!ifile)
{
cout<<"Error in opening file..!!";
//getch();
exit(0);
}
while(ifile.eof()==0)
{
ifile>>s;
cout<<s<<" ";
}
cout<<"\n";

length=ifile.tellg();
cout<<"\nLength of the file is : "<<length;
ifile.close();
return 0;
}
OUTPUT:
Program 6: Write a program open two file in read mode and write the data from both the
files in the third file.
Solution: #include<iostream>
#include<fstream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

int main()
{
ifstream ifiles1, ifiles2;
ofstream ifilet;
char ch, fname1[20], fname2[20], fname3[30];

cout<<"Enter first file name (with extension like file1.txt) : ";


gets(fname1);

cout<<"Enter second file name (with extension like file2.txt) : ";


gets(fname2);

cout<<"Enter Third File name of file : ";


gets(fname3);

ifiles1.open(fname1);
ifiles2.open(fname2);

if(!ifiles1|| !ifiles2)
{
cout<<"Error Message "<<endl;
cout<<"Press any key to exit..."<<endl;

exit(0);
}

ifilet.open(fname3);

if(!ifilet)
{
cout<<"Error Message "<<endl;
cout<<"Press any key to exit..."<<endl;

exit(0);
}

cout<<endl<<"Contents of File 1"<<endl;


while(ifiles1.eof()==0)
{
ifiles1>>ch;
cout<<ch;
ifilet<<ch;
}

cout<<endl<<"Contents of File 2"<<endl;

while(ifiles2.eof()==0)
{
ifiles2>>ch;
cout<<ch;
ifilet<<ch;
}

cout<<"The two files were merged into "<<fname3<<" file


successfully..!!"<<endl;

ifiles1.close();
ifiles2.close();
ifilet.close();

ifiles1.open(fname3);

cout<<"Contents of File 3"<<endl;

while(ifiles1.eof()==0)
{
ifiles1>>ch;
cout<<ch;
}
return 0;
}
OUTPUT:
Program 7: WAP of Exception class.

Solution: #include<iostream>
using namespace std;

class Divide
{
int num,num1,exc=1;
public:
void getData()
{
cout<<"Enter 2 Values"<<endl;
cin>>num>>num1;

if(num1==0)
{
throw exc;
}
}

double div()
{
double div;

try
{
div = num/num1;
return div;
}

catch(int exc)
{
cout<<"cannot div. by zero";
exit(1);
}
}
};

int main()
{
Divide P,Q;

P.getData();

cout<<P.div();

return 0;
}
OUTPUT:

Program 8: Implement and exception handling mechanism which reports stack full and
empty mechanism for a class called stack.
Program 9: WAP of template function.
Solution: #include <iostream>
#include <string>
using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b)
{
return a < b ? b:a;
}
int main ()
{
int i = 39;
int j = 20;
cout << "Max(i, j): " << Max(i, j) << endl;
double f1 = 13.5;
double f2 = 20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl;
string s1 = "Hello";
string s2 = "World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl;
return 0;
}

OUTPUT:

Program 10: WAP of template class.

Solution: #include <iostream>


using namespace std;

template <class T>


T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;

cout << Large(i1, i2) <<" is larger." << endl;


cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;

cout << Large(f1, f2) <<" is larger." << endl;


cout << "\nEnter two characters:\n";
cin >> c1 >> c2;

cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}

OUTPUT:

Program 11: WAP of stack using template. Write a Stack Class. Create the Stack using
different option, Empty Stack, Stack with one item and stack with multiple items. Write the
function to add and delete item in the stack. Verify if the Stack is full or empty at the time of
addition and deletion of items.

Solution: #include <iostream>


#include <vector>
#include <cstdlib>
using namespace std;

template <class T>

class Stack
{
private:
vector<T> elems;
public:
void push(T const&);
void pop();
T top() const;

bool empty() const


{
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem)
{
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop ()
{
if (elems.empty())
{
throw out_of_range("Stack<>::pop(): empty stack");
}
elems.pop_back();
}
template <class T>
T Stack<T>::top () const
{
if (elems.empty())
{
throw out_of_range("Stack<>::top(): empty stack");
}
return elems.back();
}

int main()
{
try {
Stack<int> intStack;
Stack<string> stringStack;
intStack.push(7);

cout << intStack.top() <<endl;


stringStack.push("hello");

cout << stringStack.top() << std::endl;

stringStack.pop();
stringStack.pop();

} catch (exception const& ex)


{
cerr << "Exception: " << ex.what() <<endl;
return -1;
}
}
OUTPUT:

Program 12: WAP of singly linked list using template. Implement a Linked List Class write the
function to Insert and Delete the node at the provided position. Inherit the Linked List Class
in Stack Class using Private Inheritance and use the function Insert and Delete Node of the
Linked List class to implement the Push and Pop Functionality of Stack class.

Solution: #include<iostream>
#include<stdlib.h>
using namespace std;

template<class T>
class linklist
{
public:
T data;
linklist<T> *link;
};
template<class T>
class stack
{
private:
linklist<T> *first;
public:
stack();
~stack();
void createlist();
void deletion();
void insertion();
void display();
};
template<class T>

stack<T>::stack()
{ first=NULL; }

template<class T>
stack<T>::~stack()
{
linklist<T> *next;
while(first)
{
next=first->link;
delete first;
first=next;
}
}
template<class T>
void stack<T>::createlist()
{
T a;
linklist<T> *cur,*ptr;
cout<<"\nEnter data Of New Node OR Enter 0 for other option # ";
cin>>a;
while(a)
{
cur=new linklist<T>;
cur->data=a;
cur->link=NULL;
if(first==NULL)
first=cur;
else
ptr->link=cur;
ptr=cur;

cout<<"\nEnter data Of New Node OR Enter 0 for other option # ";

cin>>a;
}
}
template<class T>
void stack<T>::insertion()
{
linklist<T> *cur,*ptr;
T ele;
char ch;
ptr=first;
cur=new linklist<T>;
cout<<"\nEnter data Of New Node:";
cin>>cur->data;
cur->link=NULL;
cout<<"\n Do u wish to insert at the start [y/n]:";
cin>>ch;
if(ch=='Y'||ch=='y')
{
cur->link=first;
first=cur;
}
else
{
cout<<"\n Specify after which element do u want to insert :";
cin>>ele;
while(ptr!=NULL)
{
if(ptr->data==ele)
{
cur->link=ptr->link;

ptr->link=cur;
break;
}
else
{
ptr=ptr->link;
}
}
}
}
template<class T>
void stack<T>::deletion()
{
T ele;
char ch;
linklist<T> *ptr,*ptr1;
if(first==NULL)
{
cout<<"\nSorry list is empty.";
}
else
{
ptr=first;
cout<<"\nDo u want to delete first element? [y/n]:";
cin>>ch;
if(ch=='y'||ch=='Y')
{
first=first->link;
delete ptr;

}
else
{
cout<<"\nSpecify which element do u want to delete :";
cin>>ele;
while(ptr!=NULL)
{
if(ptr->link->data==ele)
{
ptr1=ptr->link;
ptr->link=ptr1->link;
delete ptr1;
return;
}
else
{
ptr=ptr->link;
}
}
}
}
}
template<class T>
void stack<T>::display()
{
linklist<T> *ptr;
if(first==NULL)
{
cout<<"\n Sorry list is empty..";

}
else
{
ptr=first;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->link;
}
}
}
int main()
{
int n;
stack <int> l;
l.createlist();
do
{
cout<<"\n1.Insertion \n2.Deletion \n3.Print List \n4.Exit \n";
cout<<"\n Enter your option : ";
cin>>n;
switch(n)
{
case 1: l.insertion();
break;
case 2: l.deletion();
break;
case 3: l.display();
break;
case 4:
exit(0);
break;
}
}while(n<=4);
return 0;
}
OUTPUT:
Program 13: WAP of Doubly linked list using template.

Solution: #include <stdio.h>


#include <iostream>
using namespace std;

int insertdata(int x);


void display();
void deleteint(int x);
void reversel();
int searchint(int x);

int compare_fn(int a,int b)


{
if(a>b)
return 1;
else if(b>a)
return -1;
}

int compare_no=1;

struct node
{
int data;
node *prev;
node *next;
};
node *top = NULL;
int main()
{
int ch,d,y;

char ans='y';
while(ans=='y')
{
cout<<"\n 1.Insert \n2. Delete \n3.Reverse \n4.EXIT\nEnter Choice : ";
cin>>ch;
if(ch==1)
{
cout<<"Enter An Element To be inserted : ";
cin>>d;
d=insertdata(d);
display();
}
else if(ch==2)
{
cout<<"Enter Element To Be Deleted : ";
cin>>d;
deleteint(d);
display();
}
else if(ch==3)
reversel();
else
return 0;
}
return 0;
}

int searchint(int x)
{
int count=0;
node *searchele=top;
while( searchele!=NULL)
{
if(compare_fn(x,searchele->data)==compare_no)
{
searchele=searchele->next;
count+=1;
}
else
break;
}
return count;
}

int insertdata(int x)
{
if(top==NULL)
{
top=new node;
top->data=x;
top->next=NULL;
top->prev=NULL;
}
else if(compare_fn(top->data ,x)==compare_no)
{
node *n=new node;
n->data=x;
n->next=top;
n->prev=NULL;
top->prev=n;
top=n;
}
else
{
int c=searchint(x);
node *insertele=top;
for(int i=0;i<c-1;i++)
insertele=insertele->next;
node *n=new node;
n->data=x;
node *b=insertele->next;
node *N =insertele;
n->prev=insertele;
n->next=b;
insertele->next=n;
if(b!=NULL)
b->prev=n;
}
}

void display()
{
cout<<"Element In The Linked List Are : ";
node *disp=top;
while(disp!=NULL)
{
cout<<" "<<disp->data;
if(disp->next==NULL)
{
break;
}
disp=disp->next;
}
}

void deleteint(int x)
{
node *del=top;
if(del->data == x)
{
if(del->next==NULL && del->prev==NULL)
{
top=NULL;
return;
}
del->next->prev=NULL;
top=del->next;
}
else
{
node *delsuc=del->next;
if(del==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
if(delsuc==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
while(delsuc->data != x)
{
del=del->next;
delsuc=delsuc->next;
if(del==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
if(delsuc==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
}
del->next=delsuc->next;
if(delsuc->next!=NULL)
delsuc->next->prev=del;
}
}

void reversel()
{
node *a=top;
node *b,*c,*d;
while(a!=NULL)
{
d=a;
c=a->next;
b=a->prev;
a->prev=a->next;
a->next=b;
a=c;
}
top=d;
cout<<"After Reversing the linked list";
display();
compare_no*=-1;
}

OUTPUT:

Program 14: WAP of Binary Search tree using template Write C++ code to perform following
operations on Binary Search Trees:
i) Addition of a node
ii) Deletion of a node
iii) Traversal
a) Pre-order
b) In-order
c) Post-order

Solution: #include <iostream>


#include <cstdlib>
using namespace std;
struct node
{
int info;
struct node *left;
struct node *right;
}*root;
class BST
{
public:
void find(int, node **, node **);
void insert(node *, node *);
void del(int);
void case_a(node *,node *);
void case_b(node *,node *);
void case_c(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
void display(node *, int);

BST()
{
root = NULL;
}
};
int main()
{
int choice, num;
BST bst;
node *temp;
while (1)
{
cout<<"-----------------"<<endl;
cout<<"Operations on BST"<<endl;
cout<<"-----------------"<<endl;
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Inorder Traversal"<<endl;
cout<<"4.Preorder Traversal"<<endl;
cout<<"5.Postorder Traversal"<<endl;
cout<<"6.Display"<<endl;
cout<<"7.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
temp = new node;
cout<<"Enter the number to be inserted : ";
cin>>temp->info;
bst.insert(root, temp);
case 2:
if (root == NULL)
{
cout<<"Tree is empty, nothing to delete"<<endl;
continue;
}
cout<<"Enter the number to be deleted : ";
cin>>num;
bst.del(num);
break;
case 3:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(root);
cout<<endl;
break;
case 4:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(root);
cout<<endl;
break;
case 5:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(root);
cout<<endl;
break;
case 6:
cout<<"Display BST:"<<endl;
bst.display(root,1);
cout<<endl;
break;
case 7:
exit(1);
default:
cout<<"Wrong choice"<<endl;
}
}
}

void BST::find(int item, node **par, node **loc)


{
node *ptr, *ptrsave;
if (root == NULL)
{
*loc = NULL;
*par = NULL;
return;
}
if (item == root->info)
{
*loc = root;
*par = NULL;
return;
}
if (item < root->info)
ptr = root->left;
else
ptr = root->right;
ptrsave = root;
while (ptr != NULL)
{
if (item == ptr->info)
{
*loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if (item < ptr->info)
ptr = ptr->left;
else
ptr = ptr->right;
}
*loc = NULL;
*par = ptrsave;
}
void BST::insert(node *tree, node *newnode)
{
if (root == NULL)
{
root = new node;
root->info = newnode->info;
root->left = NULL;
root->right = NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree->info == newnode->info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree->info > newnode->info)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert(tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
}
void BST::del(int item)
{
node *parent, *location;
if (root == NULL)
{
cout<<"Tree empty"<<endl;
return;
}
find(item, &parent, &location);
if (location == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (location->left == NULL && location->right == NULL)
case_a(parent, location);
if (location->left != NULL && location->right == NULL)
case_b(parent, location);
if (location->left == NULL && location->right != NULL)
case_b(parent, location);
if (location->left != NULL && location->right != NULL)
case_c(parent, location);
free(location);
}
void BST::case_a(node *par, node *loc )
{
if (par == NULL)
{
root = NULL;
}
else
{
if (loc == par->left)
par->left = NULL;
else
par->right = NULL;
}
}
void BST::case_b(node *par, node *loc)
{
node *child;
if (loc->left != NULL)
child = loc->left;
else
child = loc->right;
if (par == NULL)
{
root = child;
}
else
{
if (loc == par->left)
par->left = child;
else
par->right = child;
}
}
void BST::case_c(node *par, node *loc)
{
node *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc->right;
while (ptr->left != NULL)
{
ptrsave = ptr;
ptr = ptr->left;
}
suc = ptr;
parsuc = ptrsave;
if (suc->left == NULL && suc->right == NULL)
case_a(parsuc, suc);
else
case_b(parsuc, suc);
if (par == NULL)
{
root = suc;
}
else
{
if (loc == par->left)
par->left = suc;
else
par->right = suc;
}
suc->left = loc->left;
suc->right = loc->right;
}
void BST::preorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
cout<<ptr->info<<" ";
preorder(ptr->left);
preorder(ptr->right);
}
}
void BST::inorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;

}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->info<<" ";
inorder(ptr->right);
}
}
void BST::postorder(node *ptr)
{
if (root == NULL)
{
cout<<"Tree is empty"<<endl;
return;
}
if (ptr != NULL)
{
postorder(ptr->left);
postorder(ptr->right);
cout<<ptr->info<<" ";
}
}
void BST::display(node *ptr, int level)
{
int i;
if (ptr != NULL)
{
display(ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<"Root->: ";
else
{
for (i = 0;i < level;i++)
cout<<" ";
}
cout<<ptr->info;
display(ptr->left, level+1);
}
}
OUTPUT:
Program 15: WAP of BFS using STL functions

Solution:
#include <iostream>

using namespace std;


int c = 0, t = 0;
struct node_info
{
int no;
int st_time;
}*q = NULL, *r = NULL, *x = NULL;
struct node
{
node_info *pt;
node *next;
}*front = NULL, *rear = NULL, *p = NULL, *np = NULL;
void push(node_info *ptr)
{
np = new node;
np->pt = ptr;
np->next = NULL;
if (front == NULL)
{
front = rear = np;
rear->next = NULL;
}
else
{
rear->next = np;
rear = np;
rear->next = NULL;
}
}
node_info *remove()
{
if (front == NULL)
{
cout<<"empty queue\n";
}
else
{
p = front;
x = p->pt;
front = front->next;
delete(p);
return(x);
}
}
void bfs(int *v,int am[][7],int i)
{
if (c == 0)
{
q = new node_info;
q->no = i;
q->st_time = t++;
cout<<"time of visitation for node "<<q->no<<":"<<q->st_time<<"\n\n";
v[i] = 1;
push(q);
}
c++;
for (int j = 0; j < 7; j++)
{
if (am[i][j] == 0 || (am[i][j] == 1 && v[j] == 1))
continue;
else if (am[i][j] == 1 && v[j] == 0)
{
r = new node_info;
r->no = j;
r->st_time = t++;
cout<<"time of visitation for node "<<r->no<<":"<<r->st_time<<"\n\n";
v[j] = 1;
push(r);
}
}
remove();
if (c <= 6 && front != NULL)
bfs(v, am, remove()->no);
}
int main()
{
int v[7], am[7][7];
for (int i = 0; i < 7; i++)
v[i] = 0;
for (int i = 0; i < 7; i++)
{
cout<<"enter the values for adjacency matrix row:"<<i+1<<endl;
for (int j = 0; j < 7; j++)
{
cin>>am[i][j];
}
}
bfs(v, am, 0);
return 0;
}
OUTPUT:

Program 16: WAP of DFS using STL functions

Solution: #include<iostream>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
int main()
{
int m;
cout <<"Enter no of vertices:";
cin >> n;
cout <<"Enter no of edges:";
cin >> m;
cout <<"\nEDGES \n";
for(k=1; k<=m; k++)
{
cin >>i>>j;
cost[i][j]=1;
}
cout <<"Enter initial vertex to traverse from:";
cin >>v;
cout <<"DFS ORDER OF VISITED VERTICES:";
cout << v <<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n; j>=1; j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v << " ";
k++;
visit[v]=0;
visited[v]=1;
}
return 0;
}

OUTPUT:

Potrebbero piacerti anche