Escolar Documentos
Profissional Documentos
Cultura Documentos
end of the stack called Top of stack. The various applications of stacks are listed below:
1. Evaluation of postfix expression.
2. Conversion of Infix into Postfix expression.
3. Balancing of Symbols.
4. Function Calling.
EVALUATION OF POSTFIX EXPRESSION:
However, there exists two other yet significantly less popular notations
called prefix and postfix. In this article we will concentrate on the later and
describe what it is and how to evaluate it using computer.
Postfix notation
To evaluate this expression we take two first numbers 2 and 3, add them
and remember the result; then we take the next two numbers 7 and 9,
divide them and remember the result. At last we take the two remembered
values and we subtract them to obtain the final result.
While postfix notation may seem less natural and straightforward, it has
several advantages which made it popular in computing. The main reason is
that postfix expressions are generally easier to calculate on computers than
the equivalent infix expressions and do not require any brackets to define
the order of operations (assuming that every operator has fixed number of
operands). Additionally, the ease of processing results in significantly
simpler and more efficient algorithms. This made postfix notation very
popular in representing intermediate results of computations.
Algorithm
Example
The exact steps of the algorithm are put in the table below:
Input token
Operation
Stack contents
(top on the right)
Push on the
stack
Push on the
stack
2, 3
Push on the
stack
2, 3, 4
Add
2, 7
Details
Pop two
values: 3 and
4 and push the
result 7 on the
stack
Multiply
14
Push on the
stack
14, 6
(End of tokens)
Subtract
(Return the
result)
Pop two
values: 2 and 7
and push the
result 14 on
the stack
Pop two
values: 14 and
6 and push the
result 8 on the
stack
#include<math.h>//preprocessor
char p[20]; //input string
float s[10];// stack
signed int top=-1,i=0,j=0,n;
float a,b,c,x;
//function declarations
signed int push(float);
float pop();
void main()//main function
{
printf("\n\tEnter An expression in post fix notation\n\t");
scanf("%s",p);
n=strlen(p);//find length of expression
while(p[i]!='\0')
{
switch(p[i])
{
case '+':
printf("\n in case +");
b=pop();
a=pop();
c=a+b;
push(c);
break;
case '-':
printf("\n in case -");
b=pop();
a=pop();
c=a-b;
push(c);
break;
case '*':
printf("\n in case *");
a=pop();
b=pop();
c=a*b;
push(c);
break;
case '/':
printf("\n in case /");
b=pop();
a=pop();
c=a/b;
push(c);
break;
case '^':
printf("\n in case ^");
b=pop();
a=pop();
c=pow(a,b);
push(c);
break;
default :
printf("\n in default case");
/*we have to typecast p[i] which is character
to float so that we can push it on to float
type stack*/
x = (float)(p[i]-'0');
printf("\n\tThe x value is %f \t",x);
push(x);
break;
}//end Switch
i++;
}//end While
printf("\n\tThe evaluation of given expression is
%8.4f\n\t",s[top]);
}//end main
//function definitions
int push(float x)//push function
{
top++;//increment top
s[top]=x;//assign x to stack of top
s[top+1]='\0';
return 0;
}//end push
float pop()//pop function
{
float item;
item=s[top];//assign stack of top to item
s[top]='\0';
top--;//decrement top
return (item);
}//end pop
/*
C:\Dev-Cpp\stack>poteval2.exe
Enter An expression in post fix notation
54321^*/in default case
The x value is 5.000000
in default case
The x value is 4.000000
in default case
The x value is 3.000000
in default case
The x value is 2.000000
in default case
The x value is 1.000000
in case ^
in case *
in case /
in case The evaluation of given expression is
*/
4.3333
applies to the immediately two preceding operands b and c. The addition operator is then applied
to operand a and the result (b * c). If we had meant the expression (a + b) * c, we would have
written it in postfix notation as a b + c *. Now the + operation is applied to the two operands a
and b, and * is performed on the two operands c and the result (a + b).
Because of the existence of this unique interpretation, some compilers first convert
arithmetic expressions from the standard infix notation to postfix to simplify code generation. To
convert an infix expression to postfix, we must use a stack to hold operators that cannot be
processed until their operands are available.
Assume that we are given as input the infix string a + b * c d. This is equivalent to the
parenthesized infix arithmetic expression (a + (b * c)) d. To convert this to postfix format, we
scan the input from left to right. If the next symbol in the input stream is an operand (for
example, a) it is placed directly into the output stream without further processing.
Input: a + b * c d
Output: a
opStack: empty
If the next symbol in the input string is an operator (for example, +), then we compare the
precedence of this operator to the one on top of a stack called opStack, short for operator stack,
which is initialized to empty at the start of the scan. If opStack is empty or if the precedence of
the next operator in the input stream is greater than the precedence of the one on top of opStack,
then we push the operator from the input string onto opStack and continue.
Input: a + b * c d
Output: a
opStack: +
Lets explain what is happening a little more intuitively. We are trying to locate the highestprecedence operation to determine which operation to perform next. As long as the operators
being scanned are increasing in precedence, we cannot do anything with our infix expression.
Instead, we stack them and continue scanning the input string.
Input: a + b * c d
Output: a b
opStack: +
Output: a b
opStack: +
*
Output: a b c
opStack: +
*
Output: a b c
opStack: +
*
Input: a + b * c d
Input: a + b * c d
Input: a + b * c d
At this point, we encounter the operator, whose precedence is lower than the *, the
operator on top of the stack. We now pop operators from opStack until either (1) opStack is
empty, or (2) the precedence of the operator on top of opStack is strictly less than that of the
current operator in the input string. In this case, we pop both the * and + operators and place
them into the output stream:
Input: a + b * c d
Output: a b c *
opStack: +
Output: a b c * +
opStack:
empty
Input: a + b * c d
This scanning process continues until we come to the end of the input. Then, any remaining
operators on opStack are popped into the output and the algorithm terminates.
Input: a + b * c d
Output: a b c * +
opStack:
Output: a b c * + d
opStack:
Output: a b c * + d
opStack:
empty
Input: a + b * c d
Input: a + b * c d
The algorithm has produced the expression a b c * + d , the correct postfix representation of
the original input.
In this example, a stack was the right structure to hold operators from the input stream
because of the nature of the algorithm. Operators must be saved until we determine their
proper location, and then they are placed into the output stream in the reverse order of their
occurrence in the input. Again, this is a perfect match with the LIFO model of a stack.
LTC :
// Program for converting infix expression to postfix form using
stacks
#include<stdio.h>//preprocessor
#include<string.h>//preprocessor
#include<stdlib.h>//preprocessor
int preceed(char c);
void push(char c);
char pop();
char stk[30];
int tos =-1;
int main()
{
int i,j=0,n,u,v;
char infix[30],postfix[30];
char c;
printf("\n enter the infix expression:");
scanf("%s",infix);
n=strlen(infix);
for(i=0;i<n;i++)
{
if((infix[i]>= 'a' && infix[i]<= 'z') || (infix[i]>= 'A' &&
infix[i]<= 'Z'))
{ postfix[j] = infix[i];
j=j+1;
} //end of if
else
if( infix[i]=='^'||infix[i]=='*'||infix[i]=='/'
||infix[i]=='+'||infix[i]=='-')
{ u = preceed(stk[tos]);
v = preceed(infix[i]);
while(v<= u && stk[tos]!= '(')
{ postfix[j]=pop();
j=j+1;
u = preceed(stk[tos]);
}
push(infix[i]);
}//end of else if 1
else
if( infix [i] == '(')
{ push(infix[i]);
} // end of else if 2
else
if (infix[i] == ')')
{ c = pop();
while(c != '(')
{ postfix[j]= c;
j=j+1;
c= pop();
} // end of while
}// end of if else 3
else
{
printf("\n\tTHE EQUATION HAS ERROR");
exit(0);
}//end else
} // end of for
while(tos!=-1)
{ postfix[j]= pop();
j=j+1;
}
postfix[j]='\0';
printf("\nThe equation in POSTFIX notation is: %s\n",postfix);
}//end main
#define max 50
void main()
{
char stk[max],exp[100];
int top,i;
clrscr();
top = -1;
printf("\nEnter an infix expression ");
gets(exp);
for(i=0; exp[i] != '\0'; i++)
{
if( exp[i]=='(' || exp[i] =='[' || exp[i] == '{' )
{
top++;
stk[top]= exp[i];
}
else
if ( exp[i] == ')' )
{
if( stk[top] == '(' )
top--;
}
else
{
printf("Unbalanced exp");
exit(0);
}
}
else
if ( exp[i] == ']' )
{
if( stk[top] == '[' )
top--;
else
{
printf("Unbalanced exp");
exit(0);
}
}
else
if ( exp[i] == '}' )
{
if( stk[top] == '{' )
top--;
else
{
printf("Unbalanced exp");
exit(0);
}
}
} // for
if( top == -1 )
printf("Exp is balanced");
else
printf("Exp is not balanced");
} // main