Question in polish Notation example infix notation 15841 po
Question in polish Notation. example:
infix notation : (1+5)*(8-(4-1))
postix notation : 15+841--*
Given a consant string
: 1. Write just the function in C and the whole program in MIPS assembly that converts with the help of stack, the given string and makes it postfix. Then write another function in C and then the program in MIPS assembly that calculates the result of the converted(postix) function.
Solution
The function to convert infix to postfix in C.
 
 int infixToPostfix(char* exp)
 {
 int i, k;
 struct Stack* stack = createStack(strlen(exp));
 if(!stack)
 return -1 ;
 
 for (i = 0, k = -1; exp[i]; ++i)
 {
 if (isOperand(exp[i]))
 exp[++k] = exp[i];
 else if (exp[i] == \'(\')
 push(stack, exp[i]);
 else if (exp[i] == \')\')
 {
 while (!isEmpty(stack) && peek(stack) != \'(\')
 exp[++k] = pop(stack);
 if (!isEmpty(stack) && peek(stack) != \'(\')
 return -1;
 else
 pop(stack);
 }
 else
 {
 while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack)))
 exp[++k] = pop(stack);
 push(stack, exp[i]);
 }
 }
 while (!isEmpty(stack))
 exp[++k] = pop(stack );
 exp[++k] = \'\\0\';
 printf( \"%s\ \", exp );
 }
 
 C program to evaluate postfix expression,with Push and Pop with their usual meanings
 
 void EvalPostfix()
 {
 char pofx[50],ch;
 int i=0,op1,op2;
 printf(\"\ \ Enter Postfix Expression : \");
 scanf(\"%s\",pofx);
 while( (ch=pofx[i++]) != \'\\0\')
 {
 if(isdigit(ch)) push(ch-\'0\');
 else
 {
 op2=pop();
 op1=pop();
 switch(ch)
 {
 case \'+\':push(op1+op2);break;
 case \'-\':push(op1-op2);break;
 case \'*\':push(op1*op2);break;
 case \'/\':push(op1/op2);break;
 }
 }
 }
 printf(\"\  Given Postfix Expression: %s\ \",pofx);
 printf(\"\  Result after Evaluation: %d\ \",s[top]);
 }
 
 The exact program in MIPS for Postfix Evaluation would look like below

