Lab Manual DS and OOPS

100
1 K.RAMAKRISHNAN COLLEGE OF ENGINEERING SAMAYAPURAM, TRICHY – 621112. Data structures and Object Oriented Programming Lab (As per Anna University syllabus for CSE) LAB MANUAL 2008 Regulation

Transcript of Lab Manual DS and OOPS

Page 1: Lab Manual DS and OOPS

1

K.RAMAKRISHNANCOLLEGE OF

ENGINEERINGSAMAYAPURAM, TRICHY – 621112.

Data structures and Object Oriented Programming Lab

(As per Anna University syllabus for CSE)

LAB MANUAL

2008 Regulation

Page 2: Lab Manual DS and OOPS

2

III SEMESTER

Page 3: Lab Manual DS and OOPS

3

1.DEFAULT ARGUMENTS

Aim:

To implement a function with default arguments.Algorithm:

Step 1.Declare the default function.Step 2.Invoke the default function.Step 3.Display the  result

              Program:

#include<iostream.h>void printLine(char =’_’,int =70);void main(){printLine();printLine(‘/’);printLine(‘*’,40);printLine(‘R’,55);}void printLine(char ch, int Repeatcount){int i;cout<<endl;for(i=0;i<Repeatcount;i++)cout<<ch;}

Result: Thus the program to illustrate the default arguments has been implemented.

 

Output: 

- - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - - - / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / * * * * * * * * * * * * * * * * * * * * * * * * * * * *R R R R R R R R R R R R R R R R R R R R R R R

Page 4: Lab Manual DS and OOPS

4

 

2.CLASS WITH STATIC DATA MEMBER

Aim:

          To implement static data member in class. Algorithm:

Step 1.Create class ITEM with static data member as count.Step 2.Create a member function to increment the count.Step 3.Declare the static datamember using scope resolution operator.Step 4.Display the count value.

Program:#include<iostream.h>class item{static int count;int num;public:void getdata(int a){num=a;count++;cout<<”Number”<<num;}void showcount(){cout<<”count”;cout<<count<<”\n”;}};int item::count;int main(){item a,b,c;a.showcount();b.showcount();c.showcount();a.getdata(20);b.getdata(30);c.getdata(40);a.showcount();b.showcount();c.showcount();}

Page 5: Lab Manual DS and OOPS

5

Result:

Thus the program to illustrate static data member in a class has been implemented.

Output:count                            0count                            0count                            0Number              20Number              30Number              40count                            3count                            3count                            3

                            

Page 6: Lab Manual DS and OOPS

6

  3. PROGRAM FOR CALL BY VALUE

Aim: To Write a C++ program to illustrate Call by Value using a function.

Algorithm:

Step 1.Start the program

Step 2.Write the function and pass one value through that function

Step 3.Call that function in the main program

Step 4.Pass the value when we call that function

Step 5.Compile and run the program

Page 7: Lab Manual DS and OOPS

7

Program:

#include<iostream.h>#include<conio.h>void cube(int);int main (){clrscr();int num;cout << "Enter number: ";cin >> num;cube(num);getch();return 0;}void cube (int x){cout << "The number is " << x << endl;x *=x*x;cout << "The cube of the number is " << x << endl;}

Result:

Thus the program using Call by Value has been implemented.

Output:Enter number: 7The number is 7The cube of the number is 343

Page 8: Lab Manual DS and OOPS

8

4.OBJECT AS ARGUMENT AND RETURNING AN OBJECT

Aim:               To write a program for object as argument and returning an object using complex number addition. 

Algorithm: Step 1.The class complex contains two member variables real and imaginary. Step 2.Assign the value for real and imaginary part. Step 3.Declare a temporary variable temp. Step 4.Add real part with real of other object and store it in temp’s real. Step 5.Add imaginary part with imaginary of other object and store it in temp’s imaginary. Step 6.Display temp.

 Program:

#include<iostream.h>template<class T> class complex{private:              T real;T imag;Public:complex(){real=imag=0;}void getdata(){cout<<”real part?”;cin>>real;cout<<”imag part?”;cin>>imag;}complex operator +(complex c2);void outdata(char *msg){cout<<msg<<”(“<<real;cout<<”,”<<img<<”)”<<endl;}};Template<class T>

Page 9: Lab Manual DS and OOPS

9

complex<T> complex<T>::operator +(complex<T>c2){Complex<T>temp;temp.real=real+c2.real;temp.img=imag+c2.imag;return(temp);}void main(){complex<int>c1,c2,c3;cout<<”Addition of integercomplexobjects….”<<endl;cout<<”Enter complex number c1..”<<endl;c1.getdata();cout<<”Enter complex numberc2”<<endl;c2.getdata();c3=c1+c2;c3.outdata(“c3=c1+c2:”); complex<float>c4,c5,c6;cout<<”Additionof float complexobjects….”<<endl;cout<<”Enter complex number c4..”<<endl;c4.getdata();cout<<”Enterthecomplexnumberc5”<<endl;c5.getdata();c6=c4+c5;c6.outdata(“c6=c4+c5:”); }

Result:

Thus the program using object as argument has been implemented.  

Output:Addition of integer complexobjects…Enter complex number c1..Real part?1Imag part?2Enter complex number c2..Real part?3Imag part?4C3=c1+c2:(4,6) Addition of float complexobjects…Enter complex number c4..Real part?1.5Imag part?2.5Enter complex number c5..Real part?2.4Imag part?3.7

Page 10: Lab Manual DS and OOPS

10

C6=c4+c5:(3.9,6.2)  

5.FRIEND FUNCTION 

Aim:              To write a c++ program to illustrate usage of friend function. Algorithm:

Step 1. Create the class and declare the data member as private.Step 2. Declare the friend function using the keyword friend.

Step 3. Perform the operation of adding two private variables in the friend function.

Step 4. Display the result.Program:  #include <iostream.h>using namespace std;class myclass {int a, b;public:friend int sum(myclass x);void set_ab(int i, int j);};void myclass::set_ab(int i, int j){a = i;b = j;}// Note: sum() is not a member function of any class.int sum(myclass x){/* Because sum() is a friend of myclass, it candirectly access a and b. */return x.a + x.b;}int main(){myclass n;n.set_ab(3, 4);cout << sum(n);return 0;}

Result:

Thus the program using friend function has been implemented.

Page 11: Lab Manual DS and OOPS

11

 Output: 7

 

6.PROGRAM FOR MATRIX ADDITION

Aim: To Write a C++ program to add two matrices.

Algorithm:

Step 1.Start the program

Step 2.Create the class

Step 3.Declare the data member as array and member function

Step 4.Get the input and store it in an array

Step 5.Create the object for the class

Step 6.Call the function by using of the object

Step 7.The function perform the operation using the array data members

Step 8.Compile and execute the program

Program:

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

 main(){ clrscr(); int m, n, c, d, first[10][10], second[10][10], sum[10][10];  cout << "Enter the number of rows and columns of matrix "; cin >> m >> n; cout << "Enter the elements of first matrix\n";  for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) cin >> first[c][d];  cout << "Enter the elements of second matrix\n";  for ( c = 0 ; c < m ;c++ ) for ( d = 0 ; d < n ; d++ ) cin >> second[c][d];

Page 12: Lab Manual DS and OOPS

12

  for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = first[c][d] + second[c][d];  cout << "Sum of entered matrices:-\n";  for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) cout << sum[c][d] << "\t";  cout << endl; } getch();   return 0;}

Result:

Thus the program for adding two matrices has been implemented.

Output:

Enter the A matrix: 1 11 1Enter the B matrix:2 22 2 Addition of Two matrixes:3 33 3

   

Page 13: Lab Manual DS and OOPS

13

7.CLASS AND OBJECTSAim:              To write a c++ program for employee wages calculation using class and objects. Algorithm: 

Step 1.Employee class contains name and wage variable and member function a putname(), putwage(),getwage() and getname(). Step 2.Putname: Assign the valve for the character array name. Step 3.Getname: Retrieves the value of Variable name. Step 4.Putwage: Assign the valve for wage variable. Step 5.Getwage: Retrieves the value of wage variable. Step 6.In main() Put and display both name and wages.

    Program: #include <iostream.h>class employee {char name[80]; public:void putname(char *n); void getname(char *n);private:double wage; // now, private againpublic:void putwage(double w); // back to publicdouble getwage();};void employee::putname(char *n){strcpy(name, n);}void employee::getname(char *n){strcpy(n, name);}void employee::putwage(double w){wage = w;}double employee::getwage(){return wage;}int main()

Page 14: Lab Manual DS and OOPS

14

{employee ted;char name[80];ted.putname("Ted Jones");ted.putwage(75000);ted.getname(name);cout << name << " makes $";cout << ted.getwage() << " per year.";return 0;}

 

Result:

Thus the program for employee wages calculation has been implemented using classes and objects.

 

Output: Ted Jones makes $75000 per year.  

Page 15: Lab Manual DS and OOPS

15

8. PROGRAM TO IMPLEMENT FUNCTION OVERLOADING

Aim: To Write a C++ program to implement the function Overloading.

Algorithm:

Step 1.Start the program

Step 2.Create the function with same name

Step 3.The function will be differed in return type and number of arguments

Step 4.Implement the function, which has the same name

Step 5.Compile and execute the program

Program:

#include <iostream.h>

#include<conio.h>

int abs(int n);

double abs(double n);

int main()

{

clrscr();

cout << "Absolute value of -10: " << abs(-10) << endl;

cout << "Absolute value of -10.01: " << abs(-10.01) << endl;

getch();

return 0;

}

int abs(int n)

Page 16: Lab Manual DS and OOPS

16

{

cout << "In integer abs()\n";

return n<0 ? -n : n;

}

double abs(double n)

{

cout << "In double abs()\n";

return n<0 ? -n : n;

}

Result:

Thus the program for function overloading has been implemented.

Output:In integer abs()Absolute value of -10:10In double abs()Absolute value of -10.01:10.01

  

Page 17: Lab Manual DS and OOPS

17

9. PROGRAM TO IMPLEMENT CONSTRUCTOR AND DESTRUCTOR

Aim: To Write a C++ program to implement constructor and destructor.

Algorithm: Step 1: Create the stack class.

Step 2: Declare the constructor and destructor in the class

Step 3: Stack constructor definition.

Step 4: Stack destructor definition.

Step 5: Create the objects for the class stack. Objects automatically call the constructor for object initialization.

Step 6: Before program termination destructors are automatically called by compiler. It destroys the objects in memory.

Program:

#include<iostream.h>#define SIZE 100class stack{ int stck[SIZE]; int tos;public: stack(); //constructor ~stack(); //destructorvoid push(int i); int pop();};//stack’s constructor functionstack :: stack() { tos=0; cout<<”Stack Initialized\n”;}//stacks destructor functionstack :: ~stack()

Page 18: Lab Manual DS and OOPS

18

{ cout<<”\Stack Destroyed”;}void stack :: push(int i){if(tos==SIZE){ cout<<”Stack is full.\n”; return;}stck[tos] = i;tos++;}int stack :: pop (){if(tos==0){ cout<<”Stack underflow.\n”; return;}tos--;return stck[tos];}int main(){ stack a,b;a. push(1);b. push(2);a. push(3);b. push(4);cout<<a.pop()<< “ “;cout<<a.pop()<< “ “;cout<<b.pop()<< ” “;cout<<b.pop()<<”\n”;return 0;}

Result:

Thus the program for constructors and destructors has been implemented.

Output:Stack InitializedStack Initialized3 1 4 2Stack DestroyedStack Destroyed

Page 19: Lab Manual DS and OOPS

19

10. PROGRAM TO IMPLEMENT PAYROLL SYSTEM USING SINGLE INHERITANCE

Aim:

To write a program to find out the payroll system using single inheritance.

Algorithm: Step 1: Start the program.Step 2: Declare the base class emp.Step 3: Define and declare the function get() to get the employee details.Step 4: Declare the derived class salary.Step 5: Declare and define the function get1() to get the salary details.Step 6: Define the function calculate() to find the net pay.Step 7: Define the function display().Step 8: Create the derived class object.Step 9: Read the number of employees.Step 10: Call the function get(),get1() and calculate() to each employees.Step 11: Call the display().Step 12: Stop the program.

Program:#include<iostream.h>#include<conio.h> class emp{   public:     int eno;     char name[20],des[20];     void get()     {              cout<<"Enter the employee number:";              cin>>eno;              cout<<"Enter the employee name:";              cin>>name;              cout<<"Enter the designation:";              cin>>des;     }}; class salary:public emp{     float bp,hra,da,pf,np;   public:     void get1()     {                           cout<<"Enter the basic pay:";              cin>>bp;

Page 20: Lab Manual DS and OOPS

20

              cout<<"Enter the Humen Resource Allowance:";              cin>>hra;              cout<<"Enter the Dearness Allowance :";              cin>>da;              cout<<"Enter the Profitablity Fund:";              cin>>pf;     }     void calculate()     {              np=bp+hra+da-pf;     }     void display()     {             cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<np<<"\n";     }}; void main(){    int i,n;    char ch;    salary s[10];    clrscr();    cout<<"Enter the number of employee:";    cin>>n;    for(i=0;i<n;i++)    {              s[i].get();              s[i].get1();              s[i].calculate();    }    cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";    for(i=0;i<n;i++)    {              s[i].display();    }    getch(); }

Output: Enter the Number of employee:1Enter the employee No: 150Enter the employee Name: ramEnter the designation: ManagerEnter the basic pay: 5000Enter the HR allowance: 1000Enter the Dearness allowance: 500Enter the profitability Fund: 300 E.No   E.name   des      BP    HRA   DA   PF     NP150    ram      Manager  5000  1000  500  300    6200

Page 21: Lab Manual DS and OOPS

21

1.SINGLY LINKED LISTAim:

To write a program to implement singly linked list.

Algorithm:Step 1: Start the program.Step 2: Define a structure with name.branch,examno as members of the structure.Step 3: add():add a new record by creating new node using malloc().Step 4:del():if (head==NULL) then No records are there to delete.Step 5: if records are there traverse through the list using (delet=head;delet!=NULL;delet=delet->next) and display the record to be deleted.Step 6: display():if (head==NULL) then No records are there to display if records are there traverse through the list using (disp=head;disp!=NULL;disp=disp->next) and display the records in the list.

Step 7: modify():if (head==NULL) then No such records are there to modify. if records are there traverse through the list using (modify=head;modify!=NULL;modify=modify->next) and display the records in the list.

Step 8: view():if (head==NULL) then No such records are there to display. if records are there traverse through the list using (disp=head;disp!=NULL;disp=disp->next) and display the records in the list.

Step 9: Stop the program.

Program:

#include<stdio.h>#include<conio.h>void add();void del();void mod();void view();

struct info{ char name[20];char branch[10];int examno;struct info*next;}*head,*temp,*disp;

Page 22: Lab Manual DS and OOPS

22

void main( ){ int choice,n;clrscr( );do{ printf("\n\n\t\t\t\tMENU\n\t\t\t\t~~~~\n\n\n");printf("\n\t1-ADD\t 2-DELETE\t3-MODIFY\t4-DISPLAY\t5-EXIT\n\n\n");printf("ENTER YOUR CHOICE\t=\t");scanf("%d",&choice);switch(choice){case 1:clrscr();add();break;case 2:clrscr();del();break;case 3:clrscr();mod();break;case 4:clrscr();view();break;case 5:exit(0);}}while(choice<5);}void add(){ struct info *add;int r,proceed=1;while(proceed==1){ add=(struct info*) malloc(sizeof(struct info));printf("\nEnter the Name \t=");scanf("%s",add->name);printf("\nEnter the branch \t=");scanf("%s",add->branch);printf("\nEnter the Exam No\t=");scanf("%d",&add->examno);if(head==NULL){head=add;add->next=NULL;temp=add;}else{ temp->next=add;add->next=NULL;temp=add;}printf("\nDO U WANT TO PROCEED ?(0 -NO or 1 - YES)");scanf("%d",&r);proceed=r;}

Page 23: Lab Manual DS and OOPS

23

return;}void del( ){ struct info *delet;int exno,present=0;if(head==NULL){ printf("\n NO Records to delete");return;}printf("\n ENTER THE EXAM NO = ");scanf("%d",&exno);for(delet=head;delet!=NULL;delet=delet->next){ if(delet->examno==exno){present=1;if(head->examno==exno){delet=head;head=head->next;free(delet);return;}else{for(disp=head;disp!=NULL;disp=disp->next)if(disp->next==delet){disp->next=delet->next;free(delet);if(disp->next==NULL)temp=disp;return;}}}}if(present==0)printf("\n NO SUCH EXAM NO PRESENT");return;}

void mod(){struct info *modify;int exno,present=0;if(head==NULL){

Page 24: Lab Manual DS and OOPS

24

printf("\nNO RECORDS TO MODIFY");return;}printf("\nEnter The EXAM NO To Modify =");scanf("%d",&exno);for(modify=head;modify!=NULL;modify=modify->next)if(modify->examno==exno){present=1;printf("\nEnter The Name to Change =");scanf("%s",modify->name);printf("\nEnter the branch To Change =");scanf("%s",modify->branch);printf("\nEnter the EXAM NO To Change =");scanf("%d",&modify->examno);}if(present==0)printf("\n NO SUCH EXAM NO FOUND");return;}

void view(){if(head==NULL){ printf("\n NO RECORDS TO DISPLAY");return;}printf("\n\n\n");printf("\tEX-NO\t\tNAME\t\tBRANCH\n");printf("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");for(disp=head;disp!=NULL;disp=disp->next){ printf("\t%d\t\t%s\t\t%s\n",disp->examno,disp->name,disp->branch);}return;getch();}

Page 25: Lab Manual DS and OOPS

25

Output:

MENU ~~~~

1-ADD 2-DELETE 3-MODIFY 4-DISPLAY 5-EXIT

ENTER YOUR CHOICE =1

Enter the Name =rosy

Enter the branch =it

Enter the Exam No =321

ENTER YOUR CHOICE =4Name branch Exam No rosy it 321

Page 26: Lab Manual DS and OOPS

26

Page 27: Lab Manual DS and OOPS

27

Page 28: Lab Manual DS and OOPS

28

Page 29: Lab Manual DS and OOPS

29

*.STACK USING ARRAY IMPLEMENTATIONAim:              To write a program for stack using array implementation. Algorithm :

           Step1:Define a array which stores stack elements..

          Step 2: The operations on the stack area)PUSH data into the stack         b)POP data out of stack Step  3:  PUSH DATA INTO STACK

                   3a.Enter the data to be inserted into stack.                   3b.If TOP is NULL                         the input data is the first node in stack.                         the link of the node is NULL.                        TOP points to that node.                   3c.If TOP is NOT NULL                        the link of TOP points to the new node.                        TOP points to that node.

           Step 4:   POP DATA FROM STACK                   4a.If TOP is NULL                        the stack is empty                   4b.If TOP is NOT NULL                        the link of TOP is the current TOP.                        the pervious TOP is popped from stack.

            Step 5.  The stack represented by linked list is traversed to display its content. 

 

PROGRAM:#include<stdio.h>#include<conio.h>#define SIZE 5

Page 30: Lab Manual DS and OOPS

30

int  stack[SIZE],top=-1;void push();void pop();void display();void main(){int choice;int isempty();int length();clrscr();while(1){              printf(“\n 1.Push”);              printf(“\n 2. POP”);              printf(“\n 3.Display”);              printf(“\n 4. Length ”);              printf(“\n 5.Quit”);              printf(“\n Enter the choice:”);              scanf(“\n %d”,&choice);              switch(choice)              {                            case 1: push();                                         break;

case 2: pop();              break;case 3: display();             break;case 4: printf(“\n No. of elements in the stack is %d”,length());             break;case 5: exit(0);             break;default: printf(“\n Invalid choice”);

                            }              }} void push(){              int n;if(top==SIZE-1)printf(“\n Stack is full”);else{

printf(“\nEnter the no.”);scanf(“%d”,&n);top++;stack[top]=n;

}} 

Page 31: Lab Manual DS and OOPS

31

void pop(){              int n;              if(isempty()){

printf(“\nStack is empty”);top=-1;

}else{              n=stack[top];             

printf(“\n %d is popped from the stack \n”,n);--top;

}} void display(){              int i,temp=top;if(isempty()){

printf(“\n Stack Empty”);return;

              }printf(“\n Elements in the stack:”);for(i=temp;i>=0;i--)printf(“%d \n”,stack[i]);} int isempty(){              return (top==-1);}int length(){              return (top+1);}            Output: 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 1 Enter the no. 10

Page 32: Lab Manual DS and OOPS

32

 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 1 Enter the no. 20 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 1 Enter the no. 30 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 1 Enter the no. 40 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 3 Elements in the stack:40302010 1.Push2. POP3.Display4. Length5.Quit

Page 33: Lab Manual DS and OOPS

33

 Enter the choice: 2 40 is popped from the stack 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 4Number  of elements in the stack is 3 1.Push2. POP3.Display4. Length5.Quit Enter the choice: 5            

*STACK USING LINKED LISTAim:              To write a program for stack using linked list implementation. Algorithm :

           Step1:Define a C-struct for each node in the stack. Each node in the stack                      contains data and link to the next node. TOP pointer points to last                     node inserted in the stack.

          Step 2: The operations on the stack are         a)PUSH data into the stack         b)POP data out of stack 

         Step  3:  PUSH DATA INTO STACK                   3a.Enter the data to be inserted into stack.

Page 34: Lab Manual DS and OOPS

34

                   3b.If TOP is NULL                         the input data is the first node in stack.                         the link of the node is NULL.                        TOP points to that node.                   3c.If TOP is NOT NULL                        the link of TOP points to the new node.                        TOP points to that node.

           Step 4:   POP DATA FROM STACK                   4a.If TOP is NULL                        the stack is empty                   4b.If TOP is NOT NULL                        the link of TOP is the current TOP.                        the pervious TOP is popped from stack.

            Step 5.  The stack represented by linked list is traversed to display its content. 

          PROGRAM:# include<stdio.h># include<conio.h>

struct node{int info;struct node *link;} *top=NULL;

main(){int choice;while(1){ printf("1.Push\n");printf("2.Pop\n");printf("3.Display\n");printf("4.Quit\n");printf("Enter your choice : ") ;scanf("%d", &choice);

switch(choice){

Page 35: Lab Manual DS and OOPS

35

case 1:push();break;case 2:pop();break;case 3:display();break;case 4:exit(1);default :printf("Wrong choice\n");}/*End of switch */}/*End of while */}/*End of main() */

push(){struct node *tmp;int pushed_item;tmp = (struct node *)malloc(sizeof(struct node));printf("Input the new value to be pushed on the stack : ");scanf("%d",&pushed_item);tmp->info=pushed_item;tmp->link=top;top=tmp;}/*End of push()*/

pop(){struct node *tmp;if(top == NULL)printf("Stack is empty\n");else{ tmp=top;printf("Popped item is %d\n",tmp->info);top=top->link;free(tmp);}

}/*End of pop()*/

display(){ struct node *ptr;ptr=top;if(top==NULL)printf("Stack is empty\n");else{

Page 36: Lab Manual DS and OOPS

36

printf("Stack elements :\n");while(ptr!= NULL){printf("%d\n",ptr->info);ptr = ptr->link;}/*End of while */}/*End of else*/}/*End of display()*/           Output: 1.Push2. POP3.Display5.Quit Enter the choice: 1 Input the new value to be pushed on the stack :. 10  1.Push2. POP3.Display5.Quit Enter the choice: 1 Input the new value to be pushed on the stack : 20 1.Push2. POP3.Display5.Quit Enter the choice: 1 Input the new value to be pushed on the stack : 30 1.Push

Page 37: Lab Manual DS and OOPS

37

2. POP3.Display5.Quit Enter the choice: 1 Input the new value to be pushed on the stack :  40 1.Push2. POP3.Display5.Quit Enter the choice: 3 Elements in the stack:40302010 1.Push2. POP3.Display5.Quit Enter the choice: 2 40 is popped from the stack 1.Push2. POP3.Display5.Quit Enter the choice: 5              

Page 38: Lab Manual DS and OOPS

38

         

 *QUEUE USING ARRAY

Aim:              To write a program for Queue using array implementation. Algorithm :

           Step1:Define a array which stores queue elements..

          Step 2: The operations on the queue are         a)INSERT data into the queue         b)DELETE data out of queue 

         Step  3:  INSERT DATA INTO queue                   3a.Enter the data to be inserted into queue.                   3b.If TOP is NULL                         the input data is the first node in queue.                         the link of the node is NULL.                        TOP points to that node.                   3c.If TOP is NOT NULL                        the link of TOP points to the new node.                        TOP points to that node.

           Step 4:   DELETE DATA FROM queue                   4a.If TOP is NULL                        the queue is empty                   4b.If TOP is NOT NULL                        the link of TOP is the current TOP.                        the pervious TOP is popped from queue.

            Step 5.  The queue represented by linked list is traversed to display its content. 

      

Page 39: Lab Manual DS and OOPS

39

           PROGRAM:# include<stdio.h># define MAX 5

int queue_arr[MAX];int rear = -1;int front = -1;

main(){int choice;while(1){printf("1.Insert\n");printf("2.Delete\n");printf("3.Display\n");printf("4.Quit\n");printf("Enter your choice : ");scanf("%d",&choice);

switch(choice){case 1 :insert();break;case 2 :del();break;case 3:display();break;case 4:exit(1);default:printf("Wrong choice\n");}/*End of switch*/}/*End of while*/}/*End of main()*/

insert()

Page 40: Lab Manual DS and OOPS

40

{int added_item;if (rear==MAX-1)printf("Queue Overflow\n");else{if (front==-1) /*If queue is initially empty */front=0;printf("Input the element for adding in queue : ");scanf("%d", &added_item);rear=rear+1;queue_arr[rear] = added_item ;}}/*End of insert()*/

del(){if (front == -1 || front > rear){printf("Queue Underflow\n");return ;}else{printf("Element deleted from queue is : %d\n", queue_arr[front]);front=front+1;}}/*End of del() */

display(){int i;if (front == -1)printf("Queue is empty\n");else{printf("Queue is :\n");for(i=front;i<= rear;i++)printf("%d ",queue_arr[i]);printf("\n");}}/*End of display() */        

Page 41: Lab Manual DS and OOPS

41

  Output: 1.Insert2.Delete3.Display4.QuitEnter your choice:1 Input the element for adding in queue :10 1.Insert2.Delete3.Display4.QuitEnter your choice:1 Input the element for adding in queue :20 1.Insert2.Delete3.Display4.QuitEnter your choice:1 Input the element for adding in queue :30 1.Insert2.Delete3.Display4.QuitEnter your choice:1 Input the element for adding in queue :40 1.Insert2.Delete3.Display4.QuitEnter your choice:3 Queue is :40302010 1.Insert2.Delete

Page 42: Lab Manual DS and OOPS

42

3.Display4.QuitEnter your choice:2  Element deleted from queue is :10 1.Insert2.Delete3.Display4.QuitEnter your choice:3 Queue is :403020 1.Insert2.Delete3.Display4.QuitEnter your choice:4                    

QUEUE OPERATIONS USING LINKED LISTAim:              To write a program for Queue using Linked implementation. Algorithm :

           Step1: Define a C-struct for each node in the queue. Each node in the queue

Page 43: Lab Manual DS and OOPS

43

                     contains data and link to the next node. Front and rear pointer points to first and last                     node inserted in the queue.

          Step 2: The operations on the queue are         a)INSERT data into the queue         b)DELETE data out of queue 

         Step  3:  INSERT DATA INTO queue                   3a.Enter the data to be inserted into queue.                   3b.If TOP is NULL                         the input data is the first node in queue.                         the link of the node is NULL.                        TOP points to that node.                   3c.If TOP is NOT NULL                        the link of TOP points to the new node.                        TOP points to that node.

           Step 4:   DELETE DATA FROM queue                   4a.If TOP is NULL                        the queue is empty                   4b.If TOP is NOT NULL                        the link of TOP is the current TOP.                        the pervious TOP is popped from queue.

            Step 5.  The queue represented by linked list is traversed to display its content. 

               PROGRAM:#include<stdio.h>#include<malloc.h>#define MAXSIZE 10

void insertion();void deletion();void display();

Page 44: Lab Manual DS and OOPS

44

struct node{int info;struct node *link;}*new,*temp,*p,*front=NULL,*rear=NULL;typedef struct node N;

main(){int ch;do{printf("\n\t\t\tLinked queue");printf("\n 1.Insertion");printf("\n 2.Deletion");printf("\n 3.Display");printf("\n 4.Exit");printf("\n Enter your choice : ");scanf("%d",&ch);switch(ch){case 1:insertion();break;case 2:deletion();break;case 3:display();break;default:break;}}while(ch<=3); } void insertion(){int item; new=(N*)malloc(sizeof(N)); printf("\nEnter the item : "); scanf("%d",&item); new->info=item;new->link=NULL;if(front==NULL)front=new;elserear->link=new;rear=new;

Page 45: Lab Manual DS and OOPS

45

}

void deletion(){if(front==NULL)printf("\nQueue is empty");else{p=front;printf("\nDeleted element is : %d",p->info);front=front->link;free(p);}}

void display(){if(front==NULL)printf("\nQueue is empty");else{printf("\nThe elements are : ");temp=front;while(temp!=NULL){printf("%d",temp->info);temp=temp->link;}}}  Output: 1.Insertion2.Deletion3.Display4.ExitEnter your choice:1Enter the item :10 1.Insertion2.Deletion3.Display4.ExitEnter your choice:1Enter the item :20 1.Insertion2.Deletion

Page 46: Lab Manual DS and OOPS

46

3.Display4.ExitEnter your choice:1Enter the item :30 1.Insertion2.Deletion3.Display4.ExitEnter your choice:1Enter the item :40 1.Insertion2.Deletion3.Display4.ExitEnter your choice:3 The elements are :40302010 1.Insertion2.Deletion3.Display4.ExitEnter your choice:2 Deleted element is : 10 1.Insertion2.Deletion3.Display4.ExitEnter your choice:3 The elements are :403020 1.Insertion2.Deletion3.Display4.ExitEnter your choice:4  

Page 47: Lab Manual DS and OOPS

47

                        

LINKED LIST IMPLEMENTATION USING LIST AIM:  To implement a linked list and do all operations on it. ALGORITHM: Step 1 : Start the process. Step 2: Initialize and declare variables. Step 3: Enter the choice. INSERT / DELETE. Step 4: If choice is INSERT then

a. Enter the element to be inserted. 

b. Get a new node and set DATA[NEWNODE] = ITEM. 

c. Find the node after which the new node is to be inserted.  

d. Adjust the link fields. 

e. Print the linked list after insertion. Step 5: If choice is DELETE then

Page 48: Lab Manual DS and OOPS

48

 a. Enter the element to be deleted.

 b. Find the node containing the element (LOC) and its preceding node (PAR).

 c. Set  ITEM = DATA[LOC] and delete the node LOC.

 d. Adjust the link fields so that PAR points to the next element. ie

LINK[PAR] = LINK [ LOC]. 

e. Print the linked list after deletion.  Step 6: Stop the process.        Program: #include<stdio.h>#include<stlib.h>#include<conio.h> struct node;typedef struct node *ptr;typedef ptr list;typedef ptr position;typedef int data; struct node{              data element;              struct node *next;} //function prototypesvoid makeempty(void);              //to make empty listint isempty(void);                            //to check list is empty or notvoid create(void);                            //to create initial set of elementsposition findprevious(data);              //to find position of previous elementvoid delet(data);                            //to delete given elementvoid display(void);                            //to display all the elementsvoid insert(data, int);                            //to insert a new elementposition getprevposition(int);              //to find position of previous elementdata getelement(int);                            //to find the element at given positionint getposition(data);                            //to find position of given element //global variable declarations

Page 49: Lab Manual DS and OOPS

49

position first;position last;position L;int length; //to make empty listvoid makeempty(void){              position tmp;              tmp = malloc(sizeof(list));              tmp->next = NULL;              L = tmp;              first = last = NULL;}  //to check list is empty or notint isempty(void){              if (L->next = NULL)                            return 1;              else                            return 0;} //to create initial set of elementsvoid create(void){              data e;              int n, i;              position tmp;              makeempty();              printf(“Enter number of element : \              “);              scanf(“%d”, &n);              for (i=0; i<n; i++)              {                            printf(“Enter an element : “);                            scanf(“%d”, &e);                            tmp = malloc(sizeof(list));                            tmp->element = e;                            tmp->next = NULL;                            if (L->next == NULL)                            {                                          L->next = tmp;                                          first = last = tmp;                            }                            else                            {                                          last->next = tmp;                                          last = tmp;

Page 50: Lab Manual DS and OOPS

50

                            }              }} //to display all the elementsvoid display(){              position t;              for(t=first; t!=NULL; t=t->next)                            printf(“%d --> “, t->element);              getch();}//to find position of previous elementposition getprevposition(int index){              position tmp;              int count = 1;              if (index>length)              {                            printf(“Invalid Position”);                            return NULL;              }              else              {                            for (tmp=first; count<index-1; tmp=tmp->next)                                          count++;                            return tmp;              }} //to insert a new elementvoid insert(data x, int p){              position pos, tmp;              tmp = malloc(sizeof(list));              tmp->element=x;              if (p==1)                            //first position              {                            tmp->next = first;                            L->next = tmp;                            first = tmp;                            length++;              }              else if (p == length)              //last position              {                            last->next = tmp;                            last = tmp;                            tmp->next = NULL;              }              else                                          //arbitrary position

Page 51: Lab Manual DS and OOPS

51

              {                            pos = getpreviousposition(p);                            if (pos == NULL)                            {                                          printf(“Invalid position”);                                          getch();                            }                            else                            {                                          tmp->next = pos->next;                                          pos->next = tmp;                                          length++;                            }              }} //to find position of previous elementposition findprevious(data x){              position p;              p = L;              while (p->next->element!=x && p->next!=NULL)                            p = p->next;              return p;} //to delete given elementvoid delet(data x){              position p, tmp;              if (isempty())              {                            printf(“List is empty”);                            getch();              }              else              {                            p = findprevious(x);                            if (p->next = NULL)                            {                                          printf(“Element not found”);                                          getch();                            }                            else                            {                                          if (p->next == last)                                          {                                                        free (p->next);                                                        p->next =  NULL;                                                        last = p;

Page 52: Lab Manual DS and OOPS

52

                                                        length--;                                                        return;                                          }                                          if (p == L)                                          {                                                        first = first->next;                                          }                                          tmp = p->next;                                          p->next = tmp->next;                                          free(tmp);                                          length--;                            }              }} int menu(){              int ch;              printf(“1. Create\n2. Display\n3.Insert\n4.Get Element\n5.Get Position\n6. Delete\n7. Exit\n\n Enter your choice : “);              scanf(“%d”, &choice);              return choice;} //to find the element at given positiondata getelement(int pos){              position p;              int i;              p = L;              if (pos > length)                            return NULL;              else              {                            for(i=0; i<pos; i++)                                          p = p->next;                            return p->element;              }} //to find position of given elementint getposition(data e){              position p;              int i=0;              for (p=first; p!=NULL; p=p->next)              {                            if (p->element == e)                                          return i+1;                            else

Page 53: Lab Manual DS and OOPS

53

                                          i++;              }              return NULL;} void main(){              int ch;              data n, p;              while(1)              {                            clrscr();                            ch = menu();                            switch (ch)                            {                                          case 1:                                                        create();                                                        break;                                          case 2:                                                        display();                                                        break;                                          case 3:                                                        printf(“Enter an element : “);                                                        scanf(“%d”, &n);                                                        printf(“Enter Position : “);                                                        scanf(“%d”, &p);                                                        insert (n, p);                                                        break;                                          case 4:                                                        printf(“Enter an element : “);                                                        scanf(“%d”, &n);                                                        delet (n);                                                        break;                                          case 5:                                                        printf(“Enter position : “);                                                        scanf(“%d”, &p);                                                        if (p<1 || p>length)                                                                      printf(“Invalid position”);                                                        else

printf(“Element at position %d is %d”, p, getelement(p));                                                        getch();                                                        break;                                          case 6:                                                        printf(“Enter an element : “);                                                        scanf(“%d”, &n);                                                        if (getposition(n) == NULL)                                                                      printf(“Element doesn’t Exist”);                                                        else                                                                      printf(“%d exists at position %d”, n, getposition(n));

Page 54: Lab Manual DS and OOPS

54

                                                        getch();                                                        break;                                          default:                                                        printf(“Invalid Choice”);                                                        getch();                            }              }}           

 Output: 

1. Create1. Display2. Insert3. Delete4. Get element5. Get position6. Exit

Page 55: Lab Manual DS and OOPS

55

 Enter your Choice: 1 Enter number of element: 3Enter an element: 10Enter an element: 20Enter an element: 30  Enter your Choice: 3 Enter element: 25Enter Position: 3  Enter your Choice: 2 10 --> 20 --> 25 --> 30  Enter your Choice: 6 Enter an element:2020 exists at position 2  Enter your Choice: 4 Enter an element 30  Enter your Choice: 2 10 --> 20 --> 25  Enter your Choice: 6                

CURSOR IMPLEMENTATION – LIST  Aim:              To write a c program for cursor implementation of list. Algorithm: 

1. Start the program. 2. Create a node with two fields data and link field.

Page 56: Lab Manual DS and OOPS

56

o Allocate space for the node dynamically. o Create link between the created nodes and let the last node be with NULL

Link o Insert the input data in the data field and press –1 to stop the same.

3. Get the choice of operations either insertion or deletion. 4. For insertion get the position in which insertion is to be done and the element to

be inserted. Check for the start, middle or end position of insertion. Insert the node and change its link accordingly.

5. For deletion get the position in which deletion is to be done. Delete the node and then link it to the next node. Before deletion check whether there is data in the list to be deleted.

6. Using display option list the elements of the list. 7. Stop the program.

          

Program: #include<stdio.h>#include<conio.h>struct cursor{char data;int next;}c[10];int fp=0;void create(){char a;int p,i;   for(i=0;i<10;i++)  {     c[i].data=' ';

Page 57: Lab Manual DS and OOPS

57

     c[i].next=-1;  }printf("Enter the first element to be inserted");scanf("%c",&a);printf("Enter the position");scanf("%d",&p);fp=p;c[p].data=a;c[p].next=0;}void insert(char a,int pos){int i;   if(c[pos].next==-1)    {              c[pos].data=a;      for(i=0;i<10;i++)      {              if(c[i].next==0)              {                c[i].next=pos;              }      }      c[pos].next=0;    }    else     printf("\n Already data is available");}  void display(){int i;i=fp;do{printf("%d\t",i);printf("%c\t",c[i].data);printf("%d\n",c[i].next);i=c[i].next;}while(i>0);}void del(){  int temp,i;  char d;  printf("\n Enter the character to be deleted");  d=getch();  if(c[fp].data==d)

Page 58: Lab Manual DS and OOPS

58

  {   c[fp].data=' ';   temp=c[fp].next;   c[fp].next=-1;   fp=temp;  }  else  {   i=fp;   do   {   if(c[c[i].next].data==d)    {     temp=c[i].next;     c[i].next=c[c[i].next].next;     c[temp].next=-1;    }    i=c[i].next;    }    while(i>0);    }}      void main(){int opt,p;char a;clrscr();create();do{printf("\n 1.Insert");printf("\n 2.Delete");printf("\n 3.Display");printf("\n 4.Exit");printf("\n Enter your choice");scanf("%d",&opt);              switch(opt)              {                     case 1:                              printf("\nEnter the element to be inserted");                              a=getch();                              printf("\nEnter the position");                              scanf("%d",&p);                            insert(a,p);

Page 59: Lab Manual DS and OOPS

59

                              break;                       case 2:                              del();                            break;                     case 3:                          display();                          break;              }     }  while(opt<4);}         Output:1.Insert2.Delete3.Display4.ExitEnter your choice:1 Enter the element to be inserted 20 Enter the position 1 1.Insert2.Delete3.Display4.ExitEnter your choice:1 Enter the element to be inserted 40 Enter the position 2 1.Insert2.Delete3.Display4.ExitEnter your choice:1 Enter the element to be inserted 30

Page 60: Lab Manual DS and OOPS

60

 Enter the position 3 1.Insert2.Delete3.Display4.ExitEnter your choice:3 1.202.403.30 1.Insert2.Delete3.Display4.ExitEnter your choice:1 Enter the element to be inserted 60 Enter the position 2  1.Insert2.Delete3.Display4.ExitEnter your choice:3 1.202.603.404.30 1.Insert2.Delete3.Display4.ExitEnter your choice:4          

Page 61: Lab Manual DS and OOPS

61

              

BINARY SEARCH TREE Aim:              To write a c program for binary search tree. Algorithm: 

1. Declare function add(),search(),findmin().find(),findmax(),Display(). 2. Create a structure for  a tree contains left pointer and right pointer. 3. Insert an element is by checking the top node and the leaf node and the operation

will be performed. 4. Deleting an element contains searching the tree and deleting the item. 5. display the Tree elements.

Program:#include<stdio.h>#include<stdlib.h>#include<conio.h> struct searchtree{              int element;              struct searchtree *left,*right;}*root;typedef struct searchtree *node;typedef int ElementType; node insert(ElementType, node);node delete(ElementType, node);void makeempty();node findmin(node);node findmax(node);node find(ElementType, node);void display(node, int); void main()

Page 62: Lab Manual DS and OOPS

62

{              int ch;              ElementType a;              node temp;              makeempty();              while(1)              {                            printf("\n1. Insert\n2. Delete\n3. Find min\n4. Find max\n5. Find\n6. Display\n7. Exit\nEnter Your Choice : ");                            scanf("%d",&ch);                            switch(ch)                            {                                          case 1:                                                        printf("Enter an element : ");                                                        scanf("%d", &a);                                                        root = insert(a, root);                                                        break;                                          case 2:                                                        printf("\nEnter the element to delete : ");                                                        scanf("%d",&a);                                                        root = delet(a, root);                                                        break;                                          case 3:                                                        printf("\nEnter the element to search : ");                                                        scanf("%d",&a);                                                        temp = find(a, root);                                                        if (temp != NULL)                                                                      printf("Element found");                                                        else                                                                      printf("Element not found");                                                        break;                                          case 4:                                                        temp = findmin(root);                                                        if(temp==NULL)                                                                      printf("\nEmpty tree");                                                        else                                                                      printf("\nMinimum element : %d", temp->element);                                                        break;                                          case 5:                                                        temp = findmax(root);                                                        if(temp==NULL)                                                                      printf("\nEmpty tree");                                                        else                                                                      printf("\nMaximum element : %d", temp->element);                                                        break;                                          case 6:                                                        if(root==NULL)                                                                      printf("\nEmpty tree");

Page 63: Lab Manual DS and OOPS

63

                                                        else                                                                      display(root, 1);                                                        break;                                          case 7:                                                        exit(0);                                          default:                                                        printf("Invalid Choice");                            }              }} node insert(ElementType x,node t){              if(t==NULL)              {                            t = (node)malloc(sizeof(node));                            t->element = x;                            t->left = t->right = NULL;              }              else              {                            if(x < t->element)                                          t->left = insert(x, t->left);                            else if(x > t->element)                                          t->right = insert(x, t->right);              }              return t;} node delet(ElementType x,node t){              node temp;              if(t == NULL)                            printf("\nElement not found");              else              {                            if(x < t->element)                                          t->left = delet(x, t->left);                            else if(x > t->element)                                          t->right = delet(x, t->right);                            else                            {                                          if(t->left && t->right)                                          {                                                        temp = findmin(t->right);                                                        t->element = temp->element;                                                        t->right = delet(t->element,t->right);                                          }                                          else if(t->left == NULL)                                                        t=t->right;

Page 64: Lab Manual DS and OOPS

64

                                          else                                                        t=t->left;                            }              }              return t;}void makeempty(){              root = NULL;}  node findmin(node temp){              if(temp == NULL || temp->left == NULL)                            return temp;              return findmin(temp->left);}  node findmax(node temp){              if(temp==NULL || temp->right==NULL)                            return temp;              return findmin(temp->right);} node find(ElementType x, node t){              if(t==NULL) return NULL;              if(x<t->element) return find(x,t->left);              if(x>t->element) return find(x,t->right);              return t;} void display(node t,int level){              int i;              if(t)              {                            display(t->right, level+1);                            printf(“\n”);                            for(i=0;i<level;i++)                                          printf(" ");                            printf("%d", t->element);                            display(t->left, level+1);              }} Output: 1. Insert

Page 65: Lab Manual DS and OOPS

65

2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 1Enter an element : 10 1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 1Enter an element : 20  1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 1Enter an element : 5  1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 4The smallest Number is 5 1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 3Enter an element : 100

Page 66: Lab Manual DS and OOPS

66

Element not Found 1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 2Enter an element : 20 1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 6   510 1. Insert2. Delete3. Find4. Find Min5. Find Max6. Display7. ExitEnter your Choice : 7    

   

Program:

#include<stdio.h>#include<conio.h>struct tree{    int data;    struct tree *left;    struct tree *right;};

Page 67: Lab Manual DS and OOPS

67

struct tree *create();void preorder(struct tree *);void inorder(struct tree *);void postorder(struct tree *);struct tree *create(){    struct tree *p,*root;    int m,x;    char s;    root=(struct tree *)malloc(sizeof(struct tree));    printf("\nenter the value of the main root");    scanf("%d",&m);    root->data=m;    root->left=NULL;    root->right=NULL;    printf("\nenter n to stop creation of the binary search tree");    fflush(stdin);    scanf("%c",&s);    while(s!='n')    {        p=root;        printf("\nenter the value of the newnode");        fflush(stdin);        scanf("%d",&x);        while(1)        {            if(x<p->data)            {                if(p->left==NULL)                {                    p->left=(struct tree *)malloc(sizeof(struct tree));                    p=p->left;                    p->data=x;                    p->right=NULL;                    p->left=NULL;                    break;                }                else                p=p->left;            }            else            {                if(p->right==NULL)                {                    p->right=(struct tree *)malloc(sizeof(struct tree));                    p=p->right;                    p->data=x;                    p->right=NULL;                    p->left=NULL;                    break;

Page 68: Lab Manual DS and OOPS

68

                }                else                p=p->right;            }        }        printf("\nwant to continue");        fflush(stdin);        scanf("%c",&s);    }    return(root);}void preorder(struct tree *p){    if(p!=NULL)    {        printf("%d ",p->data);        preorder(p->left);        preorder(p->right);    }}void inorder(struct tree *p){    if(p!=NULL)    {        inorder(p->left);        printf("\t%d",p->data);        inorder(p->right);    }}void postorder(struct tree *p){    if(p!=NULL)    {        postorder(p->left);        postorder(p->right);        printf("\t%d",p->data);    }}void main(){    int h;    struct tree *root;    while(1)    {        printf("\nenter 1. for creation of the binary search tree");        printf("\nenter 2. for preorder traversal");        printf("\nenter 3. for inorder traversal");        printf("\nenter 4. for postorder traversal");        printf("\nenter 5. for exit");        printf("\nenter your choice");

Page 69: Lab Manual DS and OOPS

69

        scanf("%d",&h);        switch(h)        {            case 1:            root=create();            break;            case 2:            preorder(root);            break;            case 3:            inorder(root);            break;            case 4:            postorder(root);            break;            case 5:            exit(0);            default:            printf("\nentered a wrong choice");        }    }}

Output:

enter n to stop creation of the binary search tree

enter the value of the newnode45

want to continue

enter the value of the newnode78

want to continue

enter the value of the newnode12

want to continue

enter the value of the newnode50

want to continue

enter the value of the newnode89

want to continuen

enter 1. for creation of the binary search treeenter 2. for preorder traversalenter 3. for inorder traversal

Page 70: Lab Manual DS and OOPS

70

enter 4. for postorder traversalenter 5. for exitenter your choice256 45 12 50 78 89enter 1. for creation of the binary search treeenter 2. for preorder traversalenter 3. for inorder traversalenter 4. for postorder traversalenter 5. for exitenter your choice3 12 45 50 56 78 89enter 1. for creation of the binary search treeenter 2. for preorder traversalenter 3. for inorder traversalenter 4. for postorder traversalenter 5. for exitenter your choice4 12 50 45 89 78 56enter 1. for creation of the binary search treeenter 2. for preorder traversalenter 3. for inorder traversalenter 4. for postorder traversalenter 5. for exitenter your choice

*Conversion Of Infix Expression To Postfix Expression:

Aim:              To write a c program to convert the infix expression to postfix expression.. Algorithm: Scan the Infix string from left to right.

1. Initialize an empty stack. 2. If the scanned character is an operand, add it to the Postfix string. If the scanned

character is an operator and if the stack is empty push the character to stack. 3. If the scanned character is an Operator and the stack is not empty, compare the

precedence of the character with the element on top of the stack (top Stack). If top Stack has higher precedence over the scanned character pop the stack else push the scanned character to stack. Repeat this step as long as stack is not empty and top Stack has precedence over the character.

4. Repeat this step till all the characters are scanned.

Page 71: Lab Manual DS and OOPS

71

5. After all characters are scanned, we have to add any character that the stack may have to the Postfix string. If stack is not empty add top Stack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty.

Program:

#include<stdio.h>#include<conio.h>#include<string.h>#include<ctype.h>#include<stdlib.h>#define N 64#define LP 10#define RP 20#define OPERATOR 30#define OPERAND 40

// Left parentheses precedence. Minimum of all#define LPP 0

// Addition Subtraction precedence. Minimum among all operator precedence#define AP 1#define SP AP

// Multiplication divisor precedence.#define MP 2#define DP MP

// Remainder precedence.#define REMP 2

#define NONE 9

static char infix[N+1],stack[N],postfix[N+1];static int top;

void infixtopostfix(void); /** POSTFIX CONVERSION FUNCTION **/int gettype(char); /** TYPE OF EXPRESSION GENERATOR **/void push(char); /** PUSH FUNCTION **/char pop(void); /** POP FUNCTION **/int getprec(char); /** PRECEDENCE CHECKER FUNCTION **/

void main(){ char ch; do { top=-1; printf("\nEnter an infix expression\n");

Page 72: Lab Manual DS and OOPS

72

fflush(stdin); gets(infix); infixtopostfix(); printf("\ninfix = %s\npost fix =%s\n",infix,postfix); printf("\nDo you wish to continue\n"); ch=getche(); }while(ch=='Y' || ch=='y');}

void infixtopostfix(void){ int i,p,l,type,prec; char next; i=p=0; l=strlen(infix); while(i<l) { type=gettype(infix[i]); switch(type) { case LP: push(infix[i]); break; case RP: while((next=pop())!='(') postfix[p++]=next; break; case OPERAND: postfix[p++]=infix[i]; break; case OPERATOR: prec=getprec(infix[i]); while(top>-1 && prec <= getprec(stack[top])) postfix[p++]=pop(); push(infix[i]); break; } i++; } while(top>-1) postfix[p++]=pop(); postfix[p]='\0';}

int gettype(char sym){ switch(sym) { case '(':

Page 73: Lab Manual DS and OOPS

73

return(LP); case ')': return(RP); case '+': case '-': case '*': case '/': case '%': return(OPERATOR); default : return(OPERAND); }}

void push(char sym){ if(top>N) { printf("\nStack is full\n"); exit(0); } else stack[++top]=sym;}

char pop(void){ if(top<=-1) { printf("\nStack is empty\n"); exit(0); } else return(stack[top--]);}

int getprec(char sym){ switch(sym) { case '(': return(LPP); case '+': return(AP); case '-': return(SP); case '*': return(MP); case '/': return(DP);

Page 74: Lab Manual DS and OOPS

74

case '%': return(REMP); default : return(NONE); }}

OUTPUT:

 Enter any infix expression3*6+4*2/5

Infix = 3*6+4*2/5Post fix =36*42*5/+

Do you wish to continue

Page 75: Lab Manual DS and OOPS

75

   

*QUICK SORTAim:              To  write a c program to perform quick sort. Algorithm:

1. Get the value of how many no. to be sorted.

2. Get the elements from the user.

3. Two function qsort() and swap(). Quick sort to perform sorting.

4. Swap() is just to rearrange the values.

5. Quick sort algorithm works by partitioning the array to be sorted, then recursively

sorting each partition.

6. Display the sorted value.

               #include<stdio.h>

Page 76: Lab Manual DS and OOPS

76

#include<conio.h>int i,j,n,pivot,a[20];void quick(int a[],int left,int right);void swap(int a[],int i,int j);void main(){ int n,a[20]; textcolor(15); clrscr(); printf("\n\nQUICK SORT"); printf("\n\nEnter the limit : "); scanf("%d",&n); textcolor(4); textcolor(5); clrscr(); printf("\n\nEnter the element\n\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); quick(a,0,n-1); textcolor(10); printf("\n\nThe sorted list is \n\n"); for(i=0;i<n;i++) printf("%d ",a[i]); getch(); } void quick(int a[],int first,int last) { if(first<last) { pivot=a[first]; i=first; j=last; while(i<j)

{ while(a[i]<=pivot&&i<last) i++; while(a[j]>=pivot&&j>first) j--; if(i<j) swap(a,i,j); } swap(a,first,j); quick(a,first,j-1); quick(a,j+1,last); } } void swap(int a[],int i,int j) { int temp; temp=a[i];

Page 77: Lab Manual DS and OOPS

77

a[i]=a[j]; a[j]=temp; }

Output: Enter the size:5 Enter the elements: 8532460496 Sorted list: 0432468596                    

  

*HEAP SORTAim:              To  write a c program to perform heap sort.

Page 78: Lab Manual DS and OOPS

78

 Algorithm:

1. Get the size of the array from the user. 2. Get the elements to be sorted. 3. Sorting is performed when we call the heap sort function. 4. Now the array is contained with sorted elements. 5. Display the sorted elements.

 Program:#include<stdio.h>#include<conio.h>void heapsort(int x[],int);void main(){int x[100],i,n;clrscr();printf(“\nEnter the size:”);scanf(“%d”,&n);printf(“Enter %d elements:”,n);for(i=0;i<n;i++){scanf(“%d”,&x[i]);}for(i=n;i>1;i--){heapsort(x,i-1);}printf(“\nSorted elements are:”);for(i=0;i<n;i++){printf(“-->%d\n”,x[i]);}getch();}void heapsort(int x[],int arr){int i,m;int lc,rc,mc,rt,temp;rt=(arr-1)/2;for(m=rt;m>=0;m--){for(i=rt;i>=0;i--){lc=(2*i)+1;rc=(2*i)+2;if((lc<=arr)&&(rc<=arr)){if(x[rc]>=x[lc])mc=rc;else

Page 79: Lab Manual DS and OOPS

79

mc=lc;}else{if(rc>arr)mc=lc;elsemc=rc;}if(x[i]<x[mc]){temp=x[i];x[i]=x[mc];x[mc]=temp;}}}temp=x[0];x[0]=x[arr];x[arr]=temp;return;}                    Output: Enter the size:5 Enter 5 elements:9067

Page 80: Lab Manual DS and OOPS

80

127501 sorted elements:112677590