Lab Program 5a:
Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int i, top = -1;
int op1, op2,
res, s[20];
char
postfix[90], symb;
void push(int
item)
{
top
= top+1;
s[top]
= item;
}
int pop()
{
int
item;
item =
s[top];
top
= top-1;
return
item;
}
void main()
{
printf("\nEnter a valid postfix
expression:\n");
scanf("%s", postfix);
for(i=0; postfix[i]!='\0'; i++)
{
symb = postfix[i];
if(isdigit(symb))
{
push(symb -
'0');
}
else
{
op2 = pop();
op1 = pop();
switch(symb)
{
case '+': push(op1+op2);
break;
case
'-': push(op1-op2);
break;
case '*': push(op1*op2);
break;
case '/': push(op1/op2);
break;
case '%': push(op1%op2);
break;
case '$':
case '^': push(pow(op1, op2));
break;
default
: push(0);
}
}
}
res = pop();
printf("\n Result = %d",
res);
}
Output:
To compile in Linux: gcc –lm 5.c
Enter a valid
postfix expression:
623+-382/+*2$3+
Result = 52
Enter a valid
postfix expression:
42$3*3-84/11+/+
Result = 46
Also Credits to:
Manoj Taleka (manoj89biet@gmail.com)
Yashaswini Jogi (jogi.yash@gmail.com)
In push(symb-'0'), why are we using this -'0'? What is the use of that?
ReplyDeleteASCII value of '0' is 48.
DeleteOur input postfix is a string. Suppose we take input as say 4 that means ASCII value of '4' i.e. 52 will be stored in symb.
So symb - '0' = 52-48 = 4
Is it because we're using default: push(0) in the switch statement?
ReplyDelete