Você está na página 1de 45

1

CONSTRUCTOR AND DESTRUCTOR

AIM:
To write a C++ program to illustrate the usage of constructors and destructors.

ALGORITHM:
Step-1: Create a class named myclass with data members as two integers a and b.
Step-2: Define a constructor for the class to initialize these variables.
Step-3: Define a destructor.
Step-4: Define a member function named show() to display the sum of two numbers.
Step-5: Create an object for myclass inside main function.
Step-7: Call the object.show() function from main function.
Step-8: The sum of two numbers is displayed and while closing the program the destructor
is called to deallocate the memory occupied by two integers.

PROGRAM:
#include <iostream.h>
#include <conio.h>
class myclass
{
int a,b;
public:
myclass(); // constructor
~myclass(); // destructor - no need to call the destructor
void show();
};
myclass::myclass()
{
cout << "Now inside constructor:\n";
a = 30;
b = 20;
cout<<”\n Variable initialized”;
}

myclass::~myclass()
{
//invoked before removing objects from memory
cout << "Destructing...\n";
cout<<”Destructed”;
}
void myclass::show()
{
cout << "\n A =" << a << endl << "B =" << b << endl;
cout << "Sum is " << a+b << endl;
}
void main()
{
2

myclass ob;
clrscr();
ob.show();
getch();
}

COPY CONSTRUCTOR

AIM:
To write a C++ program to illustrate copy constructor concept.

ALGORITHM:

Step-1: Create a class named copy with data members as two integer variables fact and var.
Step-2: Define the constructor to initialize the var value.
Step-3: Define the member function calculate() that computes the factorial of the given
number and returns the result to the main function.
Step-4: In main function, create an object for the class by passing the number as an
argument.
Step-5: Create another object and copy the first object to this object.
Step-6: Call the calculate() function using both the objects.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class copy
{ int var,fact;
public:
copy(int temp)
{ var = temp;
}
int calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
3

{ clrscr();
int n;
cout<<"\nEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n"<<" Factorial of "<<n<<" is:"<<obj.calculate();
cout<<"\n"<<" Factorial of "<<n<<" is:"<<cpy.calculate();
getch();
}

FRIEND FUNCTION

AIM:
To write a C++ program to access a private data from non-member function to the class.
ALGORITHM:
Step-1: Create a class called account with private data members as name, accno,
and balance.
Step-2: Define a member function named read() to get the input for the above data
members.
Step-3: Define a non-member function named showbalance() which displays the
balance available in the given account number.
Step-4: Since it is a non-member function, declare the showbalance() function as
friend inside the account class.
Step-5: Create an object for the account class as A inside main() function.
Step-6: Call the read() function for object A from main() function.
Step-7: Now call the showbalance() function by passing A as an actual argument
from main() function. This function displays the balance available in A
object’s account.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class Account
{ private:
char name[25];
int accno;
float balance;
public:
void read()
4

{
cout<< " \n Enter Customer Name: ";
cin>>name;
cout<< "\n Enter his/her account no: " ;
cin>>accno;
cout<<"\n Enter the amount to be deposited in his/her account: ";
cin>>balance;
}
friend void showbalance(Account);
};
void showbalance(Account acc)
{
cout<< "\n The balance of Acc No. " <<acc.accno<< " is Rs. " << acc.balance;
}
void main()
{ Account A1, A2;
clrscr();
A1.read();
A2.read();
showbalance(A1);
showbalance(A2);
getch();
}

FRIEND CLASS

AIM:
To write a C++ program to implement friend class concept.

ALGORITHM:
Step-1: Create a class named readint with data members as two floating point variables a
and b.
Step-2: Define the member function named read() inside readint class that gets the input for
the two variables.
Step-3: Create a new class named sum with data members as a float variable c.
Step-4: Now declare the class sum as a friend of class readint.
Step-5: Define a member function named add() inside sum class that adds the data members
of readint class and stores the result in sum class.
Step-6: Create objects for both the classes inside main function as r and s for readint and
sum classes respectively..
5

Step-7: Call the r.read() function and then s.add() from main function. This will display the
result of addition of two variables.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class readint
{ float a,b;
public:
void read()
{ cout<<"\n\nEnter the First Number : ";
cin>>a;
cout<<"\n\nEnter the Second Number : ";
cin>>b;
}
friend class sum;
};
class sum
{ public:
float c;
void add(readint rd)
{ c=rd.a+rd.b;
cout<<"\n\nSum="<<c;
}
};
void main()
{
int cont;
readint rd;
sum s;
clrscr();
rd.read();
s.add(rd);
getch();
}
6

INHERITANCE

AIM:
To write a C++ program to implement various inheritance types.

ALGORITHM:
Step-1: Create a class named Student with student_ID, Name, and Contact_No as its public
data members and a constructor to initialize the values..
Step-2: Create another class my_Information with member functions displaying the data.
Step-3: Inherit the Student class to my_Information class publicly to access the members of
Student class.

PROGRAM:

1.SINGLE INHERITANCE
#include<iostream.h>
#include<conio.h>
#include<string.h>
class Student
{
public:
int student_ID;
char name[15]; int contact_no;
public:
Student()
{
/*When object is created for derived class, the Base class constructor is called first by default…..*/
student_ID=1;
strcpy(name,"YOUR NAME");
contact_no=4288;
}
};
class my_Information: public Student
{
public:
void print_details()
{
cout<< "ID : "<<student_ID<<endl<< "Name: "<<name<<endl<< "Contact Number: "<<contact_no;
}
7

};
void main()
{ my_Information S1;
clrscr();
S1.print_details();
getch();
}

2.MULTILEVEL INHERITANCE:
ALGORITHM:
Step-1: Create a base class named grandparent with protected data member name.
Step-2: Create a middle-level derived class named parent with protected data member age
that derives the grandparent class publicly.
Step-3: Derive a class from parent class named child with member function
print_details().

PROGRAM:
#include<iostream>
#include<conio>
#include<string>
using namespace std;
class grandparent
{ protected:
char name[20];
grandparent()
{
strcpy(name,"grandparent_name");
}
void disp()
{
cout<<"\n Grandparent Name: "<<name;
}
};
class parent:public grandparent
{
protected:
int age;
public:
parent()
{
strcpy(name,"parent_name");
8

age=45;
}
void display()
{
cout<<"\n Parent Name: "<<name<<"\tAge: "<<age;
}
};
class child:public parent
{
public:
child()
{ strcpy(name,"Your_Name");
age=20;
}
void print_details()
{
disp();
cout<<endl;
display();
cout<<"\n";
cout<<endl<<"Name: "<<name<<"\tAge: "<<age;
}
};
void main()
{
child c;
clrscr();
c.print_details();
getch();
}
3. MULTIPLE INHERITANCE:
ALGORITHM:
Step-1: Create a class named M with an integer data member and a member function get_m().
Step-2: Create a class named N with an integer data member and a member function get_n().
Step-3: Create a class named P with a member function called display().
Step-4: Derive the class P from both M and N classes.
Step-5: In main function, create an object for class P and call the display() function using it.
Step-6: Inside display() function, compute the product of the data members of M and N classes.

PROGRAM:
9

#include<iostream.h>
#include<conio.h>
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;
public:
void get_n(int);
};
class P:public M, public N
{
public:
void display();
};
void M::get_m(int a)
{
m=a; }
void N::get_n(int b)
{
n=b;
}
void P::display()
{
cout<<"\n m= "<<m;
cout<<endl<<" n= "<<n;
cout<<endl<<" m*n="<<m*n;
}
void main()
{
P p1;
clrscr();
p1.get_m(10);
p1.get_n(20);
p1.display();
getch();
}
4. HIERARCHICAL INHERITANCE:
10

ALGORITHM:
Step-1: Create the base classes named red, yellow and blue with their constructors respectively.
Srep-2: Create a class named orange and publicly inherit the properties of red and yellow.
Step-3: Create a class named green and publicly inherit the properties of blue and yellow.
Step-4: Create a class named violet and publicly inherit the properties of red and blue.
Step-5: Create a class named reddishbrown and inherit the properties of orange and violet
publicly.
Step-6: Create a class named yelowishbrown and inherit the properties from green and orange
publicly.
Step-7: Create another class named bluishbrown by inheriting the properties of violet and green
publicly.
Step-8: In main function, create objects for all the level 2 derived classes.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class red
{
public:
red()
{
cout<<"\nRed ";
}
};

class yellow
{ public:
yellow()
{
cout<<"\nYellow ";
}
};
class blue
{
public:
blue()
{
cout<<"\nBlue ";
}
11

};
class orange: public red, public yellow
{
public:
orange()
{
cout<<" =Orange ";
}
};
class green:public blue, public yellow
{
public:
green()
{
cout<<" =Green ";
}
};
class violet:public red, public blue
{
public:
violet()
{
cout<<" =Violet ";
}
};
class reddishbrown:public orange, public violet
{
public:

reddishbrown()
{
cout<<" =Reddish Brown ";
}
};
class yellowishbrown:public green, public orange
{
public:
yellowishbrown()
{
cout<<" =Yellowish Brown ";
}
};
class bluishbrown:public violet, public green
{
12

public:
bluishbrown()
{
cout<<" =Bluish Brown ";
}
};
void main()
{
clrscr();
reddishbrown r;
bluishbrown b;
yellowishbrown y;
getch();
}
5. HYBRID INHERITANCE:
ALGORITHM:
Step-1: Create a class named Physique and derive it from Player.
Step-2: Create a class named Game and derive it from Physique and Location.
Step-3: Write two member functions to get and display the details of the data members of all the
classes using the object of Game.
PROGRAM:
#include<iostream.h>
#include<constream.h>
class PLAYER
{
protected:
char name[15];
char gender;
int age;
};
class PHYSIQUE:public PLAYER
{
protected:
float height;
float weight;
};
class LOCATION
{
protected:
char city[10];
char pin[7];
13

};
class GAME:public PHYSIQUE, public LOCATION
{
protected:
char game[15];
public:

void getdata()
{
cout<<"enter following information\n";
cout<<"NAME :";cin>>name;
cout<<"GENDER:";cin>>gender;
cout <<"AGE:";cin>>age;
cout<<"HEIGHT:";cin>>height;
cout<<"WEIGHT:";cin>>weight;
cout<<"CITY:";cin>>city;
cout<<"PINCODE:";cin>>pin;
cout<<"GAME:";cin>>game;
}
void show()
{
cout<<"\nentered information\n";
cout<<"\nNAME :";cout<<name;
cout<<"\nGENDER:";cout<<gender;
cout <<"\nAGE:";cout<<age;
cout<<"\nHEIGHT:";cout<<height;
cout<<"\nWEIGHT:";cout<<weight;
cout<<"\nCITY:";cout<<city;
cout<<"\nPINCODE:";cout<<pin;
cout<<"\nGAME:";cout<<game;
}
};
void main()
{
clrscr();
GAME G;
G.getdata();
G.show();
getch();
}
14

POLYMORPHISM

ALGORITHM:
Step-1: Create a class called shape with width and height as data members and a
constructor to initialize these variables and a member function called area().
Step-2: Create a class called rectangle and inherit from shape class. Redefine the area()
function to compute the area of a rectangle.
Step-3: Create a class called triangle and do the same as for rectangle.
Step-4: In main function, create a pointer object for base class and assign it with
addresses of objects of derived classes separately.

Step-5: Call the area() function for using shape class’ pointer object. We can clearly see
that irrespective of the derived class, the base class function overrides the derived
class.

PROGRAM:

#include<iostream.h>
#include<conio.h>
class Shape
{
protected:
int width, height;
public:
Shape( int a, int b)
{
width = a;
height = b;
}
void area()
{
cout << "Parent class area called" <<endl;
}
};
class Rectangle: public Shape
{ public:
Rectangle( int a, int b):Shape(a, b){ }
int area ()
{
cout << "Rectangle class area :";
return (width * height);
}
};
15

class Triangle: public Shape


{
public:
Triangle( int a, int b):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" ;
return (width * height / 2);
}
};
// Main function for the program
void main( )
{
Shape *shape;
clrscr();
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
cout<<rec.area()<<"\n";
cout<<tri.area();
getch();
}
FUNCTION OVERLOADING
ALGORITHM:

Step-1: Create a class named square.


Step-2:The class contains two member functions with the same name sqr() but with
different signatures.

Step-3:In main function, create an object for the square class and call the sqr() function
by passing different types of arguments each time.

PROGRAM:

#include<iostream.h>
#include<conio.h>
class Square
{
16

public:
int sqr(int a)
{
return a*a;
}
float sqr(float b)
{
return b*b;
}
};
void main()
{
clrscr();
Square s;
int p=5;
float q=2.5;
cout<<"\n Square of integers = "<<s.sqr(p);
cout<<"\n Square of float values= "<<s.sqr(q);
getch();
}
VIRTUAL FUNCTIONS
ALGORITHM:
Step 1: Create a class named base with data member as an integer b and initilaize the value
using constructor.
Step 2: Write a member function named display() and make it virtual.
Step-3: Create another class named derived with data member as an integer d and initialize
it using constructor.
Step-4: Rewrite the member function named display() in derived class.
Step-5: In main function, create a pointer object and a normal object for base class.
Step-6: Create an object for derived class.
Step-7: Now assign the address of the normal object of the base class to the pointer object
and invoke the display() function. Now the base class function is called.
Step-8: Reassign the pointer object of base class to the address of the object of derived
class and invoke the display() function. Now the derived class function is called.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{ int ib;
public:
base()
{ ib=20; }
17

virtual void display()


{
cout<<"\n ib= "<<ib;
}
};
class derived:public base
{
int id;
public:
derived()
{ id=40; }
void display()
{ cout<<"\nid= "<<id; }
};
void main()
{
base b,*bp;
derived d;
clrscr();
bp=&b;
bp->display();
bp=&d;
bp->display();
getch();
}
OVERLOADING UNARY OPERATOR

ALGORITHM:

Step-1: Create a class named num with private integer members a, b, c and d.
Step-2: Write a constructor for num class to initialize these variables.
Step-3: Define a member function called show() to display the values of these variables.
Step-4: Define a member function to overload the operator ++.
Step-5: In main function, create an object for num class and call show() function using it.
Step-6: Increment the object of num class. This step calls the overloading function.
Step-7: Again call the show() function using the same object after incrementing.
Step-8: The output shows that ++ operator had been overloaded and the data members are
incremented.

PROGRAM:
#include<iostream.h>
18

#include<constream.h>
class num
{
private:
int a,b,c,d;
public:
num(int j,int k,int m,int l)
{
a=j;
b=k;
c=m;
d=l;
}
void show(void);
void operator ++();
};
void num::show()
{ cout<<" A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d; }
void num::operator++()
{ ++a; ++b; ++c; ++d; }
void main()
{
clrscr();
num X(3,2,5,7);
cout<<"\n Before Increment of X:";
X.show();
++X;
cout<<"\n\n After Increment of X: ";
X.show();
getch();
}

2. OVERLOADING UNARY OPERATOR VIA NON-MEMBER FUNCTION

ALGORITHM:

Step-1: Create a class named num with private integer members a, b, c and d.
Step-2: Write a constructor for num class to initialize these variables and an empty
constructor.
Step-3: Define a member function called show() to display the values of these variables.
Step-4: Declare a friend function to overload the operator ++.
Step-5: In main function, create an object for num class and call show() function using it.
Step-6: Increment the object of num class and assign it to another object of same class. This
step calls the overloading function which is a non-member of the num class.
Step-7: Again call the show() function using the same object after incrementing.
19

Step-8: The output shows that ++ operator had been overloaded using a friend function and
the data members are incremented.

PROGRAM:

#include<iostream.h>
#include<constream.h>
class num
{
private:
int a,b,c,d;
public:
num() { }
num(int j,int k,int m,int l)
{ a=j; b=k; c=m; d=l; }
void show(void);
friend num operator ++(num);
};
void num::show()
{ cout<<" A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d; }
num operator++(num n)
{ ++n.a; ++n.b; ++n.c; ++n.d;
return n;
}
void main()
{
clrscr();
num X(3,2,5,7),Y;
cout<<"\n Before Increment of X:";
X.show();
Y=++X;
cout<<"\n\n After Increment of X: ";
Y.show();
getch();
}

OVERLOADING BINARY OPERATOR


1. OVERLOADING BINARY OPERATOR VIA MEMBER FUNCTION

ALGORITHM:

Step-1: Create a class named num with private integer members a, b, c and d.
20

Step-2: Define a member function input() to read these values.


Step-3: Define a member function called show() to display the values of these variables.
Step-4: Define a member function to overload the operator *.
Step-5: In main function, create three objects for num class and call input() function for two
objects using it.
Step-6: Multiply the objects of num class and store it in third object. This step calls the
overloading function.
Step-7: Again call the show() function using the third object after multiplying.
Step-8: The output shows that * operator had been overloaded.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class num
{ private:
int a,b,c,d;
public:
void input(void);
void show(void);
num operator*(num);
};
void num::input()
{
cout<<"\n Enter values for a,b,c and d: ";
cin>>a>>b>>c>>d;
}
void num::show()
{
cout<<" A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d<<"\n";
}
num num:: operator*(num t)
{
num tmp;
tmp.a=a*t.a;
tmp.b=b*t.b;
tmp.c=c*t.c;
tmp.d=d*t.d;
return tmp;
}
21

void main()
{
clrscr();
num X,Y,Z;
cout<<"\n Object X:";
X.input();
cout<<"\n Object Y:";
Y.input();
cout<<"\n X:";
X.show();
cout<<"\n Y:";
Y.show();
Z=X*Y;
cout<<"\n Z:";
Z.show();
getch();
}
2. OVERLOADING BINARY OPERATOR VIA NON-MEMBER FUNCTION

ALGORITHM:
Step-1: Create a class named num with private integer members a, b, c and d.
Step-2: Define a member function input() to read these values.
Step-3: Define a member function called show() to display the values of these variables.
Step-4: Define a friend function to overload the operator *.
Step-5: In main function, create two objects for num class and call input() function using one
object.
Step-6: Multiply the object of num class with an integer and assign it to the second object. This
step calls the overloading function.
Step-7: Again call the show() function using the second object after multiplying.
Step-8: The output shows that * operator had been overloaded.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class num
{ private:
int a,b,c,d;
public:
void input(void);
void show(void);
friend num operator*(int,num);
};
void num::input()
{ cout<<"\n Enter values for a,b,c and d: "; cin>>a>>b>>c>>d; }
22

void num::show()
{ cout<<" A= "<<a<<" B= "<<b<<" C= "<<c<<" D= "<<d<<"\n"; }
num operator*(int a,num q)
{
num tmp;
tmp.a=a*q.a;
tmp.b=a*q.b;
tmp.c=a*q.c;
tmp.d=a*q.d;
return tmp;
}
void main()
{
num X,Z;
int a=5;
clrscr();
cout<<"\n Object X:";
X.input();
cout<<"\n X:";
X.show();
Z=a*X;
cout<<"\n Z:";
Z.show();
getch();
}
CLASS TEMPLATES
ALGORITHM:
Step-1: Declare a template for the class.
Step-2: Create a class named sqr and write a constructor to find the square of the parameter
passed.
Step-3: In main function, create an integer object and pass an integer value to the
constructor.
Step-4: Again create a floating point object for the class and pass a float value to the
constructor.
Step-5: For this purpose we need not write two separate constructor functions instead we
can use class templates.

PROGRAM:
#include<iostream.h>
#include<conio.h>
template<class S>
class sqr
{
23

public:
sqr(S c)
{
cout<<"\n C= "<<c*c;
}
};
void main()
{
clrscr();
sqr <int> i(5);
sqr <float> f(5.5);
getch();
}
FUNCTION TEMPLATES

ALGORITHM:

Step-1: Create a template for the function.


Step-2: Write a show() function to display the values of the parameters passed
irrespective of the data type of each argument.
Step-3: In main() function, call the show() function by passing three different types of
arguments in any order.
Step-4: This illustrates the use of function template.

PROGRAM:
#include<iostream.h>
#include<conio.h>
template<class A, class B, class C>
void show(A c, B i, C f)
{
cout<<"\n C= "<<c<<" I= "<<i<<" F= "<<f;
}
void main()
{
clrscr();
show('A',8,50.25);
show(7,'B',70.89);
getch();
}
24

EXCEPTION HANDLING MECHANISM


ALGORITHM:

Step-1: Create a function named num to find whether the given number is a positive integer
or not.
Step-2: The number is checked within try block. If it is equal to zero then throw an integer
value.
Step-3: Else if it is greater than zero, then throw a character.
Step-4: Else throw a float value.
Step-5: Write suitable catches for each throw exception.
Step-6: In main() function, call the num() function with values like zero, a positive value
and a negative value.

PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void num(int k)
{
try
{
if(k==0)
throw k;
else if(k>0)
throw 'p';
else if(k<0)
throw 5.0;
cout<<"***try block***\n";
}
catch(char g)
{
cout<<"caught a positive value\n";
}
catch(int j)
{cout<<"caught a null value\n";
}
catch(double f)
{
cout<<"caught a negative value\n";
}
cout<<"***try catch***\n \n";
}
int main()
25

{
cout<<"demo of multiple catches\n";
num(0);
num(5);
num(-1);
getch();
return 0;
}

STANDARD TEMPLATE LIBRARY CONCEPT


ALGORITHM:
Step-1: Create an object v for the vector of integer data type.
Step-2: This program reads the integer values using push_back() function and stores it in
vector space.
Step-3: We can print the size of the vector using size() function.
Step-4: Also we can go to the beginning using begin() function.
Step-5: In order to access an element at particular position, we can give begin() function +
position value of the element.

Step-6: To delete an element, we can use erase() function.

PROGRAM:
#include<iostream.h>
#include<vectimp.h>
void display(vector<int> &v)
{
for(int i=0;i<v.size();i++)
{ cout<<v[i]<<" "; }
cout<<"\n";
}
void main()
{ clrscr();
vector<int> v;
cout<<"\n Initital size= "<<v.size() <<"\n";
int x;
cout<<"\n Enter five integer values:";
for(int i=0;i<5;i++)
{ cin>>x;
v.push_back(x);
}
cout<<"\n Size after adding 5 values:";
cout<< v.size()<<"\n";
cout<<"\n Current contents:\n";
26

display(v);
v.push_back(6.6);
cout<<"\n Size= "<<v.size() <<"\n";
cout<<"\n Contents now: \n";
display(v);
vector<int> :: iterator itr=v.begin();
itr=itr+3;
v.insert(itr,1,9);
cout<<"\n Contents after inserting: \n";
display(v);
v.erase(v.begin()+3, v.begin()+5);
cout<<"\n Contents after deletion: \n";
display(v);
cout<<"\n END \n";
getch();
}

FILE STREAM CLASSES


AIM:

To write a C++ program to write and read in a file using file stream classes.

ALGORITHM:
Step-1: Include the fstream directory.
Step-2: Open a text file for writing the contents using out function.
Step-3: Close the out file.
Step-4: Again open the same file using in function to read the contents.
Step-5: Close the in file.

PROGRAM:
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
char name[15];
int age;
ofstream out("text.txt");
cout<<"\n Name:";
cin>>name;
cout<<"\nAGE:";
cin>>age;
out<<name<<"\t";
27

out<<age<<"\n";
out.close();
ifstream in ("text.txt");
in>>name;
in>>age;
cout<<"\nNAME\t:"<<name<<"\n";
cout<<"age :"<<age;
in.close();
getch();
}
28

STACK APPLICATIONS-CONVERSION OF INFIX TO POSTFIX EXPRESSION


AIM:
To write a C++ program to convert infix to postfix expression using stack ADT.

ALGORITHM:

Step-1: Read the infix expression as string.


Step-2: Declare a stack array and a postfix array.
Step-3: Read the character one at a time.
Step-4: If it is an operand, then move it to the postfix array.
Step-5: If it is an open paranthesis, move it to the stack array.
Step-6: If it is a closing paranthesis, then pop characters from the stack to the postfix array
one by one until an open paranthesis is encountered.
Step-7: Else if it is an operator, check the precedence of stack[top] character and the input
character. Pop the stack operators until its precedence is greater or equal to the input
character.
Step-8: If the input expression reaches the null character, then check if the stack is empty. IF
not, pop all the characters from the stack to the postfix array.
Step-9: Display the postfix array.

PROGRAM:
#include<iostream.h>
#include<constream.h>
#include<stdlib.h>
#include <ctype.h>
class infix_to_postfix
{
public:
char stack[50], infix[50], postfix[50];
int top;
public:
infix_to_postfix()
{ top=-1; }
void get_expr()
{
cout<<”\n Enter the infix expression: ”;
cin>>infix;
}
void push(char element)
{ stack[++top] = element; }
char pop()
{ return (stack[top--]); }
int precedence(char element)
29

{
switch (element)
{
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
case ‘^’:
return 4;
default:
return 0;
}
}
void convert()
{ int i=0,k=0;
char element, ch;
while ((ch = infix[i++]) != '\0')
{ if (ch == '(')
push(ch);
else if (isalnum(ch))
postfix[k++] = ch;
else if (ch == ')')
{
while (stack[top] != '(' )
postfix[k++] = pop();
element = pop(); /* Remove ( */
}
else /* Operator */
{
while (precedence(stack[top]) >= precedence(ch))
postfix[k++] = pop();
push(ch);
}
}
while (stack[top] != '#') /* Pop from stack till empty */
postfix[k++] = pop();
postfix[k] = '\0';
};
30

void main()
{
infix_to_postfix in;
clrscr();
in.get_expr();
in.push('#');
cout<<"\n\nGiven Infix Expn: “<<in.infix;
in.convert();
cout<< “Postfix Expn: “<<in.postfix;
getch();
}

STACK APPLICATIONS – EVALUATING POSTFIX EXPRESSION

AIM:

To write a C++ program to evaluate the given postfix expression using Stack ADT.

ALGORITHM:

Step-1: Read a postfix expression.


Step-2: Initialize a stack array.
Step-3: Read one character at a time from the expression.
Step-4: If it is an operand, push it on to the stack.
Step-5: Else if it is an operator, then pop two operands from the stack, apply that operator
and push the result back to the stack.
Step-6: The final result will be available at stack[top].

PROGRAM:

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include <ctype.h>
class postfix
{ public:
int stack[50];
char post[50];
int top;
public:
postfix()
{ top=-1; }
void input()
{
cout<<"\n Enter the postfix expression:";
cin>>post;
}
31

void push(int element)


{ stack[++top]=element; }
int pop()
{ return(stack[top--]); }
void evaluate()
{
char ch;
int i=0,op1,op2;
while( (ch=post[i++]) != '\0')
{ if(isdigit(ch))
push(ch-'0'); /* Push the operand */
else
{ /* Operator, So pop two operands */
op2=pop();
op1=pop();
switch(ch)
{
case '+':
push(op1+op2);
break;
case '-':
push(op1-op2);
break;
case '*':
push(op1*op2);
break;
case '/':
push(op1/op2);
break;
}
}
}
}
};
void main()
{ /* Main Program */
postfix p;
clrscr();
p.input();
p.evaluate();
cout<< " \n Given Postfix Expn is : "<<p.post;
cout<< " \n Result after Evaluation : "<<p.stack[p.top];
getch();
}
32

BINARY SEARCH TREE AND TREE TRAVERSAL TECHNIQUES

AIM:
To write a C++ program to implement binary search tree ADT with its traversal techniques.
ALGORITHM:
Step-1: Create a class named BinarySearchTree with private data members as a structure
called tree_node, and member functions for insertion(), deletion(), tree traversals
such as inorder(), preorder(), and postorder().
Step-2: For inserting the elements, the first element will be made as a root node. For
inserting further elements, those elements that are less than the root node will be
moved to the left and those elements that are greater than the root node will be
moved to the right side of the root.
Step-3: For deleting the elements, first the tree is checked for its presence.
Step-3.1: If it is a leaf node, then delete it.
Step-3.2: If it is a parent with single child, then move the child to its position and
delete the parent.
Step-3.3: If it is a node with two children, then replace the node with the smallest
element of the right subtree or the largest element of the left subtree.
Step-4: For in-order traversal, visit the nodes in left, parent and right order.
Step-5: For pre-order traversal, visit the nodes in parent, left and right order.
Step-6: For post-order traversal, visit the nodes in left, right and parent order.

PROGRAM:
#include <iostream.h>
#include <conio.h>
#include<stdlib.h>
class BinarySearchTree
{ private:
struct tree_node
{
tree_node* left;
tree_node* right;
int data;
};
tree_node* root;
public:
BinarySearchTree()
{
root = NULL;
}
int isEmpty()
{
33

if(root==NULL) return 1;
else return 0;
}
void print_inorder();
void inorder(tree_node*);
void print_preorder();
void preorder(tree_node*);
void print_postorder();
void postorder(tree_node*);
void insert(int);
void remove(int);
};
// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
tree_node* t = new tree_node;
tree_node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
// is this a new tree?
if(isEmpty())
root = t;
else
{
//Note: ALL insertions are as leaf nodes
tree_node* curr;
curr = root;
// Find the Node's parent
while(curr)
{
parent = curr;
if(t->data > curr->data) curr = curr->right;
else curr = curr->left;
}
if(t->data < parent->data) parent->left = t;
else parent->right = t;
}
}
void BinarySearchTree :: remove(int d)
{
//Locate the element
34

int found = 0;
if(isEmpty())
{
cout<<" This Tree is empty! "<<endl;
return;
}
tree_node* curr;
tree_node* parent;
curr = root;
while(curr != NULL)
{
if(curr->data == d)
{
found = 1;
break;
}
else
{
parent = curr;
if(d>curr->data) curr = curr->right;
else curr = curr->left;
}
}
if(!found)
{
cout<<" Data not found! "<<endl;
return;
}
// 3 cases :
// 1. We're removing a leaf node
// 2. We're removing a node with a single child
// 3. we're removing a node with 2 children
// Node with single child
if((curr->left == NULL&&curr->right!=NULL)||(curr->left!=NULL&&curr->right == NULL))
{
if(curr->left == NULL && curr->right != NULL)
{
if(parent->left == curr)
{
parent->left = curr->right;
delete curr;
}
else
{
35

parent->right = curr->right;
delete curr;
}
}
else // left child present, no right child
{
if(parent->left == curr)
{
parent->left = curr->left;
delete curr;
}
else
{
parent->right = curr->left;
delete curr;
}
}
return;
}
//We're looking at a leaf node
if( curr->left == NULL && curr->right == NULL)
{
if(parent->left == curr) parent->left = NULL;
else parent->right = NULL;
delete curr;
return;
}
//Node with 2 children
// replace node with smallest value in right subtree
if (curr->left != NULL && curr->right != NULL)
{
tree_node* chkr;
chkr = curr->right;
if((chkr->left == NULL) && (chkr->right == NULL))
{
curr = chkr;
delete chkr;
curr->right = NULL;
}
else // right child has children
{
//if the node's right child has a left child
// Move all the way down left to locate smallest element
if((curr->right)->left != NULL)
36

{
tree_node* lcurr;
tree_node* lcurrp;
lcurrp = curr->right;
lcurr = (curr->right)->left;
while(lcurr->left != NULL)
{
lcurrp = lcurr;
lcurr = lcurr->left;
}
curr->data = lcurr->data;
delete lcurr;
lcurrp->left = NULL;
}
else
{
tree_node* tmp;
tmp = curr->right;
curr->data = tmp->data;
curr->right = tmp->right;
delete tmp;
}
}
return;
}
}
void BinarySearchTree :: print_inorder()
{
inorder(root);
}
void BinarySearchTree :: inorder(tree_node* p)
{ if(p != NULL)
{ if(p->left)
inorder(p->left);
cout<<" "<<p->data<<" ";
if(p->right)
inorder(p->right);
}
else
return;
}
void BinarySearchTree :: print_preorder()
{
preorder(root);
37

}
void BinarySearchTree :: preorder(tree_node* p)
{
if(p != NULL)
{
cout<<" "<<p->data<<" ";
if(p->left) preorder(p->left);
if(p->right) preorder(p->right);
}
else return;
}
void BinarySearchTree :: print_postorder()
{
postorder(root);
}
void BinarySearchTree :: postorder(tree_node* p)
{
if(p != NULL)
{
if(p->left) postorder(p->left);
if(p->right) postorder(p->right);
cout<<" "<<p->data<<" ";
}
else return;
}
void main()
{
clrscr();
BinarySearchTree b;
int ch,tmp,tmp1;
while(1)
{
cout<<endl<<endl;
cout<<" Binary Search Tree Operations "<<endl;
cout<<" ----------------------------- "<<endl;
cout<<" 1. Insertion/Creation "<<endl;
cout<<" 2. In-Order Traversal "<<endl;
cout<<" 3. Pre-Order Traversal "<<endl;
cout<<" 4. Post-Order Traversal "<<endl;
cout<<" 5. Removal "<<endl;
cout<<" 6. Exit "<<endl;
cout<<" Enter your choice : ";
cin>>ch;
switch(ch)
38

{
case 1 : cout<<" Enter Number to be inserted : ";
cin>>tmp;
b.insert(tmp);
break;
case 2 : cout<<endl;
cout<<" In-Order Traversal "<<endl;
cout<<" -------------------"<<endl;
b.print_inorder();
break;
case 3 : cout<<endl;
cout<<" Pre-Order Traversal "<<endl;
cout<<" -------------------"<<endl;
b.print_preorder();
break;
case 4 : cout<<endl;
cout<<" Post-Order Traversal "<<endl;
cout<<" --------------------"<<endl;
b.print_postorder();
break;
case 5 : cout<<" Enter data to be deleted : ";
cin>>tmp1;
b.remove(tmp1);
break;
case 6 :
exit(0);
break;
}
}
getch();
}

MINIMUM SPANNING TREE USING PRIM’S ALGORITHM

AIM:
To write a C++ program to develop the minimum spanning tree using Prim’s Algorithm.
ALGORITHM:
Step-1: Consider a graph having ‘n’ number of vertices and ‘e’ number of edges. Each edge
connects a maximum of two nodes. Each edge carries a weight on it.
Step-2: A minimum spanning tree is an acyclic connected graph with all vertices from the
given graph such that the total weight is minimum.
Step-3: Start from any vertex and identify the edge with minimum weight and reach the
destination vertex of that edge.
39

Step-4: Now assume that vertex as the starting point and repeat the step-3 until all the
vertices are visited.
Step-5: Note that the MST must be acyclic.

PROGRAM:
#include<iostream.h>
#include<conio.h>
struct node
{
int fr,to,cost;
}p[6];
int c = 0,temp1 = 0,temp = 0; //global declaration
void prims(int *a,int b[][7],int i,int j)
{ a[i] = 1;
while (c < 6)
{ int min = 999;
for (int i = 0; i < 7; i++)
{ if (a[i] == 1)
{ for (int j = 0; j < 7; )
{ if (b[i][j] >= min || b[i][j] == 0)
{ j++;
}
else if (b[i][j] < min)
{ min = b[i][j];
temp = i;
temp1 = j;
}
}
}
}
a[temp1] = 1;
p[c].fr = temp;
p[c].to = temp1;
p[c].cost = min;
c++;
b[temp][temp1] = b[temp1][temp]=1000;
}
for (int k = 0; k < 6; k++)
{
cout<<"source node:"<<p[k].fr<<endl;
cout<<"destination node:"<<p[k].to<<endl;
cout<<"weight of node"<<p[k].cost<<endl<<endl;
}
}
40

void main()
{
clrscr();
int a[7];
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for ( i = 0; i < 7; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{
cin>>b[i][j];
}
}
prims(a,b,0,0);
getch();
}
MINIMUM SPANNING TREE USING KRUSKAL’S ALGORITHM

AIM:
To write a C++ program to develop the minimum spanning tree using Kruskal’s Algorithm.
ALGORITHM:
Step-1: Consider a graph having ‘n’ number of vertices and ‘e’ number of edges. Each edge
connects a maximum of two nodes. Each edge carries a weight on it.
Step-2: A minimum spanning tree is an acyclic connected graph with all vertices from the
given graph such that the total weight is minimum.
Step-3: Sort the edges in increasing order of weights.
Step-4: Start from an edge having the least weight and add it to the MST.
Step-4: Similarly add the edges to the MST such that there is no cycle formed in the graph.
Step-5: Continue this process until all the vertices are visited once.

PROGRAM:
#include<iostream.h>
#include<conio.h>
#define INF 1000
char vertex[10];
int wght[10][10];
int span_wght[10][10];
int source;
41

struct Sort
{
int v1,v2;
int weight;
}que[20];
int n,ed,f,r;
int cycle(int s,int d)
{
int j,k;
if(source==d)
return 1;
for(j=0;j<n;j++)
if(span_wght[d][j]!=INF && s!=j)
{
if(cycle(d,j))
return 1;
}
return 0;
}
void build_tree()
{
int i,j,w,k,count=0;
for(count=0;count<n;f++)
{
i=que[f].v1;
j=que[f].v2;
w=que[f].weight;
span_wght[i][j]=span_wght[j][i]=w;
source=i;
k=cycle(i,j);
if(k)
span_wght[i][j]=span_wght[j][i]=INF;
else
count++;
}
}
void swap(int *i,int *j)
{
int t;
t=*i;
*i=*j;
*j=t;
}
void main()
42

{
int i,j,k=0,temp;
int sum=0;
clrscr();
cout<<"\n\n\tKRUSKAL'S ALGORITHM TO FIND SPANNING TREE\n\n";
cout<<"\n\tEnter the No. of Nodes : ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n\tEnter "<<i+1<<" node’s name : ";
cin>>vertex[i];
for(j=0;j<n;j++)
{
wght[i][j]=INF;
span_wght[i][j]=INF;
}
}
cout<<"\n\nGetting Weight\n";
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
cout<<"\nEnter 0 if path Doesn't exist between "<<vertex[i]<<" to "<<vertex[j];
cin>>ed;
if(ed>=1)
{
wght[i][j]=wght[j][i]=ed;
que[r].v1=i;
que[r].v2=j;
que[r].weight=wght[i][j];
if(r)
{
for(k=0;k<r;k++)
if(que[k].weight>que[r].weight)
{
swap(&que[k].weight,&que[r].weight);
swap(&que[k].v1,&que[r].v1);
swap(&que[k].v2,&que[r].v2);
}
}
r++;
}
}
clrscr();
cout<<"\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n";
43

cout<<"\n\tweight matrix\n\n\t";
for(i=0;i<n;i++,cout<<"\n\t")
for(j=0;j<n;j++,cout<<"\t")
cout<<wght[i][j];
build_tree();
cout<<"\n\n\t\tMINIMUM SPANNING TREE\n\n";
cout<<"\n\t\tLIST OF EDGES\n\n";
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(span_wght[i][j]!=INF)
{ cout<<"\n\t\t "<<vertex[i]<<"  "<< vertex[j]<<" = "<<span_wght[i][j];
sum+=span_wght[i][j];
}
cout<<"\n\n\t\tTotal Weight : "<<sum);
getch();
}

SHORTEST PATH ALGORITHM-DIJKSTRA’S ALGORITHM

AIM:
To write a C++ program to find the shortest path in the graph using Dijkstra’s algorithm.
ALGORITHM:
Step-1: Consider a graph having ‘n’ number of vertices and ‘e’ number of edges. Each edge
connects a maximum of two nodes. Each edge carries a weight on it.
Step-2: Read the source vertex.
Step-3: From the source vertex, identify the shortest path to each vertex in the graph.
Step-4: The path with minimum weight from the given source vertex to each other vertex in
the graph is printed.

PROGRAM:
#include<iostream.h>
#include<constream.h>
const int LEVELS = 8;
void Dijkstra(int *, int *, int[LEVELS][LEVELS]);
void main()
{
clrscr();
int L[LEVELS][LEVELS];
cout<<"\n Enter -1 if there is no edge the vertices..\n";
for ( int i = 0; i < LEVELS; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
44

for (int j = 0; j < LEVELS; j++)


{
cin>>L[i][j];
}
}
int Vertexes[LEVELS];
int Dist[LEVELS];
for ( i = 0; i < LEVELS; i++)
{
Vertexes[i] = i;
}
Vertexes[0] = -1;
Dist[0] = 0;
for ( i = 1; i < LEVELS; i++)
{
Dist[i] = L[0][i];
}
for (int curlevel = 1; curlevel < LEVELS; curlevel++)
{
Dijkstra(Vertexes, Dist, L);
cout << "Level " << curlevel << endl;
for (i = 0; i < LEVELS; i++)
{
cout << Dist[i] << " ";
}
cout << endl;
for ( i = 0; i < LEVELS; i++)
{
cout << Vertexes[i] << " ";
}
cout << endl;
}
getch();
}
void Dijkstra(int *Vertexes, int *Dist, int L[LEVELS][LEVELS])
{
int minValue = 32767;
int minNode = 0;
for (int i = 0; i < LEVELS; i++)
{
if (Vertexes[i] == -1) { continue;
}
if (Dist[i] > 0 && Dist[i] < minValue)
{
45

minValue = Dist[i];
minNode = i;
}
}
Vertexes[minNode] = -1;
for ( i = 0; i < LEVELS; i++)
{ if (L[minNode][i] < 0)
{ continue; }
if (Dist[i] < 0)
{ Dist[i] = minValue + L[minNode][i];
continue;
}
if ((Dist[minNode] + L[minNode][i]) < Dist[i])
{ Dist[i] = minValue + L[minNode][i];
} }

Você também pode gostar