You are on page 1of 60

Department of Computer Science and Engineering /Dr.N.G.P IT.

Dr. N.G.P. INSTITUTE OF TECHNOLOGY

Coimbatore-641048

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

LAB MANUAL

Programming and Data Structures II Laboratory (R2013)

Prepared by Approved by
Ms.T.Primya,AP/CSE HoD/CSE

1
Department of Computer Science and Engineering /Dr.N.G.P IT.

Ex. No: 1 CONSTRUCTOR AND DESTRUCTOR

AIM
To write a C++ program using constructor and destructor.
ALGORITHM
Step 1: Start the program.
Step 2: Create a class and declare the variables inside the class.
Step3: Create a default constructor and declare the variables .
Step 4: Create a destructor to destroy the object that are created by the constructor.
Step 5: Assign the values for variables
Step 6: Add the values and display the result
Step 6: Stop the program.
PROGRAM:
#include <iostream>
#include <iostream>
using namespace std;
class myclass
{
int a,b;
public:
myclass();
~myclass();
void show();
};
myclass::myclass()
{
cout<< "In constructor\n";
a = 30;
b = 20;
}
myclass::~myclass()
{
cout<< "Destructing...\n";
}
void myclass::show()
{
cout<< "A =" << a << endl << "B =" << b << endl;
cout<< "Sum is " << a+b << endl;
}
int main()
{
myclass ob;
ob.show();
return 0;

2
Department of Computer Science and Engineering /Dr.N.G.P IT.

}
OUTPUT:

COPY CONSTRUCTOR
AIM:
To write a C++ program using copy constructor
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class name as Copy with data members and member functions.
Step 3: The constructor Copy() with argument to assign the value.
Step 4: To cal the function calculate() do the following steps.
Step 5: For i=1 to var do
Step 6: Calculate fact*i to assign to fact.
Step 7: Increment the value as 1.
Step 8: Return the value fact.
Step 9: Print the result.
Step 10: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:

copy(int temp)
{
var = temp;
}

3
Department of Computer Science and Engineering /Dr.N.G.P IT.

double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
OUTPUT:

RESULT:
Thus the programs for constructor, destructor and copy constructor has been done

Ex.NO:2 FRIEND FUNCTION


AIM:
To find the mean value of a given number using friend function.

4
Department of Computer Science and Engineering /Dr.N.G.P IT.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class name as Base with data members and member functions.
Step 3: The function get() is used to read the 2 inputs from the user.
Step 4: Declare the friend function mean(base ob) inside the class.
Step 5: Outside the class to define the friend function and do the following.
Step 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
Step 7: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}

5
Department of Computer Science and Engineering /Dr.N.G.P IT.

OUTPUT:

Ex. No: 2.b FRIEND CLASS


AIM:
To write a C++ program using Friend Class
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class name as Base with data members and member functions.
Step 3: The function get() is used to read the 2 inputs from the user.
Step 4: Declare the friend class sum(base d in function add) inside the class.
Step 5: Outside the class to define the friend function and do the following.
Step 6: Return the result value (d.a+d.b)
Step 7: Stop the program.
PROGRAM
#include<iostream.h>
#include<conio.h>
class getinput
{
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;
};

6
Department of Computer Science and Engineering /Dr.N.G.P IT.

class sum
{
public:
float c;
void add(getinput d)
{
c=d.a+d.b;
cout<<"\n\nSum="<<c;
}
};
void main()
{
getinput d,rd;
sum s;
clrscr();
rd.read();
s.add(rd);
getch();
}
OUTPUT:

RESULT:
Thus the programs for friend function and friend class has been done

Ex. No: 3 SINGLE INHERITANCE


AIM:
To find out the student details using multiple inheritance.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class stu.

7
Department of Computer Science and Engineering /Dr.N.G.P IT.

Step 3: Declare and define the function get() to get the student details.
Step 4: Declare the derived class total.
Step 5: Declare and define the function get1() to get the marks.
Step 8: Declare the derived class object, call the functions get(),get1(),calculate[] and
display().
Step 9: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class stu
{
public:
int sno;
int tot;
char name[20];
void get()
{
cout<<"Enter the student number:";
cin>>sno;
cout<<"Enter the student name:";
cin>>name;

}
};

class total:public stu


{
int m1,m2,m3;
public:
void get1()
{
cout<<"Enter themark1:";
cin>>m1;
cout<<"Enter themark2:";
cin>>m2;
cout<<"Enter the mark3 :";
cin>>m3;

}
void calculate()
{
tot=m1+m2+m3;
}
void display()
{

8
Department of Computer Science and Engineering /Dr.N.G.P IT.

cout<<sno<<"\t"<<name<<"\t"<<m1<<"\t"<<m2<<"\t"<<m3<<"\t"<<tot<<"\t"<<"\n";
}
};

void main()
{
int i,n;
char ch;
total t;
clrscr();
t.get();
t.get1();
t.calculate();
cout<<"\sno \t name\t m1 \t m2 \t m3 \t tot \n";
t.display();
getch();
}

OUTPUT

Ex.No :3.b MULTIPLE INHERITANCE


AIM:
To find out the student details using multiple inheritance.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class student.
Step 3: Declare and define the function get() to get the student details.
Step 4: Declare the other class sports.

9
Department of Computer Science and Engineering /Dr.N.G.P IT.

Step 5: Declare and define the function getsm() to read the sports mark.
Step 6: Create the class statement derived from student and sports.
Step 7: Declare and define the function display() to find out the total and average.
Step 8: Declare the derived class object,call the functions get(),getsm() and display().
Step 9: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
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;
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;

}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
10
Department of Computer Science and Engineering /Dr.N.G.P IT.

{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
OUTPUT:

Ex. No:3.c MULTI LEVEL INHERITANCE


AIM:
To find out the student details using multilevel inheritance.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class mm.
Step 3: Declare and define the function get_num()to get the student details, put_num[]to
print them
Step 4: Declare the derived class marks from mm.
Step 5: Declare and define the function get_marks() to read the marks put_marks[]to print
them.
Step 6:Declare the derived class res from marks.
Step 7: Declare and define the function display() to find the total and display them.
Step 8: Declare the derived class res object as std1 and call the functions
Step 9: Stop the program.
PROGRAM:
#include <iostream.h>
#include<conio.h>
class mm
{
protected:

11
Department of Computer Science and Engineering /Dr.N.G.P IT.

int rollno;
public:
void get_num()
{
cout<<"enter a number:\n";
cin>>rollno;
}
void put_num()
{ cout << "Roll Number Is:\n"<< rollno << "\n"; }
};
class marks : public mm
{
protected:
int sub1,sub2;
public:
void get_marks()
{
cout<<"enter the marks:\n";
cin>>sub1>>sub2;

}
void put_marks()
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};
class res : public marks
{
protected:
float tot;
public:
void disp()
{
tot = sub1+sub2;
put_num();
put_marks();
cout << "Total:"<< tot;
}
};
void main()
{
res std1;
std1.get_num();
std1.get_marks();

12
Department of Computer Science and Engineering /Dr.N.G.P IT.

std1.disp();
getch();
}

OUTPUT

Ex. No:3.d HIERARCHICAL INHERITANCE


AIM:
To find out the square and cube of a number using hierarchical inheritance.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class A.
Step 3: Declare and define the function getnumber() to get the number.
Step 4: Declare the derived class B from A.
Step 5: Declare and define the function square() to find the square of a number.
Step 6: Declare the derived class C from A.
Step 7: Declare and define the function cube() to find the cube of a number
Step 6: Create the class object b1 for class B and c1 for class C.
Step 7: Call the function square and cube and display the result
Step 9: Stop the program.

PROGRAM
#include<iostream.h>
#include<conio.h>
class A
{
public:
int a,b;
13
Department of Computer Science and Engineering /Dr.N.G.P IT.

void getnumber()
{
cout<<"\n\nEnter Number :::\t";
cin>>a;
}
};
class B : public A
{
public:
void square()
{
getnumber();
cout<<"\n\n\tSquare of the number :::\t"<<(a*a);
}
};
class C :public A
{
public:
void cube()
{
getnumber();
cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
}
};
void main()
{
clrscr();
B b1;
b1.square();
C c1;
c1.cube();
getch();
}
OUTPUT:

14
Department of Computer Science and Engineering /Dr.N.G.P IT.

Ex. No:3.e HYBRID INHERITANCE


AIM:
To find out the sum of given numbers using hybrid inheritance.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class A.
Step 3: Declare and define the function getab() to get the values a,b
Step 4: Declare the derived class B from A.
Step 5: Declare and define the function getc() to get the value c
Step 6: Declare the class C.
Step 7: Declare and define the function getd() to get d
Step 8: Declare the derived class D from C,B. the value
Step 9: Declare and define the function result () to find out sum value
Step 10: Create a class object d1 to call the function d1 and display the result.
Step 11: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
int a,b,c,d,e;
class A
{
protected:
public:
void getab()
{
cout<<"\n ENter a and b value:";
cin>>a>>b;
}

15
Department of Computer Science and Engineering /Dr.N.G.P IT.

};
class B:public A
{
protected:
public:
void getc()
{
cout<<"Enter c value:";
cin>>c;
}
};
class C
{
protected:
public:
void getd()
{
cout<<"Enter d value:";
cin>>d;
}
};
class D:public B,public C
{
protected:
public:
void result()
{
getab();
getc();
getd();
e=a+b+c+d;
cout<<"\n Addition is :"<<e;
}
};
void main()
{
clrscr();
D d1;
d1.result();
getch();
}

OUTPUT:

16
Department of Computer Science and Engineering /Dr.N.G.P IT.

RESULT:
Thus the programs for Inheritance has been done

Ex. No:4 FUNCTION OVERLOADING


AIM:
To calculate the area of circle, rectangle and triangle using function overloading.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the class name as fn with data members and member functions.
STEP 3: Read the choice from the user.
STEP 4: Choice=1 then go to the step 5.
STEP 5: The function area() to find area of circle with one integer argument.
STEP 6: Choice=2 then go to the step 7.
STEP 7: The function area() to find area of rectangle with two integer argument.
STEP 8: Choice=3 then go to the step 9.
STEP 9: The function area() to find area of triangle with three arguments, two as Integer
and one as float.
STEP 10: Choice=4 then stop the program.
PROGRAM:
#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14
class fn
{
public:
void area(int);
void area(int,int);
void area(float ,int,int);
};

17
Department of Computer Science and Engineering /Dr.N.G.P IT.

void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}

void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of Triangle\n4.Exit\n:”;
cout<<”Enter your Choice:";
cin>>ch;

switch(ch)
{
case 1:
cout<<"Enter Radius of the Circle:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
18
Department of Computer Science and Engineering /Dr.N.G.P IT.

}
OUTPUT:

RESULT:
Thus the programs for function overloading has been done
Ex.No:5 VIRTUAL FUNCTION

AIM:
Towrite a C++ program for virtual function
ALGORITHNM:
Step 1: Start the program.
Step 2: Declare the base class base.
Step 3: Declare and define the function show (),virtual function display();
Step 4: Declare the derived class ‘derived’ from base class.
Step 5: Declare and define the function show (), display();
Step 6: Create object b and pointer *bptr for base class
Step 7: Call the functions show, display using object pointers
Step 8: Stop the program.

PROGRAM:

#include<iostream.h>
#include<conio.h>
class base
{
public:
void show(int x)
{
cout<<"\nBase show:X="<<x;
}
virtual void display(int x)
{

19
Department of Computer Science and Engineering /Dr.N.G.P IT.

cout<<"\nBase display:X="<<x;
}
};
class derived : public base
{
public:
void show(int y)
{
cout<<"\nDerived show:Y="<<y;
}
void display(int y)
{
cout<<"\nDerived display:Y="<<y;
}
};
void main()
{
clrscr();
cout<<"\t\tVirtual Functions\n";
base b,*bptr;
derived d;
bptr=&b;
bptr->show(5);
bptr->display(10);
bptr=&d;
bptr->show(15);
bptr->display(20);
getch();
}

OUTPUT:
Virtual Functions
Base show:X=5
Base display:X=10
Base show:X=5
Derived display:Y=20
RESULT:
Thus the programs for virtual function has been done

Ex. No: 6.a BINARY OPERATOR OVERLOADING –MEMBER FUNCTION.

AIM:
To write a program to add two complex numbers using binary operator overloading.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class.
20
Department of Computer Science and Engineering /Dr.N.G.P IT.

Step 3: Declare the variables and its member function.


Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers using single
argument.
Step 6: Define the function operator –()to subtract two complex numbers using single
argument
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator + and
operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;
public:
void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";
cin>>a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a=a+ob.a;
t.b=b+ob.b;
return(t);
}
complex operator-(complex ob)
{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};
void main()
21
Department of Computer Science and Engineering /Dr.N.G.P IT.

{
clrscr();
complex obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:\n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();
getch();
}
Enter the value of Complex Numbers a,b: 2 3
Enter the value of Complex Numbers a,b: 1 2
3+5i
1-1i

Ex. No: 6.b BINARY OPERATOR OVERLOADING – NON MEMBER FUNCTION


AIM:
To write a program to add two complex numbers using binary operator overloading – non
member function.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers using two arguments.
Step 6: Define the function operator –()to subtract two complex numbers using two
arguments.
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator + and
operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
22
Department of Computer Science and Engineering /Dr.N.G.P IT.

int a,b;
public:
void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";
cin>>a>>b;
}
friend complex operator+(complex ob1, complex ob2)
{
complex t;
t.a=ob1.a+ob2.a;
t.b=ob1.b+ob2.b;
return(t);
}
friendcomplex operator-(complex ob1, complex ob2 )
{
complex t;
t.a=ob1.a-ob2.a;
t.b=ob1.b-ob2.b;
return(t);
}

void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};

void main()
{
clrscr();
complex obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:\n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();

getch();
}
OUTPUT
23
Department of Computer Science and Engineering /Dr.N.G.P IT.

Enter the value of Complex Numbers a,b: 2 3


Enter the value of Complex Numbers a,b: 1 2
3+5i
1-1i

Ex. No: 6.c UNARY OPERATOR OVERLOADING – MEMBER FUNCTION


AIM
To write a program to find the complex numbers using unary operator overloading.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator ++ to increment the values without using arguments
Step 6: Define the function operator - -to decrement the values without using arguments
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue
Step 10: Call the function operator ++() by incrementing the class object and call the
function display.
Step 11: Call the function operator - -() by decrementing the class object and call the
function display.
Step 12: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
24
Department of Computer Science and Engineering /Dr.N.G.P IT.

b=--b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
Output:
Enter the two numbers: 3 6
Increment Complex Number
4+ 7i
Decrement Complex Number
3+ 6i

Ex. No: 6.d UNARY OPERATOR OVERLOADING – NON MEMBER FUNCTION


AIM
To write a program to find the complex numbers using unary operator overloading.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator ++ to increment the value using single arguments
Step 6: Define the function operator - -to decrement the values using single arguments
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue
Step 10: Call the function operator ++() by incrementing the class object and call the
function display.
Step 11: Call the function operator - -() by decrementing the class object and call the
function display.
Step 12: Stop the program.
25
Department of Computer Science and Engineering /Dr.N.G.P IT.

PROGRAM
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++(complex ob)
{
a=++ob.a;
b=++ob.b;
}
void operator--( complex ob)
{
a=--ob.a;
b=--ob.b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
RESULT:
Thus the programs for unary and binary operator overloading has been done

Ex. No:7.a CLASS TEMPLATES

26
Department of Computer Science and Engineering /Dr.N.G.P IT.

AIM
To write a program to find the minimum value using class templates.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the template class T.
Step 3: Define the template T with arguments and write the function to find the minimum
value.
Step 4: Declare the integer, float, character variables separately and find the minimum
value
Step 5: Display the result.
Step 12: Stop the program.

PROGRAM:
#include <iostream>
using namespace std;
template <class T>
T min(T a,T b )
{
return (a < b )?a:b;
}

int main()
{
int a=10,b=5;
cout<<min(a,b )<<'\n';
char p='A',q='Z';
cout<<min(p,q)<<'\n';
float z=1.91,x=3.98;
cout<<min(z,x)<<'\n';
return 0;
}

Ex. NO:7.b FUNCTION TEMPLATE


AIM:
To swap the numbers using the concept of function template.
ALGORITHM:
STEP 1: Start the program.

27
Department of Computer Science and Engineering /Dr.N.G.P IT.

STEP 2: Declare the template class.


STEP 3: Declare and define the functions to swap the values.
STEP 4: Declare and define the functions to get the values.
STEP 5: Read the values and call the corresponding functions.
STEP6: Display the results.
STEP 7: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"\na and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\na and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\nc and d after swaping :"<<c<<"\t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
OUTPUT:
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80
A and B before swapping: 10 20
A and B after swapping: 20 10
C and D before swapping: 2.50 10.80
C and D after swapping: 10.80 2.50

RESULT:
28
Department of Computer Science and Engineering /Dr.N.G.P IT.

Thus the programs for class and function templates has been done

Ex.No: 8 EXCEPTION HANDLING


AIM:
To write a C++ program to perform exception handling for Divide by zero Exception
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables a,b,c.
Step 3: Read the values a,b,c,.
Step 4: Inside the try block check the condition.
a. if(a-b!=0) then calculate the value of d and display.
b. otherwise throw the exception.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;

try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}

catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}
29
Department of Computer Science and Engineering /Dr.N.G.P IT.

getch();
}
OUTPUT:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40
Answer is infinite because a-b is: 0
RESULT:
Thus the programs for Exception handling has been done

Ex. No: 9 STANDARD TEMPLATE LIBRARY


AIM:
To write a C++ program for standard template library function
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the vector vec as an integer.
Step 3: Get the values from the beginning to end of the vector size
Step 4: Show the values by using vector and extend the vector size.
Step 5: Display the values from the beginning to end of the vector size
Step 6: Stop the program.
PROGRAM:
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
vector<int> vec;
int i;
cout<<"vector size = "<< vec.size()<< endl;
for(i =0; i <5; i++)
{
vec.push_back(i);
}
cout<<"extended vector size = "<< vec.size()<< endl;
for(i =0; i <5; i++)
{
cout<<"value of vec ["<< i <<"] = "<< vec[i]<< endl;
}

vector<int>::iterator v = vec.begin();
while( v != vec.end())
{
cout<<"value of v = "<<*v << endl;
v++;
}
30
Department of Computer Science and Engineering /Dr.N.G.P IT.

return0;
}
OUTPUT:
vector size =0
extended vector size =5
value of vec [0]=0
value of vec [1]=1
value of vec [2]=2
value of vec [3]=3
value of vec [4]=4
value of v =0
value of v =1
value of v =2
value of v =3
value of v =4
RESULT:
Thus the programs for STL has been done

Ex.No:10 FILE STREAM CLASSES


AIM:
To write a c++ program to file handling functions
ALGORITHM:
Step1. Start the program
Step2. Create a class student and declare the necessary variables and
functions
Step3. Create as many objects as required in the main program
Step4. Create an object for fstream class and open the required file
in both input and output mode
Step5. Get the data from the user and write the values into the file
Step6. Move to the beginning position in the file
Step7. Read the values from the file and display the output
Step8. Close the file
Step9. Stop the program

PROGRAM
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
class student
{
int rollno;
char *name;
public:

31
Department of Computer Science and Engineering /Dr.N.G.P IT.

void getdata()
{
cout<<"\n Enter Rollno and name:";
cin>>rollno>>name;
}
void makenull()
{
rollno=0;
name=" ";
}
void putdata()
{
cout<<"\nRollno:"<<rollno<<"\tName:"<<name;
}
};
void main()
{
student s[3];
clrscr();
cout<<"\t\t\t File Handling";
fstream file;
file.open("student.txt",ios::in|ios::out);
for(int i=0;i<3;i++)
{
s[i].getdata();
file.write((char *)&s[i],sizeof(s[i]));
}
file.seekg(0);
for(i=0;i<3;i++)
s[i].makenull();
for(i=0;i<3;i++)
{
file.read((char *)&s[i],sizeof(s[i]));
s[i].putdata();
}
file.close();
getch();
}

OUTPUT:

File Handling

Enter Rollno and name: 20 Surya


32
Department of Computer Science and Engineering /Dr.N.G.P IT.

Enter Rollno and name: 15 Bala

Enter Rollno and name: 16 Mano

Rollno: 20 Name: Surya


Rollno: 15 Name: Bala
Rollno: 16 Name: Mano

RESULT:
Thus the programs for file stream classes has been done

Ex. No:11.a APPLICATIONS OF STACK

CONVERSION OF INFIX TO POSTFIX EXPRESSION


AIM:
To write a C++ program for conversion of infix to postfix expression
ALGORITHM:

Step 1: Start the program


Step 2: Get the expression from user and store it in an array
Step 3: Read the expression. If it is a character copy it to output array. If it is a operator,
push it
to the stack.
Step 4: Check for operator precedence, if lower precedence operator is
Step 5: If choice is 2, push the new node in top, and increment the top pointer by one
Step 6: If choice is 3, pop the node (value) from the stack and decrement the top pointer by
one
Step 7: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
char in[40],post[40];
int top=0,st[20];
void postfix();
void push(int);
char pop();
void main()
{
clrscr();
cout<<” Enter the infix expression:";
cin>>in);
postfix();
getch();
}

33
Department of Computer Science and Engineering /Dr.N.G.P IT.

void postfix()
{
int i,j=0;
for(i=0;in[i]!='\0';i++)
{
switch(in[i])
{
case '+':
while(st[top]>=1)
post[j++]=pop();
push(l);
break;
case '-':
while(st[top]>=1)
post[j++]=pop();
push(2);
break;
case '*':
while(st[top]>=3)
post[j++]=pop();
push(3);
break;
case '/':
while(st[top]>=3)
post[j++]=pop();
push(4);
break;
case '^':
while(st[top]>=4)
post[j++]=pop();
push(5);
break;
case '(':
push(0);
break;
case ')':
while(st[top]!=0)
post[j++]=pop();
top--;
break;
default:
post[j++]=in[i];
}
}
while(top>0)
post[j++]=pop();
34
Department of Computer Science and Engineering /Dr.N.G.P IT.

cout<<” Postfix Expression is “<<post);


}
void push(int element)
{
top++;
st[top]=element;
}
char pop()
{
int el;
char e;
el=st[top];
top--;
switch(el)
{
case 1:
e='+';
break;
case 2:
e='-';
break;
case 3:
e='*';
break;
case 4:
e='/';
break;
case 5:
e='^';
break;
}
return(e);
}

OUTPUT:
Enter the infix expression: a+b
Postfix Expression is : ab+

Ex. No: 11.b APPLICATIONS OF STACK


EVALUATING POSTFIX EXPRESSION
AIM:
To write a C++ program to evaluate the given expression
PROGRAM:
35
Department of Computer Science and Engineering /Dr.N.G.P IT.

Step 1: Start the program


Step 2: Get the postfix expression from user and store it in an array
Step 3: Read the expression. If it is a operand push it to the stack.
Step 4: If it is a operator, perform the operator function between the 2 operands.
Step 5: Store the resultant operand in the same stack
Step 6: Repeat step 4 & 5, until reach the end of the expression
Step 7: Stop the program
PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<math.h>
#include<string.h>
#define max 50
int top=-1,stack[max];
void push(int element)
{
stack[++top]=element;
}
int pop(void)
{
return stack[top--];
}
void main()
{
char postfix[50],ch;
int i=0,op1,op2;
clrscr();
fflush(stdin);
cout<<”Enter the Postfix Expression : ";
gets(postfix);
while((ch=postfix[i++])!='\0')
{
if(isdigit(ch))
{
push((int)ch-48);
}
else
{
op2=pop();
op1=pop();
printf("\nop1=%d\top2=%d\n",op1,op2);
switch(ch)
{
case '+': push(op1+op2);
break;
36
Department of Computer Science and Engineering /Dr.N.G.P IT.

case '-': push(op1-op2);


break;
case '*': push(op1*op2);
break;
case '/': push((int)op1/(int)op2);
break;
case '%': push((int)op1%(int)op2);
break;
case '^': push(pow(op1,op2));
break;
}
}
}
cout<<”Result after Evaluation : “<<stack[top++]);
getch();
}
OUTPUT:
Given Expression: 12*456*++
Result after Evaluation: 36

Ex. No: 11.c APPLICATIONS OF STACK

RECURSION – TOWERS OF HANOI


AIM:
To write a C++ program to perform towers of Hanoi problem using recursion.

PROGRAM:
Step 1: Start the program
Step 2: Declare the variables
Step 3: Read the number of disks
Step 4: Call the function move
Step 5: In function move, check if count>0 and if it is true call move recursively and print
how the disks are moved.
Step 6: Stop the program

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
cout<<"enter the no of disks”;
cin>>n;
if(n>0)
towers(n,"tower1",tower2",tower3");
37
Department of Computer Science and Engineering /Dr.N.G.P IT.

else
cout<<"you need atleast one disk";
getch();
}
towers(int n,char* l,char* c,char* r)
{
if(n==1)
{
Cout<<" move disk 1 from “<<l<<” to “<<r;
return;
}
else
{
towers(n-1,l,r,c);
cout<<" move disk”<<n<<“from”<<l<<” to”<<r);
towers(n-1,c,1,r);
return;
}
}
OUTPUT:
enter the no of disks 2
move disk 2 from l to r
move disk 1 from l to r

Ex. No: 11.d APPLICATIONS OF STACK

BALANCING SYMBOLS
AIM:
To write a C++ program to perform balancing symbols operation.

ALGORITHM:
Step 1: Start the program
Step 2: Declare the variables
Step 3: Get the expression from the user
Step 4: Read the expression and Push the ‘(‘ into the stack.
Step 5: Pop 1 ‘(‘ from the stack when we read 1 ‘)’.
Step 6: If the stack is empty at the end then the expression is valid else not valid
Step 6: Stop the program

PROGRAM:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
bool bracketsame(char opening,char closing)
{
38
Department of Computer Science and Engineering /Dr.N.G.P IT.

if(opening == '(' && closing == ')')


true;
else
return false;
}
bool balancedparantheses(string exp)
{
stack<char> S;
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(')
S.push(exp[i]);
else if(exp[i] == ')' )
{
if(S.empty() || !bracketsame(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
string expression;
cout<<"Enter an expression to check: ";
cin>>expression;
if(balancedparantheses(expression))
cout<<"Balanced expression \n";
else
cout<<"Expression is not balanced \n";
}

OUTPUT:
Enter an expression to check : (a-b)+(c+d)
Balanced expression

Ex. No: 11.e APPLICATION OF QUEUE – PRIORITY QUEUE


AIM:
To write a C++ program for priority queue
ALGORITHM
39
Department of Computer Science and Engineering /Dr.N.G.P IT.

Step 1: Start the program


Step 2. Get the choice from the user
Step 3. To insert an item get the value and its priority, insert it based on its priority
Step 4. To delete an item first check whether the queue is empty or not, if queue has some
item
then delete the item which is present in front
Step 5. To display the items of queue, check for ‘queue empty condition’ the display them
from front
to rear
Step 8.Step 9. Stop the program.
PROGRAM:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
usingnamespace std;
struct node
{
int priority;
int info;
struct node *link;
};

class Priority_Queue
{
private:
node*front;
public:
Priority_Queue()
{
front=NULL;
}

void insert(int item, int priority)


{
node*tmp, *q;
tmp=new node;
tmp->info = item;
tmp->priority = priority;
if(front ==NULL|| priority < front->priority)
{
tmp->link = front;

40
Department of Computer Science and Engineering /Dr.N.G.P IT.

front= tmp;
}
else
{
q = front;
while(q->link !=NULL&& q->link->priority <= priority)
q=q->link;
tmp->link = q->link;
q->link = tmp;
}
}
void del()
{
node*tmp;
if(front ==NULL)
cout<<"Queue Underflow\n";
else
{
tmp= front;
cout<<"Deleted item is: "<<tmp->info<<endl;
front= front->link;
free(tmp);
}
}
void display()
{
node*ptr;
ptr= front;
if(front ==NULL)
cout<<"Queue is empty\n";
else
{ cout<<"Queue is :\n";
cout<<"Priority Item\n";
while(ptr !=NULL)
{
cout<<ptr->priority<<" "<<ptr->info<<endl;
ptr= ptr->link;
}
}
}
};
int main()
{
int choice, item, priority;
Priority_Queue pq;
do
41
Department of Computer Science and Engineering /Dr.N.G.P IT.

cout<<"1.Insert\n";
cout<<"2.Delete\n";
cout<<"3.Display\n";
cout<<"4.Quit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case1:
cout<<"Input the item value to be added in the queue : ";
cin>>item;
cout<<"Enter its priority : ";
cin>>priority;
pq.insert(item, priority);
break;
case2:
pq.del();
break;
case3:
pq.display();
break;
case4:
break;
default:
cout<<"Wrong choice\n";
}
}
while(choice !=4);
return0;
}

OUTPUT:
1.Insert;
2.Delete;
3.Display;
4.Quit;
Enter your choice1
Input the item value to be added in the queue :10
Enter its priority:1
1.Insert;
2.Delete;
3.Display;
4.Quit
Enter your choice2
Deleted item is 10
1.Insert;
42
Department of Computer Science and Engineering /Dr.N.G.P IT.

2.Delete;
3.Display;
4.Quit;
Enter your choice3
Queue is empty

RESULT:
Thus the programs for applications of stack and queue has been done

Ex. No: 12 BINARY SEARCH TREE


AIM:
To write a C++ program for binary search tree
ALGORITHM:
Step 1:Start the program
Step 2. Get the values for binary search tree until the user enters -1
Step 3. Insert each value into the tree in such a way that if the
element is lesser than the root node, traverse through the left
sub tree and insert in appropriate position
Step 4. If the element is greater than the root node, traverse through
the right sub tree and then insert in appropriate position
Step 5. Get the element to be deleted
Step 6. If it is a leaf node, delete it without making any change.
Step 7. If it is a parent, make the appropriate child as parent and then
delete the element.
Step 8. Display the binary search tree.
Step 9. Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct tree
{
int a;
struct tree *left;
struct tree *right;
};
struct tree *ins(struct tree *p,int x)
{
if(p==NULL)
{
p=(struct tree *)malloc(sizeof(struct tree));
p->a=x;
p->left=NULL;
43
Department of Computer Science and Engineering /Dr.N.G.P IT.

p->right=NULL;
return(p);
}
if(x<p->a)
p->left=ins(p->left,x);
else
p->right=ins(p->right,x);
return(p);
}
void prn(struct tree *x,int level)
{
int i;
if(x)
{
prn(x->right,level+1);
cout<<"\n";
for(i=0;i<level;i++)
cout<<"\t";
cout<<x->a;
prn(x->left,level+1);
}
}
struct tree *delete1(struct tree *g,struct tree *h)
{
struct tree *f;
if(g->right!=NULL)
g->right=delete1(g->right,h);
else
{
f=g;
h->a=g->a;
g=g->left;
free(f);
}
return(g);
}
void copy(struct tree *t,struct tree **d)
{
int i;
if(t)
{
*d=(struct tree *)malloc(sizeof(struct tree));
(*d)->a=t->a;
copy(t->left,&(*d)->left);
copy(t->right,&(*d)->right);
}
44
Department of Computer Science and Engineering /Dr.N.G.P IT.

else
*d=NULL;
}
struct tree *del(struct tree *t,int x)
{
struct tree *q;
if(x<t->a)
t->left=del(t->left,x);
else if(x>t->a)
t->right=del(t->right,x);
else
{
q=t;
if(q->right==NULL)
{
t=q->left;
free(q);
}
else if(q->left==NULL)
{
t=q->right;
free(q);
}
else
q->left=delete1(q->left,q);
}
return(t);
}
void main()
{
struct tree *t=NULL,*d=NULL;
int a,b;
clrscr();
while(1)
{
cout<<"\nenter value -1 to stop:";
cin>>a;
if(a==-1)
break;
t=ins(t,a);
}
prn(t,1);
cout<<"\nenter value to be deleted";
cin>>b;
t=del(t,b);
cout<<"\n";
45
Department of Computer Science and Engineering /Dr.N.G.P IT.

prn(t,1);
getch();
}

OUTPUT:
enter value -1 to stop:5
enter value -1 to stop:3
enter value -1 to stop:8
enter value -1 to stop:2
enter value -1 to stop:4
enter value -1 to stop:6
enter value -1 to stop:9
enter value -1 to stop:-1
9
8
6
5
4
3
2
enter value to be deleted3
9
8
6
5
4
2
RESULT:
Thus the program for Binary search tree has been done

Ex. No: 13 BINARY TREE TRAVERSAL


AIM:
To write a C++ program for binary tree traversal

ALGORITHM:
Step 1: Start the program
Step 2. Get the node value from the user and construct the tree
Step 3. For inorder traversal the nodes are visited like left – root - right
Step 4.For preorder traversal the nodes are visited like root – left – right
Step 5.For postorder traversal the nodes are visited like left- right – root
Step 8. Display the traversal result.
Step 9. Stop the program.
PROGRAM:
#include<iostream.h>
46
Department of Computer Science and Engineering /Dr.N.G.P IT.

#include<conio.h>
#include<stdio.h>
struct btree
{
struct btree *left;
struct btree *right;
int no;
};
void postorder(struct btree *trav);
void inorder(struct btree *trav);
void preorder(struct btree *trav);
struct btree * create(struct btree *trav);
main()
{
struct btree *root=NULL;
char c;
clrscr();
while(1)
{
root=create(root);
cout<<"Do you want to continue : ";
cin>>c;
if(c=='n' ||c=='N')
break;
}
cout<<endl<<"Inoder is : ";inorder(root);
cout<<endl<<"Preorder is : ";preorder(root);
cout<<endl<<"Postorder is : ";postorder(root);
getch();
}
struct btree * create(struct btree *trav)
{
if(trav==NULL)
{
trav=new btree;
trav->right=NULL;
trav->left=NULL;
cout<<"Enter the no : ";
cin>>trav->no;
return(trav);
}
char choice;
cout<<"Enter the left or right child : ";
cin>>choice;
if(choice == 'r' || choice == 'R')
{
47
Department of Computer Science and Engineering /Dr.N.G.P IT.

trav->right=create(trav->right);
}
if(choice=='l' || choice=='L')
{
trav->left=create(trav->left);
}
return(trav);
}
void inorder(struct btree *trav)
{
if(trav==NULL)
return ;
inorder(trav->left);
cout<<" "<<trav->no;
inorder(trav->right);
}
void preorder(struct btree *trav)
{
if(trav==NULL)
return;
cout<<" "<<trav->no;
preorder(trav->left);
preorder(trav->right);
}
void postorder(struct btree *trav)
{
if(trav==NULL)
return;
postorder(trav->left);
postorder(trav->right);
cout<<" "<<trav->no;
}
OUTPUT:
Enter the no: 1
Enter the left or right child: l
Do you want to continue: Y
Enter the no: 2
Enter the left or right child: l
Do you want to continue: Y
Enter the no: 3
Enter the left or right child: r
Do you want to continue: Y
Preorder traversal
1 2 3
Inorder traversal
2 1 3
48
Department of Computer Science and Engineering /Dr.N.G.P IT.

Postorder traversal
2 3 1
RESULT:
Thus the program for Binary tree traversal has been done

Ex.No:14 MINIMUM SPANNING TREE(PRIM’S ALGORITHM)


AIM :
To find the minimum spanning tree of a given graph using Prim’s algorithm
ALGORITHM:
Step 1 : Start the process.
Step 2:: Number of vertices and adjacency between vertices are got from user.
Step 3 : Initially randomly any mode should be selected and its adjacent nodes are found
out
Step 4 : Which one is minimum, is then selected abed added into minimum spanning tree.
Step 5 : The find the adjacent of two nodes which is being in spanning tree
Step 6 : The above process is repeated till al the vertices are include in minimum spanning
tree is
displayed
Step 7 : Stop the e process
Prim’s Algorithm
Prim ( G [0 … size-1, 0…size-1 ], nodes)
Total = 0;
For I ← 0 to nodes – 1 do
Tree[i] ← 0
Tree[0] ← 1
For k ← to nodes do
{
min_dist ← ∞
for i ← 0 to nodes – 1 do
{
for j ← 0 to nodes -1 do
{
if ( G[i, j] AND ((tree[i] AND !tree[j] ) OR
(!tree[i] AND tree[j] ))) then
{
if ( G[i, j] < min_dist ) then
{
min_dist ← G [ij]
v1 ← i
v2 ← j
}
}
}
}
write ( v1, v2, min_dist)
49
Department of Computer Science and Engineering /Dr.N.G.P IT.

tree[v1\ ← tree[v2] ←1
total ← total + min_dist
}
Write ( “ Total path length is “, Total)
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define v 9
void main()
{
int g[10][10]={0},vis[10]={0},i,j,n,min,y=0,tra[10]={0},k,p=0,l;
clrscr();
cout<<"Enter the number of nodes:";
cin>>n;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
cout<<"Enter the path between “<<i<<” and”<<j;
cin>>g[i][j];
if(g[i][j]==0)
g[i][j]=in;
}
vis[0]=in;
k=0;
cout<<”The path is:";
tra[0]=0;
for(i=0;i<n-1;i++)
{
min=in;
for(l=0;l<n-i;l++)
for(j=0;j<n;j++)
if(min>g[tra[l]][j]&&g[tra[l]][j]!=in&&vis[j]!=in)
{
min=g[tra[l]][j];
k=tra[l];
y=j;
}
tra[l+l]=y;
p+=g[y][k ];
g[y][k]=g[k][y]=in;
vis[y]=in;
printf("\n%d -----> %d",k,y);
k=y;
}
Cout<<”The path length is:"<<,p);
getch();
50
Department of Computer Science and Engineering /Dr.N.G.P IT.

OUTPUT
Enter the total nodes : 4
Enter the weight for the path [ if no path enter 0 ]
1 to 2 : 2
1 to 3 : 3
1 to 4 : 4
2 to 3 : 5
2 to 4 : 6
3 to 4 : 7

Total Length of spanning tree : 9


Spanning tree edges are :

1 : 2 2
1 : 3 3
1 : 4 6

RESULT:

Thus the program for Minimum spanning tree has been done

Ex.No:15 SHORTEST PATH ALGORITHM(DIJKSTRA’S ALGORITHM)


AIM :
To find the shortest path using Dijkstra’s algorithm
ALGORITHM:
Step 1 : Start the process.
Step 2:: Declare the number of vertices.
Step 3 : find the vertex with minimum distance value, fromthe set of vertices not yet
included in shortest path tree

Step 4 : dist[i] will hold the shortestdistance from src to i


Step 5 : sptSet[i] will true if vertex i is included in shortest path tree or shortest distance
from src
to i is finalize
Step 6 : Initialize all distances as INFINITE and stpSet[] as false,Distance of source vertex
from itself
is always 0 and Find shortest path for all vertices
Step 7 : Pick the minimum distance vertex from the set of vertices notyet processed. u is
always
equal to src in first iteration.
Step 8: Mark the picked vertex as processed
Step 9:Update dist value of the adjacent vertices of the picked vertex
Step 10:Update dist[v] only if is not in sptSet, there is an edge from u to v, and total weight
of path

51
Department of Computer Science and Engineering /Dr.N.G.P IT.

from src to v through u is smaller than current value of dist[v]


Step 11:print the constructed distance array

PROGRAM

#include <stdio.h>
#include <limits.h>
#include<math.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n)
{
cout<<"Vertex Distance from Source";
for (int i = 0; i < V; i++)
cout<<i<< “\t\t “<<dist[i];
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V-1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u]+graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main()
{
int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},

52
Department of Computer Science and Engineering /Dr.N.G.P IT.

{0, 0, 0, 9, 0, 10, 0, 0, 0},


{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};

dijkstra(graph, 0);

return 0;
}
RESULT:
Thus the program for finding the shortest path has been done

CONTENT BEYOND THE SYLLABUS


Ex. No:1 OPERATOR OVERLOADING - (ASSIGNMENT OPERATOR)
AIM:
To write a c++ program for operator overloading for assignment operator

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the class sample
Step 3: Using the function getdata() to get the two values.
Step 4: Define the function operator =() to add two complex numbers using one argument.
Create object obj to access x , y values
Step 5: Define the display function to display the values.
Step 6: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
Class sample
{
Private:
Int x, y;
Public:
Void getdata ()
{
Cout <<” \n enter the value of x and y”;
Cin>> x>>y;
}
Void operator = (sample obj)
{
X= obj.x;
Y= obj.y;
53
Department of Computer Science and Engineering /Dr.N.G.P IT.

}
Void display ()
{
Cout<<”\n value of x”<<x;
Cout<<”\n value of y”<<y;
}
};
Void main ()
{
Sample obj1, obj2;
Obj1.getdata ();
Obj1.display ();
Obj2=ob1;
Obj2.display();
getch ();
}
OUTPUT:

enter the value of x and y: 3 4

value of x: 3

value of y: 4

Ex. No:2 IMPLEMENTATION OF AVL TREES


AIM:
To write a ‘C’ program to perform operations on AVL tree.
ALGORITHM:
Step 1. Start the program
Step 2. Construct the tree as binary tree
Step 3. While Constructing check Balancing Factor and
the following four conditions.
Step 4. 1: Insertion in to left sub-tree of left child.
Single rotate with left
Get the UN balanced node AS K2
Create new node AS K1
Set k1 as K2->Left;
Set K2Left=K1right;
K1right=K2;
K2height=Max(height(K2left),height(K2right))+1;
K1height=Max(height(K1left),height(K1right))+1;

Step 5. insert into left sub tree of right child.


Single rotate with right
Get the UN balanced node AS K2
Create new node AS K1

54
Department of Computer Science and Engineering /Dr.N.G.P IT.

Set k1 as K2->right;
Set K1right=K2left;
Set K2left=K2;
K1left=K2;
K2height=Max(height(K2left),height(K2right))+1;
K1height=Max(height(K1left),height(K1right))+1;
Step 6. insert into right sub tree of left child
double rotation with left K3
Single rotate with right(k3left);
Single rotate with left(k3)
Step 7: double rotation with right K3
Single rotate with left(k3right);
Single rotate with right(k3);

Step 8: Deletion
Check the Balancing factor and rotate if not balanced.
Step 9: Stop the program.

PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct tree
{
int data, bf;
struct tree *parent, *left, *right;
}tree;
typedef struct tree *tree_type;
tree_type root=NULL;
void insert(int);
void insertion(void);
void printTree(tree_type, int, int, int);
void BFactor(tree_type);
void rotate(tree_type);
void RR(tree_type);
void RL(tree_type);
void LL(tree_type);
void LR(tree_type);
int NodeHeight(tree_type);
void main(void)
{
int ch;
clrscr();
do
{ clrscr();
printf("\n\t AVLTREE");
55
Department of Computer Science and Engineering /Dr.N.G.P IT.

printf("\n\t Insert a Number ..... 1");


printf("\n\t Display the values....2");
printf("\n\t B Factor............. 3");
printf("\n\t Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: insertion(); break;
case 2: clrscr();
gotoxy(20,5);
printf("Binary Traversal");
printTree(root, 35, 10,0);
getch();
break;
case 3: BFactor(root);
rotate(root);
getch();
break;
}
}while(ch!=0);
}
void insertion(void)
{
int value;
clrscr();
printf("\n\t Insert values Greater than Zero...\n");
scanf("%d",&value);
do
{ insert(value);
scanf("%d",&value);
}while(value!=0);
}
void insert(int value)
{
tree_type ptr, curr;
curr = (tree_type)malloc(sizeof(tree));
curr->data = value;
curr->bf = 0;
curr->parent = NULL;
curr->left = NULL;
curr->right = NULL;
if(root == NULL)
root = curr;
else
{ptr = root;
while(ptr->left!=NULL || ptr->right!=NULL)
56
Department of Computer Science and Engineering /Dr.N.G.P IT.

{
if(ptr->data >= curr->data)
if(ptr->left != NULL)
ptr = ptr->left;
else
break;
if(ptr->data < curr->data)
if(ptr->right != NULL)
ptr = ptr->right;
else
break;
}
curr->parent = ptr;
if(curr->data < ptr->data)
ptr->left = curr;
if(curr->data > ptr->data)
ptr->right = curr;
}
}

void BFactor(tree_type ptr)


{
if(ptr==NULL)
return;
ptr->bf = NodeHeight(ptr);
printf("\n\t%d ----->%d",ptr->data, ptr->bf);
if(ptr->left!=NULL)
BFactor(ptr->left);
if(ptr->right!=NULL)
BFactor(ptr->right);
}
int NodeHeight(tree_type ptr)
{
int h=0;
tree_type Lptr, Rptr;
Lptr = ptr->left;
Rptr = ptr->right;
while(Lptr->left != NULL || Lptr->right != NULL)
{ if(Lptr->left != NULL)
{ Lptr = Lptr->left;
h--;
}
if(Lptr->right != NULL)
{ Lptr = Lptr->right;
h++;
}
57
Department of Computer Science and Engineering /Dr.N.G.P IT.

}
while(Rptr->right != NULL || Rptr->left != NULL)
{ if(Rptr->right != NULL)
{ Rptr = Rptr->right;
h++;
}

if(Rptr->left != NULL)
{ Rptr = Rptr->left;
h--;
}
}
return h;
}
void printTree(tree_type ptr, int x, int y, int depth)
{
if(ptr==NULL)
return;
gotoxy(x,y);
printf("%d",ptr->data);
if(ptr->left != NULL)
printTree(ptr->left, x-5/(depth+1), y+1, depth+1);
if(ptr->right != NULL)
printTree(ptr->right,x+5/(depth+1), y+1, depth+1);
}
void rotate(tree_type ptr)
{
if(ptr == NULL)
return;
while(ptr->left != NULL || ptr->right != NULL)
{ if(ptr->bf < -1)
{
LR(ptr);
ptr= ptr->left;
}
if(ptr->bf > 1)
{
RL(ptr);
ptr = ptr->right;
}}}
void RR(tree_type ptr)
{
if(ptr!=NULL)
{
ptr->right->right=ptr->right->left;
58
Department of Computer Science and Engineering /Dr.N.G.P IT.

ptr->right->left=NULL;
}
}
void RL(tree_type ptr)
{
if(ptr!=NULL)
{
ptr->right->left = ptr->right->right;
ptr->right->right=NULL;
}
}
void LR(tree_type ptr)
{
if(ptr!=NULL)
{
ptr->left->right=ptr->left->left;
ptr->left->left = NULL;
}
}
void LL(tree_type ptr)
{
if(ptr!=NULL)
{
ptr->left->left = ptr->left->right;
ptr->left->right = NULL;
}
}
OUTPUT:
AVL TREE
Insert a Number ..... 1
Display the values....2
B Factor....................3
Enter your choice : 1
Insert values Greater than Zero...
25
15
12
3
43
1
4
50
0
Binary Traversal
15
4 25
59
Department of Computer Science and Engineering /Dr.N.G.P IT.

3 12 43 50
1
AVL TREE
Insert a Number ….. 1
Display the values….2
B Factor….......... 3
Enter your choice : 3

25 ---0
15 ----1
12 ---0
3 ----1
1 ---0
4 ----1
43 ---0
50 ---0

RESULT:

Thus the C ++ program to implement insertion in AVL trees has been executed
successfully

60