Document for Data Structures Computer Sample Questions and Answers Paper for Exams

Doorsteptutor material for competitive exams is prepared by world's top subject experts: get questions, notes, tests, video lectures and more- for all subjects of your exam.

Q1. Evaluation of Postfix expression

Ans: Algorithm

1. Scan the input string from left to right

2. for each input symbol

  • If it is a digit then push it on to the stack
  • if it is an operator then pop out the top most two contents from the stack and apply the operator on them, push the result on to stack.
  • If the input symbol is ā€˜ā§µ0ā€™ empty the stack

Program:

#include < stdio. h >

#include < conio. h >

int top =-1, stack [100] ;

void main ()

{

char a [50] , ch, x;

int i, op1, op2, res, x;

void push (int) ;

int pop () ;

int eval (char, int, int) ;

clrscr () ;

printf ( ā€œenter a void postfix expressionā€ ) ;

gets (a) ;

for (i = 0; a [i] ! = ā€˜ā§µ0ā€™ ; i ++)

{

ch = a [i] ;

if (ch >= ā€˜0ā€™ && ch <= ā€˜9ā€™ )

push (ch ā€“ ā€˜0ā€™ ) ;

else

{

op2 = pop () ;

op1 = pop () ;

res = eval (ch, op1, op2) ;

push (res) ;

}

}

x = pop () ;

printf ( ā€œevaluated value =% dā€ , x) ;

getch () ;

}

void push (int n)

{

top ++ ;

stack [top] = n;

}

int pop ()

{

int res;

res = stack [top] ;

top--

return res;

}

int eval (char ch, int op1, int op2)

{

switch (ch)

{

case ā€˜+ā€™ : return (op1 + op2) ;

case ā€˜-ā€™ : return (op1-op2) ;

case ā€˜āš¹ā€™ : return (op1 āš¹ op2) ;

case ā€˜/ā€™ : return (op1/op2) ;

}

}

O/p: enter a valid postfix expression

3 5 2 āš¹+

Evaluated value = 13

Developed by: