C Programs – Stack and Expression Conversions
1. Implement Infix to Postfix Expression Conversion
This program converts an infix expression (e.g., A+B*C) into its postfix form (ABC*+)
using a stack.
C Program:
----------------------------------
#include <stdio.h>
#include <ctype.h>
char stack[50];
int top = -1;
void push(char x) {
stack[++top] = x;
}
char pop() {
return stack[top--];
}
int precedence(char x) {
if(x == '+' || x == '-') return 1;
if(x == '*' || x == '/') return 2;
if(x == '^') return 3;
return 0;
}
int main() {
char exp[50], *e, x;
printf("Enter infix expression: ");
scanf("%s", exp);
e = exp;
while(*e != '\0') {
if(isalnum(*e))
printf("%c", *e);
else if(*e == '(')
push(*e);
else if(*e == ')') {
while((x = pop()) != '(')
printf("%c", x);
}
else {
while(top != -1 && precedence(stack[top]) >= precedence(*e))
printf("%c", pop());
push(*e);
}
e++;
}
while(top != -1)
printf("%c", pop());
return 0;
}
----------------------------------
2. Evaluation of Infix/Prefix/Postfix Expressions using Stack
Below is a sample program for postfix evaluation. Same logic can be extended for infix
and prefix evaluation using stacks.
C Program (Postfix Evaluation):
----------------------------------
#include <stdio.h>
#include <ctype.h>
#include <math.h>
int stack[50];
int top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() {
return stack[top--];
}
int main() {
char exp[50];
char *e;
int n1, n2;
printf("Enter postfix expression: ");
scanf("%s", exp);
e = exp;
while(*e != '\0') {
if(isdigit(*e))
push(*e - '0');
else {
n2 = pop();
n1 = pop();
switch(*e) {
case '+': push(n1 + n2); break;
case '-': push(n1 - n2); break;
case '*': push(n1 * n2); break;
case '/': push(n1 / n2); break;
case '^': push(pow(n1, n2)); break;
}
}
e++;
}
printf("Result = %d", pop());
return 0;
}
----------------------------------
3. Implement Stack using Array
C Program:
----------------------------------
#include <stdio.h>
int stack[100], top = -1;
void push(int x) {
stack[++top] = x;
}
int pop() {
return stack[top--];
}
void display() {
for(int i = top; i >= 0; i--)
printf("%d ", stack[i]);
}
int main() {
push(10);
push(20);
push(30);
printf("Stack elements: ");
display();
printf("\nPopped: %d", pop());
return 0;
}
----------------------------------