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.

AdvancedStackLIFOpush/pop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Postfix = ABC*+

COMPLETE C PROGRAM

Complete C implementation

dsa-infix-to-postfix.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Postfix = ABC*+
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Send operands directly to output and delay operators on a precedence-controlled stack.
  3. 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.