Document for Data Structures Computer Sample Questions and Answers Paper

Doorsteptutor material for UGC Computer-Science is prepared by world's top subject experts: Get full length tests using official NTA interface: all topics with exact weightage, real exam experience, detailed analytics, comparison and rankings, & questions with full solutions.

Download PDF of This Page (Size: 99K)

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: