# 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  ;

void main ()

{

char a  , 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