0% found this document useful (0 votes)
2 views

10 Programs c++ Lab

The document contains C++ programming examples for creating a student marklist using arrays, an inventory billing system using multiple arrays, and implementing polynomial objects with overloaded operators. It also includes examples of single linked lists with functions for insertion, deletion, and display. The code snippets demonstrate various programming concepts and structures in C++.

Uploaded by

19ucs033
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

10 Programs c++ Lab

The document contains C++ programming examples for creating a student marklist using arrays, an inventory billing system using multiple arrays, and implementing polynomial objects with overloaded operators. It also includes examples of single linked lists with functions for insertion, deletion, and display. The code snippets demonstrate various programming concepts and structures in C++.

Uploaded by

19ucs033
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

7

Lesson 2
ARRAY’S
a. To write a C++ program for creating student marklist using array

#include<iostream.h>
#include<string.h>
#include<conio.h>
void create(int);
void display(int);
void cal(int);

struct student
{
char name[10],res[5];
int sno,m1,m2,m3,tot;
float avg;
}s[10];
void main()
{
int n,ch,t;
clrscr();
cout<<“Enter the no of students”;
cin>>n;

do
{
cout<<“\n\t1.CREATE\n\t2.DISPLAY\nEnter ur choice:\n”;
cin>>ch;
switch(ch)
{
case 1:
create(n);
break;
case 2:
8

display(n);
break;
default:
cout<<“WRONG CHOICE”;
break;
}
cout<<“Do u want to continue? Press(1/0):”;
cin>>t;
}while(t!=0);
}
void create(int n)
{
cout<<“Create\n”;
for(int i=0;i<n;i++)
{
cout<<“Enter Student Name:”;
cin>>s[i].name;
cout<<“Enter Student RollNo:”;
cin>>s[i].sno;
cout<<“Enter Mark1:”;
cin>>s[i].m1;
cout<<“Enter Mark2:”;
cin>>s[i].m2;
cout<<“Enter Mark3:”;
cin>>s[i].m3;
}
}
void display(int n)
{clrscr();
cal(n);
cout<<“display”;
cout<<“\nNAME\tROLLNO\tMARK1\tMARK2\tMARK3\tTOTAL\tAVERAGE\n”;
for(int i=0;i<n;i++)
cout<<“\n”<<s[i].name<<“\t”<<s[i].sno<<“\t”<<s[i].m1<<“\t”<<s[i].m2<<“\t”<<s[i].m3<<“\t”<<s[i].tot<< “\t”<<s[i].avg<<“\n”;
}
void cal(int n)
{
for(int i=0;i<n;i++)
{
9

s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
}
for(i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
if(s[i].tot<=s[j+1].tot)
{
char temp7[10];
int temp1,temp2,temp3,temp4,temp5;
float temp6;
temp5=s[i].tot; s[i].tot=s[j+1].tot; s[j+1].tot=temp5;
strcpy(temp7,s[i].name);strcpy(s[i].name,s[j+1].name);strcpy(s[j+1].name,temp7);
temp1=s[i].sno; s[i].sno=s[j+1].sno; s[j+1].sno=temp1;
temp2=s[i].m1; s[i].m1=s[j+1].m1; s[j+1].m1=temp2;
temp3=s[i].m2; s[i].m2=s[j+1].m2; s[j+1].m2=temp3;
temp4=s[i].m3; s[i].m3=s[j+1].m3; s[j+1].m3=temp4;
temp6=s[i].avg; s[i].avg=s[j+1].avg; s[j+1].avg=temp6;
}
}
}
}
10

b. Write a c++ program for create a inventory billing system using Multiple
array.
#include<iostream.h>
#include<conio.h>
struct inventory
{
int pid,qty;
char pname[10];
float price,amt;
}s[5][10];
void Line()
{
int L;
for(L=0;L<=70;L++)
cout<<“-”;
return;
}
void main()
{
int i,j,k,flr,n=0,m=0,o;float tot[10]={0.0},cashtotal=0.0;
clrscr();
cout<<“enter the number of sales counter”;
cin>>m;
13

Lesson 3
POLYNOMIAL OBJECT
a. Write a C++ program to implement the Polynomial Object using overloaded
operator

#include <iostream.h>
#include <time.h>
#include <stdlib.h>
#include <conio.h>
void line(int lines);

class Polynomial
{
private:
int power;
int* coeffs;
public:
Polynomial() {power=0;coeffs=new int[1];}
Polynomial(int deg) {power=deg;coeffs=new int[deg+1];}
Polynomial(const Polynomial& X);

void GetCoeffs(istream& in);


int Coeff(int deg);
void Show(ostream& out);
int Degree() {return power;}
//operators
friend Polynomial operator +(Polynomial& X, Polynomial& B);
friend Polynomial operator -(Polynomial& X, Polynomial& B);
};

void main()
{
int ch;
clrscr();
do
14

{
cout<<“\n\t========================”;
cout<<“\n\t1.addition of Polynomial\n\t2.subtraction of Polynomial\n\t3.Exit”;
cout<<“\n\t========================”;
count<< "Enter your choicein";
cin>>ch;
switch(ch)
{
case 1:
{
Polynomial X(3);
Polynomial Y(3);
clrscr();
cout<<“Enter the value for first Poly\n”;
X.GetCoeffs(cin);
cout<<“Enter the value for Second Poly\n”;
Y.GetCoeffs(cin);
cout<<“\n\tshow the First Polynomial\n\t”;
X.Show(cout);
line(2);
cout<<“\n\tshow the second Polynomial\n\t”;
Y.Show(cout);
line(2);
Polynomial Z(3);
Z=X+Y;
cout<<“\n\tShow the Add Polynomial\t”;
Z.Show(cout);
break;
}
case 2:
{
Polynomial X(3);
Polynomial Y(3);
clrscr();
cout<<“Enter the value for first Poly\n”;
15

X.GetCoeffs(cin);
cout<<“Enter the value for Second Poly\n”;
Y.GetCoeffs(cin);
cout<<“\n\tshow the First Polynomial\n\t”;
X.Show(cout);
line(2);
cout<<“\n\tshow the second Polynomial\n\t”;
Y.Show(cout);
line(2);
Polynomial Z(3);
Z=X-Y;
cout<<“\n\tview the Subtraction of two Polynomial\t”;
Z.Show(cout);
break;
}
case 3:
default:
exit(0);

}
}while(ch!=0);
}

Polynomial operator+(Polynomial& X, Polynomial& Y)


{
Polynomial Z;
if (X.power==Y.power)
{
Z=X;
for (int i=Y.power; i>=0; i—)
{
Z.coeffs[i]=X.coeffs[i]+Y.coeffs[i];
}
return Z;
}
16

else if(X.power<Y.power)
{
Z=Y;
for (int i=X.power; i>=0; i—)
{
Z.coeffs[i]=Y.coeffs[i];
}
return Z;
}
else if(X.power>Y.power)
{
Z=X;
for (int i=X.power; i>=0; i—)
{
Z.coeffs[i]=X.coeffs[i];
}
return Z;
}
return 0;
}
Polynomial operator-(Polynomial& X, Polynomial& Y)
{
Polynomial Z;
if (X.power==Y.power)
{
Z=X;
for (int i=Y.power; i>=0; i—)
{
Z.coeffs[i]=X.coeffs[i]-Y.coeffs[i];
}
return Z;
}
else if(X.power<Y.power)
{
Z=Y;
17

for (int i=X.power; i>=0; i—)


{
Z.coeffs[i]=Y.coeffs[i];
}
return Z;
}
else if(X.power>Y.power)
{
Z=X;
for (int i=X.power; i>=0; i—)
{
Z.coeffs[i]=X.coeffs[i];
}
return Z;
}
return 0;
}
int Polynomial::Coeff(int deg)
{

return coeffs[deg];
}

void line(int lines)


{
for (int i=0; i<lines; i++)
cout << endl;
}

void Polynomial::GetCoeffs(istream& in)


{
for (int i=power; i>=0; i—)
{
in >> coeffs[i];
}
18

in.ignore();
}

void Polynomial::Show(ostream& out)


{
for (int i=power; i>=0; i—)
{
if (coeffs[i]>=0)
{
if (i!=power)
out << “ + “;
out << coeffs[i];

}
else
{
if (coeffs[i]<0)
out << “ - “;
out << 0-coeffs[i];
}
if (i>1)
out << “x^” << i;
else if (i==1)
out << “x”;

}
}

Polynomial::Polynomial(const Polynomial& X)
{
coeffs=new int[X.power+1];
power=X.power;
for (int i=X.power; i>=0; i—)
{
coeffs[i]=X.coeffs[i];
19

}
Output
Enter the value for first Poly
3
3
3
3
Enter the value for Second Poly
1
1
1
1

show the First Polynomial


3x^3 + 3x^2 + 3x + 3

show the second Polynomial


1x^3 + 1x^2 + 1x + 1

Show the Add Polynomial 4x^3 + 4x^2 + 4x + 4


========================
1.addition of Polynomial
2.subtraction of Polynomial
3.Exit
========================
Enter your choice 2
Enter the value for first Poly
4
4
4
4
20

Enter the value for Second Poly


2
2
2
2

show the First Polynomial


4x^3 + 4x^2 + 4x + 4

show the second Polynomial


2x^3 + 2x^2 + 2x + 2

view the Subtraction of two Polynomial 2x^3 + 2x^2 + 2x + 2


========================
1.addition of Polynomial
2.subtraction of Polynomial
3.Exit
========================
Enter your choice 3

b. Pointer Method:

// ADDITION & MULTIPLICATION OF TWO POLYNOMIAL


#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#define NEXT(poly)poly->nxtpoly
typedef struct POLY
{
int coef,power;
struct POLY *nxtpoly;
}POLY;
POLY *insertpoly(int coef, int power,POLY *first)
{
POLY *NEW,*current,*prod;
26

Lesson 4
LINKED LIST
a. Write a C++ programming to implementation the single linked lists.

#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct link
{
int info;
struct link *next;
};
class Slink
{
private:
int i,number;
link start,*previous,*new1;
public:
void insertion(link *);
void create(link *);
void display(link *);
void delet(link *);
};
void Slink::create(link *node)
{
start.next=NULL;
node=&start;
i=0;
cout<<“\nInput Choice n for break:”;
char ch=getche();
while(ch!=’n’)
{
node->next=(struct link *)malloc(sizeof(struct link));
27

node=node->next;
cout<<“\nInput the node:”<<(i+1)<<“:”;
cin>>node->info;
node->next=NULL;
cout<<“\n Input Choice n For Break:”;
ch=getche();
i++;
}
}
void Slink::insertion(link *node)
{
node=start.next;
previous=&start;
new1=(struct link*)malloc(sizeof(struct link));
new1->next=node;
previous->next=new1;
cout<<“\nInput the first node value:”;
cin>>new1->info;
}
void Slink::display(link *node)
{
node=start.next;
cout<<“\nAfter inserting a node list is as follows:\n”;
cout<<“Address\t\tValue”;
while(node)
{
cout<<“\n”<<node;
cout<<“”<<node->info;
cout<<“\t”<<node->info;
node=node->next;
}
}
void Slink::delet(link *node)
{
node=start.next;
28

previous=&start;
if(node==NULL)
cout<<“\nUnder Flow\n”;
else
{
previous->next=node->next;
cout<<node->info<<“is deleted”;
free(node);
}
}

void main()
{
char choice;
clrscr();
Slink S;
link *node=(link *)malloc(sizeof(link));
do
{
cout<<“\nCreate\tInsertion\tDisplay\tdElete\teXit\n”;
cout<<“\nSelect UR Choice:”;
choice=getch();
cout<<choice;
switch(choice)
{
case ‘C’:
S.create(node);
break;
case ‘I’:
S.insertion(node);
break;
case ‘D’:
S.display(node);
break;
case ‘E’:
29

S.delet(node);
break;
case ‘X’:
exit(0);
cout<<“\n”;
break;
}
}while(choice!=’X’);
getch();
}

Output

Create Insertion Display dElete eXit

Select UR Choice:C
Input Choice n for break:
Input the node:1:2

Input Choice n For Break:3


Input the node:2:3

Input Choice n For Break:4


Input the node:3:4

Input Choice n For Break:n


Create Insertion Display dElete eXit

Select UR Choice:D
After inserting a node list is as follows:
Address Value
0x8fde0fb82 2
0x8fde0fc03 3
0x8fde0fc84 4
Create Insertion Display dElete eXit
30

Select UR Choice:I
Input the first node value:1

Create Insertion Display dElete eXit

Select UR Choice:D
After inserting a node list is as follows:
Address Value
0x8fde0fd01 1
0x8fde0fb82 2
0x8fde0fc03 3
0x8fde0fc84 4
Create Insertion Display dElete eXit

Select UR Choice:E
Create Insertion Display dElete eXit

Select UR Choice:D
After inserting a node list is as follows:
Address Value
0x8fde0fb82 2
0x8fde0fc03 3
0x8fde0fc84 4
Create Insertion Display dElete eXit

Select UR Choice:X

b. Write a C++ programming to Insert & Delete a desired node from Single
Linked List.
Source code:

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

enter the value & position to insert :95


3

parent->90->91->95->92->93->parent
enter the position to delete :4

parent->90->91->95->93->parent

d. Write a C++ Program for Creation, Insertion and Deletion in Doubly linked
list method

#include<iostream.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int info;
struct node *next,*back;
};

class list
{
struct node *root,*end;
public :
void createinfo();
void insert();
void delet();
void display();
};
void list::createinfo()
{
struct node *p,*n;
int t, s;

root=p=NULL;
42

s=sizeof(struct node);
cout<<“\n enter -999 to stop”;
cin>>t;
while(t!=-999)
{
n=(struct node *)malloc(s);
n->info=t;
n->next=NULL;
n->back=NULL;
if(root==NULL)
root=n;
else
{
p->next=n;
n->back=p;
}

p=n;
cout<<“\n enter -999 to stop”;
cin>>t;
}
end=n;
}

void list::display()
{
struct node *x=root;
cout<<“\n start->”;
while(x!=NULL)
{
cout<<x->info<<“->”;
x=x->next;
43

}
cout<<“end”;
x=end;
cout<<“\n back”;
while(x!=NULL)
{
cout<<x->info<<“->”;
x=x->back;
}
cout<<“end”;
}

void list::insert()
{
struct node *temp,*ex=root;
int value,pos,i=2;
cout<<“\n enter the value & position to insert :”;
cin>>value>>pos;
temp=(struct node *)malloc(sizeof(struct node));
temp->info=value;
temp->next=NULL;
temp->back=NULL;
if(pos==1)
{
temp->next=root;
root->back=temp;
root=temp;
}
else
{
while(ex->next!=NULL && i<pos)
{
ex=ex->next;
44

i++;
}
temp->next=ex->next;
temp->back=ex;
if(ex->next!=NULL)
ex->next->back=temp;
ex->next=temp;
if(temp->next==NULL)
end=temp;
}}

void list::delet()
{
struct node *ex=root;
int p,i=2;
cout<<“\n enter the position to delete :”;
cin>>p;
if(p==1)
{
root=root->next;
root->back=NULL;
}
else
{
while(ex->next!=NULL && i<p)
{
ex=ex->next;
i++;
}
if(ex->next->next!=NULL)
{
ex->next=ex->next->next;
ex->next->back=ex;
45

}
else
{
ex->next=NULL;
end=ex;
}}}

void main()
{
clrscr();
cout<<“\n\t\t OUT PUT\n”;
list one;
one.createinfo();
one.display();
one.insert();
one.display();
one.delet();
one.display();
getch();
}

OUT PUT

enter -999 to stop1

enter -999 to stop2

enter -999 to stop3

enter -999 to stop4

enter -999 to stop-999

start->1->2->3->4->end
back4->3->2->1->end
46

enter the value & position to insert :100 3

start->1->2->100->3->4->end
back4->3->100->2->1->end
enter the position to delete :2

start->1->100->3->4->end
back4->3->100->1->end

e. Write a C++ programming to implement sorting techniques using General


lists.

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

template <class Etype>


class Sorting
{
Etype *Array;
int Size;
public:
void GetData();
void Display();
void Swap(Etype &X,Etype &Y);
void Bubble();
void Insertion();
void Selection();
void QuickCall();
void Quick(int,int);
};

template <class Etype>


void Sorting<Etype>::GetData()
{
54

Lesson 5
IMPLEMENTATION OF STACK
a. Write a C++ programming to implementation of stack using arrays

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define n 100
int top=-1;
int flag=0;
class stacks
{
private:char stack[100];
int str1;
public:
void push(char*,char);
int pop(char*);
void display(char*);
};
//Definition of the push function
void stacks::push(char s[],char d)
{
if(top==(n-1))
flag=0;
else
{ flag=1; ++top;
s[top]=d;
}
}
//Definition of the pop function
int stacks:: pop(char s[])
{
int pop;
if(top==-1)
55

{
pop=0;
flag=0;
}
else
{flag=1;
pop=s[top];
—top;
}
return(pop);
}
//Display Function
void stacks::display(char s[])
{
if(top==-1)
{
cout<<“Stackis empty”;
}
else
{
for(int i=top;i>=0;—i)
cout<<“\n\t”<<s[i];
}
}
void main()
{
clrscr();
stacks sarray;
char stack[n];
char data;
int choice;
int q=0;
int top=-1;
do{
cout<<“\nPush=1 Pop=2 Quit=3”;
56

cout<<“\n\t’Select Your choice from 1 2 3:’”;


cin>>choice;
switch(choice)
{
case 1:
cout<<“\n Insert the character”;
cin>>data;
sarray.push(stack,data);
if(flag)
{
cout<<“\nAfter inserting”;
sarray.display(stack);
if(top==(n-1))
cout<<“\nStack is full”;
}
else
cout<<“\nStack overflow after pushing”;
break;
case 2: data=sarray.pop(stack);
if(flag)
{
cout<<“\nData is popped”<<data;
cout<<“\nRest data in stack is as follows”;
sarray.display(stack);
}
else
cout<<“\nStack underflow”;
break;
case 3: q=3;
}
}while(!q);
}

Output
Push=1 Pop=2 Quit=3
57

‘Select Your choice from 1 2 3:’1

Insert the charactera

After inserting
a
Push=1 Pop=2 Quit=3
‘Select Your choice from 1 2 3:’1

Insert the characterb

After inserting
b
a
Push=1 Pop=2 Quit=3
‘Select Your choice from 1 2 3:’1

Insert the characterc

After inserting
c
b
a
Push=1 Pop=2 Quit=3
‘Select Your choice from 1 2 3:’2

Data is poppedc
Rest data in stack is as follows
b
a
Push=1 Pop=2 Quit=3
‘Select Your choice from 1 2 3:’3
b. Write a C++ program to implement operations of a Stack using pointers

// PUSH POP OPERATIONS OF STACK USING POINTERS

#include<iostream.h>
58

#include<malloc.h>
#include<conio.h>
struct link
{
int info;
link *next;
};
class stack_link
{
private:link*start;
public:void display(link *);
link*push(link*);
link*pop(link*);
int main_menu();
};
void stack_link::display(link*rec)
{
while(rec!=NULL)
{
cout<<“\n”<<rec->info;
rec=rec->next;
}
}
link*stack_link::push(link*rec)
{
link*new_rec;
cout<<“\n Input the new value for next location of the stack:”;
new_rec=(link*)malloc(sizeof(link));
new_rec->next=rec;
cin>>new_rec->info;
new_rec->next=rec;
rec=new_rec;
return(rec);
}
link*stack_link::pop(link*rec)
59

{
link*temp;
if(rec==NULL)
{cout<<“\nStack is empty”;}
else
{
temp=rec->next;
free(rec);
rec=temp;
cout<<“\nAfter pop operation the stack is as follows:\n”;
display(rec);
if(rec==NULL)
cout<<“\n Stack is empty”;
}
return(rec);
}
int stack_link::main_menu()
{
int choice;
do
{
cout<<“\n 1<-push”;
cout<<“\n 2<-pop”;
cout<<“\m 3<-quit”;
cout<<“\n Input your choice:”;
cin>>choice;
if(choice<1||choice>3)
cout<<“\n incorrect choice-> try once again”;
}
while(choice<1||choice>3);
return(choice);
}
void main()
{
clrscr();
60

stack_link stack;
link*start;
int choice;
start=NULL;
do
{
choice=stack.main_menu();
switch(choice)
{
case 1:
start=stack.push(start);
cout<<“\n After push operation stack is as follows:”;
stack.display(start);
break;
case 2:
start=stack.pop(start);
break;
default:cout<<“\n End of session”;
}
}
while(choice!=3);
getch();
}

OUTPUT :

1<-push
2<-pop
3<-quit
Input your choice:1

Input the new value for next location of the stack:23

After push operation stack is as follows:m


23
61

1<-push
2<-pop
3<-quit
Input your choice:1

Input the new value for next location of the stack:45

After push operation stack is as follows:


45
23
1<-push
2<-pop
3<-quit
Input your choice:1

Input the new value for next location of the stack:56

After push operation stack is as follows:


56
45
23
1<-push
2<-pop
3<-quit
Input your choice:2

After pop operation the stack is as follows:

45
23
1<-push
2<-pop
3<-quit
Input your choice:3

End of session
66

Select the choice [1, 2, 3]:1


Insert the elementA
queue after inserting:A
1. INSERT 2. DELETE 3. QUIT
Select the choice [1, 2, 3]:1

Insert the element:B

queue after inserting:AB


1. INSERT 2. DELETE 3. QUIT
Select the choice [1, 2, 3]:1

Insert the element:C

queue after inserting:ABC


1. INSERT 2. DELETE 3. QUIT
Select the choice [1, 2, 3]:2
Elementis Deleted:A
queue after deleteion :BC
1. INSERT 2. DELETE 3. QUIT
Select the choice [1, 2, 3]:3

b. Write a C ++ program to implement operations of a queue using pointers


//Queue using pointers

#include<iostream.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
node *link;
};
struct queue
{
node *first;
67

node *last;
node *link_next;
};
struct Q
{
queue q;
node *qlink;
public:
void Initialise()
{
q.first=NULL;
q.last=NULL;
}
void insertqueue();
void deletequeue();
void display();
};
void Q::insertqueue()
{
qlink=new(node);
cout<<“Enter the node”;
cin>>qlink->data;
cout<<“Insert the node :”<<qlink->data;
qlink->link=NULL;
if((q.last)==NULL)
q.first=qlink;
else
q.last->link=qlink;
q.last=qlink;
}
void Q::deletequeue()
{
if(q.first==NULL)
{
cout<<“\tQueue is Empty”;
q.last=NULL;
68

}
else
{
qlink=q.first;
cout<<“\tDelete the node:”<<q.first->data;
q.first=q.first->link;
free(qlink);
}
}
void Q:: display()
{
if(q.first==NULL)
cout<<“Queue is Empty”;
else
{
cout<<“\nfirst”;
for(qlink=q.first;qlink!=NULL;qlink=qlink->link)
cout<<“==>”<<qlink->data;
cout<<“<==last\n”;
}
}
void main()
{
char choice;
Q mainqueue;
clrscr();
mainqueue.Initialise();
cout<<“\t\tQUEUE USING POINTER”;
cout<<“\n\tInsert\tDelete\tView\tExit”;
do {
cout<<“\nEnter your choice:\t”;
cin>>choice;
switch(choice)
{
case ‘I’: mainqueue.insertqueue();
break;
case ‘D’: mainqueue.deletequeue();
69

break;
case ‘V’: mainqueue.display();
break;
case ‘E’:
break;
default:
cout<<“Invalid choice”;
}
}while(choice!=’E’);
getch();
}

Output:

QUEUE USING POINTER


Insert Delete View Exit
Enter your choice: I
Enter the node100
Insert the node :100
Enter your choice: I
Enter the node200
Insert the node :200
Enter your choice: I
Enter the node300
Insert the node :300
Enter your choice: V

first==>100==>200==>300<==last

Enter your choice: D


Delete the node:100
Enter your choice: V

first==>200==>300<==last

Enter your choice: E


83

void main( )
{
char expr[M] ;
inprefix pfix ;
clrscr();
cout << “\nEnter an expression in infix form: “ ;
cin.getline ( expr, M ) ;

pfix.expr( expr ) ;
pfix.convert( ) ;

cout << “The Prefix expression is: “ ;


pfix.view( ) ;
}

output

Enter an expression in infix form: (a+b)*(a-b)


The Prefix expression is: * + a b - a b

C. Write a program to evaluate the given expressions.

Source code:

#include<iostream.h>

#include<conio.h>

#include<math.h>

#include<string.h>

#include<stdio.h>

#define M 30

#define symbol 10
84

#define str 20

typedef struct prepost

int top;

int s[M];

}Fix;

void init(Fix*);

void push(Fix*,int);

int pop(Fix*);

void eval(Fix*,char,int,int);

int gettype(char);

void main()

char str1[M];

int item1,item2,item,l,i,pr;

Fix stk;

fflush(stdin);

int k;

clrscr();

do{

cout<<“\n\t\tEvaluation of Expression.”;

cout<<“\n\t1:PreFix\t2:PostFix3:Exit \n\t”;

cin>>k;

switch(k)

case 1:
85

init(&stk);

cout<<“ ENTER THE PREFIX EXPRESSION “;

gets(str1);

l=strlen(str1);

for(i=l;i>=0;i—)

if(str1[i]==’ ‘ || str1[i]==’\0')

continue;

switch(gettype(str1[i]))

case symbol : item=str1[i]-’0';

push(&stk,item);

break;

case str : item1=pop(&stk);

item2=pop(&stk);

eval(&stk,str1[i],item1,item2);

cout<<“\n\tResult of prefix evaluation is:”;

cout<<stk.s[0];

getch();

break;

case 2:

init(&stk);
86

cout<<“ ENTER THE Postfix EXPRESSION “;

gets(str1);

l=strlen(str1);

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

if(str1[i]==’ ‘ || str1[i]==’\0')

continue;

switch(gettype(str1[i]))

case symbol : item=str1[i]-’0';

push(&stk,item);

break;

case str : item2=pop(&stk);

item1=pop(&stk);

eval(&stk,str1[i],item1,item2);

cout<<“\n\tResult of postfix evaluation is:”;

cout<<stk.s[0];

getch();

break;

case 3: k=3;

default:cout<<“\n End”;

}while (k!=3);

}
87

void init(Fix *stk )

stk->top=-1;

void push(Fix *st,int num)

st->top++;

st->s[st->top]=num;

int pop(Fix *st)

int item;

item=st->s[st->top];

st->top—;

return item;

void eval(Fix *st,char opr,int item1,int item2)

int res;

switch(opr)

case ‘+’: res=item1+item2;

break;

case ‘-’: res=item1-item2;


88

break;

case ‘*’: res=item1*item2;

break;

case ‘/’: res=item1/item2;

break;

case ‘%’: res=item1%item2;

break;

case ‘^’: res=pow(item1,item2);

break;

push(st,res);

int gettype(char c)

switch(c)

case ‘+’:

case ‘-’:

case ‘*’:

case ‘/’:

case ‘^’:

case ‘%’: return str;

default : return symbol;

}
89

Output

Evaluation of Expression.

1:PreFix 2:PostFix3:Exit

ENTER THE PREFIX EXPRESSION *+23-25

Result of prefix evaluation is:-15

Evaluation of Expression.

1:PreFix 2:PostFix3:Exit

ENTER THE Postfix EXPRESSION 23+25-*

Result of postfix evaluation is:-15

Evaluation of Expression.

1:PreFix 2:PostFix3:Exit

End
90

Lesson 9
TREE TRAVERSALS
a. To write a c++ program for Binary implementation and traversals using
recursion.
Traverse the given tree using Inorder, Preorder and Postorder traversals.

Example : Postorder Traversals

2 55

30

41

Postorder : 2 41 30 55 5

#include<iostream.h>
#include<alloc.h>
#include<stdlib.h>
#include<conio.h>
typedef struct tree *node;
node create(int ,node NODE);
void inorder(node NODE);
void preorder(node NODE);
void postorder(node NODE);
struct tree
{
int nodevalue;
struct tree *right,*left;
91

}*root;

void main()
{
node NODE= NULL;
int nodevalue,choice,i=0,num;
clrscr();
cout<<“\t\t\t**** BINARY TREE TRAVERSAL****\nEnter the number of Nodes to
form a Tree:”;
cin>>num;
cout<<“\n Enter the values for nodes\n”;
for(i=1;i<=num;i++)
{
cin>>nodevalue;
NODE=create(nodevalue,NODE);

cout<<“\n\t\t\t1.INORDER\n\t\t\t2.PREORDER\n\t\t\t3.POSTOTRDER\n\t\t\t4.EXIT\n”;
do
{
cout<<“\nEnter your choice:”;
cin>>choice;
switch (choice)
{
case 1:
cout<<“Inorder Traversal\n”;
inorder(NODE);
break;
case 2:
cout<<“Preoroder Traversal\n”;
preorder(NODE);
break;
case 3:
92

cout<<“Postorder Traversal\n”;
postorder(NODE);
break;
default:
cout<<“Exit”;
exit(0);
}

}
while(choice!=4);
getch();
}
node create(int X, node NODE)
{

struct tree *new1;


new1=(tree*)malloc(sizeof(struct tree));
if(new1==NULL)
cout<<“No Nodes are here\n”;
else
{
if(NODE==NULL)
{
new1->nodevalue=X;
new1->left=NULL;
new1->right=NULL;
NODE=new1;
}
else
{
if(X<NODE->nodevalue)
NODE->left=create(X,NODE->left);
else
NODE->right=create(X,NODE->right);
93

}
}
return NODE;
}
void inorder(node NODE)
{
if(NODE!=NULL)
{
inorder(NODE->left);
cout<<“\t”<<NODE->nodevalue;
inorder(NODE->right);
}
}
void preorder(node NODE)
{
if(NODE!=NULL)
{
cout<<“\t”<<NODE->nodevalue;
preorder(NODE->left);
preorder(NODE->right);
}
}
void postorder(node NODE)
{
if(NODE!=NULL)
{
postorder(NODE->left);
postorder(NODE->right);
cout<<“\t”<<NODE->nodevalue;
}
}
94

OUTPUT
**** BINARY TREE TRAVERSAL****
Enter the number of Nodes to form a Tree:5

Enter the values for nodes


5
55
2
30
41

1.INORDER
2.PREORDER
3.POSTOTRDER
4.EXIT

Enter your choice:1


Inorder Traversal
2 5 30 41 55
Enter your choice:2
Preoroder Traversal
5 2 55 30 41
Enter your choice:3
Postorder Traversal
2 41 30 55 5
Enter your choice:4

b. Write a C++ program to implementation Binary Search Trees.

#include<iostream.h>
#include<conio.h>
enum boolean { false=0,true=1};

struct node
95

{
int ele;
node *left,*right;
}*root=NULL;

class BST
{
node *par,*temp,*temp1;
node* newnode(int);
public:
void insert(int,node*,int);
boolean search(int,node*);
node* deletemin(node**);
void del(int,node**);
void display(node*);
};

node* BST::newnode(int x)
{
node *nod=new node;
nod->ele=x;
nod->left=nod->right=NULL;
return(nod);
}

void BST::insert(int x,node *cur,int pos)


{
if(cur == NULL)
{
cur=newnode(x);
if(pos==1)
par->left=cur;
else if (pos==2)
par->right=cur;
96

if(root==NULL)
root=cur;
}
else
{
par=cur;

if(x < cur->ele)


insert(x,cur->left,1);

else if(x > cur->ele)


insert(x,cur->right,2);
}}

boolean BST::search(int x,node *cur)


{
if(root == NULL)
return false;
else if(x == cur->ele)
return true;
else if(x < cur->ele && cur->left != NULL)
return (search(x,cur->left));
else if(x > cur->ele && cur->right != NULL)
return (search(x,cur->right));
return false;
}
node* BST::deletemin(node **cur)
{
if((*cur)->left==NULL)
{
temp=(*cur);
(*cur)=(*cur)->right;
}
97

else
temp=deletemin((&(*cur)->left));
return(temp);
}

void BST::del(int x,node **cur)


{
if((*cur)!=NULL)
{
if(x<(*cur)->ele)
del(x,(&(*cur)->left));
else if(x>(*cur)->ele)
del(x,(&(*cur)->right));

else // x == (*cur)->ele
{
if( ((*cur)->left==NULL) && ((*cur)->right==NULL) )
{
delete((*cur));
(*cur)=NULL; //must
}
else if((*cur)->left==NULL)
(*cur)=(*cur)->right;

else if((*cur)->right==NULL)
(*cur)=(*cur)->left;
else
{
temp1=(*cur)->left;
(*cur)=deletemin((&(*cur)->right));
(*cur)->left=temp1;
}
}
}
98

void BST::display(node *cur)


{
if(cur != NULL)
{
display(cur->left);
cout<<“\t”<<cur->ele;
display(cur->right);
}
}

void main()
{
int no,x,p;
BST bst;
clrscr();
do
{
cout<<“\n1:Insert\t2:Delete\t3:Search\t4:Display\t5:Exit\nSelect your option :”;
cin>>no;

switch(no)
{
case 1:
cout<<“\nEnter the no. to be inserted:”;
cin>>x;
bst.insert(x,root,0);
break;
case 2:
cout<<“\nEnter the element to be deleted : “;
cin>>x;
bst.del(x,&root);
break;
99

case 3:
cout<<“\nEnter the element to be searched :”;
cin>>x;
p=bst.search(x,root);
if(p==true)
cout<<“The element is in the BST\n”;
else
cout<<“The element is not in the BST\n”;
break;
case 4:
cout<<“\nThe elements in the list are\n”;
bst.display(root);
}

}while(no<5);

Output:

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :1
Enter the no. to be inserted:3

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :1
Enter the no. to be inserted:4

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :1
Enter the no. to be inserted:7

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :1
100

Enter the no. to be inserted:6

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :4

The elements in the list are


3 4 6 7
1:Insert 2:Delete 3:Search 4:Display 5:Exit
Select your option :2
Enter the element to be deleted : 3

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :4
The elements in the list are
4 6 7

1:Insert 2:Delete 3:Search 4:Display 5:Exit


Select your option :3
Enter the element to be searched :7

The element is in the BST


1:Insert 2:Delete 3:Search 4:Display 5:Exit
Select your option :3
Enter the element to be searched :10

The element is not in the BST Possition


1:Insert 2:Delete 3:Search 4:Display 5:Exit
Select your option :5

c. Write a C++ program for Breadth & Depth First Traversal in undirected
Graphs

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

Lesson 10
SHORTEST PATH
a) Write a program to find the Shortest distance [using Dijikstra’s algorithm]

Program purpose input the Vertix A as 0, Vertix B as 1, Vertix C as 2, Vertix D as 3, Vertix


E as 4, Vertix F as 5

Source code

#include<iostream.h>

#define INFINITY 9999

#include <stdio.h>

#include<stdlib.h>

#include<conio.h>

#define MAX 10

typedef struct node

struct node *next;

int vertex,weight;

}node;
109

node *G[10];//adjacency list

int n,t;// Number of vertices

void readgraph();

void insert(int vi,int vj,int w);

void dijkstra(int startnode);

void main()

int u,u1;

clrscr();

readgraph();

cout<<“\nEnter the starting node : “;

cin>>u;

dijkstra(u);

void dijkstra( int startnode)

int distance[MAX],pred[MAX];

int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far

// A node picked up for expansion is marked as visited[node no.]=1

//initialize

node *p;

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

distance[i]=INFINITY;
110

pred[i]=startnode;visited[i]=0;
}
distance[startnode]=0;
count=0;
while(count<=n)
{
mindistance=INFINITY ;
// nextnode is the node at minimum distance
for(i=0;i<n+1;i++)
if(distance[i] < mindistance && !visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exist through nextnode
visited[nextnode]=1;
for(p=G[nextnode];p!=NULL;p=p->next)
if(!visited[p->vertex])
if(mindistance+p->weight<distance[p->vertex])
{
distance[p->vertex]=mindistance+p->weight;
pred[p->vertex]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
111

cout<<“\n Distance of”<<i<<“=”<<distance[i];


cout<<“ Path = “<<i;
j=i;
do
{
j=pred[j];
cout<<“<- “<<j;
}while(j!=startnode);
}
}

void readgraph()
{ int i,j;
int adj[10][10];
cout<<“\nEnter no. of vertices :”;
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cout<<“\nEnter the distance for”<<i<<“to”<<j<<“:”;
cin>>adj[i][j];
}
}
//initialise G[] with NULL
for(i=0;i<n;i++)

G[i]=NULL;

for(i=0;i<n;i++) //create adjacency list


112

for(j=0;j<n;j++)
if(adj[i][j]!=0)
insert(i,j,adj[i][j]);
}

void insert(int vi,int vj,int w)


{
node *p,*q;
//acquire memory for the new node
q=(node *)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;
q->weight=w;
//insert the node in the linked list for the vertex no. vi
if(G[vi]==NULL)
G[vi]=q;
else
{
// go to the end of linked list
p=G[vi];
while(p->next!=NULL)
p=p->next;
p->next=q;
}

}
113

Sample

Input going to give as row by row manner

Node 0 1 2 3 4 5

0 0 7 0 0 14 9

1 7 0 15 0 0 8

2 0 15 0 4 0 6

3 0 0 4 0 9 0

4 14 0 0 9 0 2

5 9 8 6 0 2 0

Find the shortest distance from starting node 2 to destination.

Input
Enter no. of vertices :6
Enter the distance for0to0:0
Enter the distance for0to1:7
Enter the distance for0to2:0
Enter the distance for0to3:0
Enter the distance for0to4:14
Enter the distance for0to5:9
Enter the distance for1to0:7
Enter the distance for1to1:0
Enter the distance for1to2:15
Enter the distance for1to3:0
Enter the distance for1to4:0
Enter the distance for1to5:8
Enter the distance for2to0:0
Enter the distance for2to1:15
114

Enter the distance for2to2:0


Enter the distance for2to3:4
Enter the distance for2to4:0
Enter the distance for2to5:6
Enter the distance for3to0:0
Enter the distance for3to1:0
Enter the distance for3to2:4
Enter the distance for3to3:0
Enter the distance for3to4:9
Enter the distance for3to5:0
Enter the distance for4to0:14
Enter the distance for4to1:0
Enter the distance for4to2:0
Enter the distance for4to3:9
Enter the distance for4to4:0
Enter the distance for4to5:2
Enter the distance for5to0:9
Enter the distance for5to1:8
Enter the distance for5to2:6
Enter the distance for5to3:0
Enter the distance for5to4:2
Enter the distance for5to5:0
Enter the starting node : 2

Output

Passible Paths from source to destination and its corresponding total distance.
Distance of0=15 Path = 0<- 5<- 2
Distance of1=14 Path = 1<- 5<- 2
Distance of3=4 Path = 3<- 2
Distance of4=8 Path = 4<- 5<- 2
Distance of5=6 Path = 5<- 2

You might also like