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.
#include
#include
#include
#define MAX 100
int stack[MAX], top = -1;
// Stack operations
void push(int val) { stack[++top] = val; }
int pop() { return (top == -1) ? 0 : stack[top--]; }
// (a) Evaluate Postfix Expression
int evaluatePostfix(char* exp) {
int i = 0, a, b;
char ch;
while ((ch = exp[i++]) != '\0') {
if (isdigit(ch)) {
push(ch - '0'); // convert char to int
} 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((int)pow(a, b)); break;
default: printf("Invalid operator: %c\n", ch);
}
}
}
return pop();
}
// (b) Tower of Hanoi
void towerOfHanoi(int n, char from, char aux, char to) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
towerOfHanoi(n - 1, from, to, aux);
printf("Move disk %d from %c to %c\n", n, from, to);
towerOfHanoi(n - 1, aux, from, to);
}
// Main Menu
int main() {
int choice, result, n;
char expr[100];
do {
printf("\n--- Stack Applications ---\n");
printf("1. Evaluate Postfix Expression\n");
printf("2. Tower of Hanoi\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // consume newline
switch (choice) {
case 1:
printf("Enter postfix expression (e.g. 23*54*+9-): ");
scanf("%s", expr);
top = -1; // reset stack
result = evaluatePostfix(expr);
printf("Result = %d\n", result);
break;
case 2:
printf("Enter number of disks: ");
scanf("%d", &n);
printf("Steps to solve Tower of Hanoi:\n");
towerOfHanoi(n, 'A', 'B', 'C');
break;
case 3:
printf("Exiting program.\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 3);
return 0;
}
--- Stack Applications ---
1. Evaluate Postfix Expression
2. Tower of Hanoi
3. Exit
Enter your choice: 1
Enter postfix expression : 623+-382/+*2+
Result = 9
--- Stack Applications ---
1. Evaluate Postfix Expression
2. Tower of Hanoi
3. Exit
Enter your choice: 2
Enter number of disks: 3
Steps to solve Tower of Hanoi:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
--- Stack Applications ---
1. Evaluate Postfix Expression
2. Tower of Hanoi
3. Exit
Enter your choice: 3
Exiting program.
Replay !
Share Your Thoughts