Example of Stacks
Example of Stacks
● ( (AB+)*C-(DE-) ) $ (FG+)
● ( (AB+C*)-(DE-) ) $ (FG+)
● (AB+C*DE--) $ (FG+)
● AB+C*DE- -FG+$
element */
/* at a time into symb */ symb opnd1 opnd2 value opndstk
while (not end of input) { 6 6
prcd(‘$’,’$’) = FALSE
* AB+ *
push(opstk, symb);
} /* end else */ C AB+C *
AB+C*
} /* end while */
Algorithm to Convert Infix to Postfix
Example-2: (A+B)*C
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand) symb Postfix opstk
add symb to the postfix string string
else { ( (
while (!empty(opstk) &&
prcd(stacktop(opstk),symb) ) A A (
{
+ A (+
topsymb = pop(opstk);
add topsymb to the postfix string; B AB (+
} /* end while */ ) AB+
if (symb is an operand)
add symb to the postfix string ( ((
else {
while (!empty(opstk) && prcd(stacktop(opstk),symb) ) A A ((
{ - A ((-
} /* end else */
$ ABC+-D* $
( ABC+-D* $(
} /* end while */
E ABC+-D*E $(
Algorithm to Convert Infix to Postfix
Example-4: ( A + B ) * ( C – D)
opstk = the empty stack;
while (not end of input) {
symb = next input character;
if (symb is an operand) symb Postfix string opstk
add symb to the postfix string
else {
while (!empty(opstk) && prcd(stacktop(opstk),symb) )
{
topsymb = pop(opstk);
add topsymb to the postfix string;
} /* end while */
} /* end else */
} /* end while */
Factorial of a number
● Write function to calculate the factorial of a
number.
○ Iterative definition
○ Recursive