5.
Develop a Program in C for the following Stack Applications
a) Evaluation of Suffix expression with single digit operands and operators: +, -,
*, /, %, ^
b) Solving Tower of Hanoi problem with n disks
a) Evaluation of Suffix expression with single digit operands and operators: +, -,
*, /, %, ^
#include<stdio.h>
#include<math.h>
#include<ctype.h>
char s[50],ch;
int i,a,b,top=-1,stk[50],ans,num,elm;
void push(int num)
{
top=top+1;
stk[top]=num;
}
int pop()
{
elm=stk[top]; top=top-1; return (elm);
}
int main()
{
printf("Enter the postfix expression\n");
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
{
ch=s[i];
if(isdigit(ch))
push(ch-'0');
else
{
b=pop();
a=pop();
switch(ch)
{
case'+': push(a+b);
break;
case '-': push(a-b);
break;
case '*': push(a*b);
break;
case '/':push(a/b);
break;
case '%': push(a%b);
break;
case '$': push(pow(a,b));
break;
case '^':push(pow(a,b));
break;
default:printf("Invalid operator\n"); }
}
}
ans=pop();
printf("Result of given expression= %d\n",ans);
return 0;
}
b) Solving Tower of Hanoi problem with n disks
#include <stdio.h>
void tower_of_hanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);
return;
}
tower_of_hanoi(n - 1, from_rod, aux_rod, to_rod);
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
tower_of_hanoi(n - 1, aux_rod, to_rod, from_rod);
}
int main() {
int n;
printf("Enter number of disks: ");
scanf("%d", &n);
tower_of_hanoi(n, 'A', 'C', 'B');
return 0;
}