DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS
Convert an Infix Expression to Postfix
Learn how to convert an infix expression to postfix using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Postfix = ABC*+
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <ctype.h>
#include <stddef.h>
int precedence(char operator)
{
if (operator == '*' || operator == '/') return 2;
if (operator == '+' || operator == '-') return 1;
return 0;
}
int main(void)
{
const char infix[] = "A+B*C";
char operators[50], postfix[50];
int top = -1, write = 0;
for (size_t index = 0; infix[index] != '\0'; index++) {
char token = infix[index];
if (isalnum((unsigned char) token)) postfix[write++] = token;
else {
while (top >= 0 && precedence(operators[top]) >= precedence(token))
postfix[write++] = operators[top--];
operators[++top] = token;
}
}
while (top >= 0) postfix[write++] = operators[top--];
postfix[write] = '\0';
printf("Postfix = %s\n", postfix);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Postfix = ABC*+
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Send operands directly to output and delay operators on a precedence-controlled stack.
- Display the computed result.
Send operands directly to output and delay operators on a precedence-controlled stack.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
