Showing posts with label Stack. Show all posts
Showing posts with label Stack. Show all posts

Sunday, November 29, 2026

Infix to Postfix Conversion Using Stack in C – Data Structures Lab

 In this laboratory exercise, we implement a C program to convert an infix expression into its equivalent postfix expression using the stack data structure. The program is compatible with Code::Blocks on Windows.

1. Aim

To implement a program in C for converting an Infix Expression to a Postfix Expression using a Stack.

2. Learning Objectives

After completing this laboratory exercise, students will be able to:

  • Understand infix, prefix and postfix notations.

  • Understand operator precedence and associativity.

  • Implement stack operations using arrays.

  • Apply the stack data structure to expression conversion.

  • Analyse the time and space complexity of the algorithm.

3. Introduction

An expression is a combination of operands and operators used to perform mathematical or logical operations. Based on the position of operators, expressions are classified into three types.

Expression type

Description

Example

Infix

Operator between operands

A+B

Prefix

Operator before operands

+AB

Postfix

Operator after operands

AB+

Infix Expression

An infix expression is the conventional representation of a mathematical expression in which the operator is placed between two operands.

Example: A+B*C

Postfix Expression

A postfix expression is a representation in which the operator is placed after its operands. It is also known as Reverse Polish Notation (RPN).

Example: ABC*+

Postfix expressions do not require parentheses or precedence rules during evaluation, making them convenient for computer-based expression processing.

Role of Stack

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.

During infix-to-postfix conversion, the stack is used to temporarily store operators and parentheses until their appropriate position in the postfix expression is determined.

4. Operator Precedence and Associativity

Operator precedence determines the priority of an operator, whereas associativity determines the order of processing operators having the same precedence.

Operator

Operation

Precedence

Associativity

^

Exponentiation

3

Right to Left

*

Multiplication

2

Left to Right

/

Division

2

Left to Right

%

Modulus

2

Left to Right

+

Addition

1

Left to Right

-

Subtraction

1

Left to Right

Note: In this laboratory exercise, ^ represents mathematical exponentiation. In the C programming language, it normally represents the bitwise XOR operator.

5. Algorithm

Step 1: Start.

Step 2: Initialize an empty stack and an empty postfix expression.

Step 3: Read the infix expression from the user.

Step 4: Scan the infix expression from left to right.

Step 5: Perform the appropriate operation based on the scanned character:

  • If it is an operand, append it to the postfix expression.

  • If it is an opening parenthesis, push it onto the stack.

  • If it is a closing parenthesis, pop operators until an opening parenthesis is encountered. Discard the opening parenthesis.

  • If it is an operator, pop operators with higher precedence. Also pop operators with equal precedence if the incoming operator is left-associative. Push the incoming operator onto the stack.

Step 6: Repeat Step 5 until all characters are processed.

Step 7: Pop all the remaining operators from the stack and append them to the postfix expression.

Step 8: Display the postfix expression.

Step 9: Stop.

6. C Program

#include <stdio.h>
#include <ctype.h>

#define MAX 100

char stack[MAX];
int top = -1;

/* Function to push an element onto the stack */
void push(char ch)
{
    if (top == MAX - 1)
        printf("Stack Overflow\n");
    else
        stack[++top] = ch;
}

/* Function to pop an element from the stack */
char pop()
{
    if (top == -1)
        return '\0';

    return stack[top--];
}

/* Function to determine operator precedence */
int precedence(char ch)
{
    switch (ch)
    {
        case '^':
            return 3;

        case '*':
        case '/':
        case '%':
            return 2;

        case '+':
        case '-':
            return 1;

        default:
            return 0;
    }
}

/* Function to check whether a character is an operator */
int isOperator(char ch)
{
    return (ch == '+' || ch == '-' ||
            ch == '*' || ch == '/' ||
            ch == '%' || ch == '^');
}

/* Function to convert infix to postfix */
void infixToPostfix(char infix[], char postfix[])
{
    int i, j = 0;
    char ch;

    for (i = 0; infix[i] != '\0'; i++)
    {
        ch = infix[i];

        /* Ignore whitespace */
        if (isspace((unsigned char)ch))
            continue;

        /* If operand, append to postfix expression */
        if (isalnum((unsigned char)ch))
        {
            postfix[j++] = ch;
        }

        /* If opening parenthesis, push onto stack */
        else if (ch == '(')
        {
            push(ch);
        }

        /* If closing parenthesis, pop until '(' */
        else if (ch == ')')
        {
            while (top != -1 && stack[top] != '(')
            {
                postfix[j++] = pop();
            }

            if (top != -1)
                pop();
        }

        /* If operator */
        else if (isOperator(ch))
        {
            while (top != -1 && stack[top] != '(' &&
                  (precedence(stack[top]) > precedence(ch) ||
                  (precedence(stack[top]) == precedence(ch)
                   && ch != '^')))
            {
                postfix[j++] = pop();
            }

            push(ch);
        }
    }

    /* Pop remaining operators from the stack */
    while (top != -1)
    {
        postfix[j++] = pop();
    }

    postfix[j] = '\0';
}

/* Main function */
int main()
{
    char infix[MAX], postfix[MAX];

    printf("Enter the Infix Expression: ");

    if (fgets(infix, MAX, stdin) == NULL)
        return 1;

    infixToPostfix(infix, postfix);

    printf("Postfix Expression: %s\n", postfix);

    return 0;
}

7. Program Execution Using Code::Blocks

  1. Open Code::Blocks.

  2. Select File → New → Project.

  3. Select Console Application.

  4. Select C as the programming language.

  5. Enter the project name and select the destination folder.

  6. Open the main.c file.

  7. Replace the existing program with the above C program.

  8. Select Build and Run or press F9.

  9. Enter the infix expression and observe the generated postfix expression.

8. Sample Output

Execution 1:

Enter the Infix Expression: A+B*C
Postfix Expression: ABC*+

Execution 2:

Enter the Infix Expression: (A+B)*C
Postfix Expression: AB+C*

Execution 3:

Enter the Infix Expression: A+B*(C-D)/E
Postfix Expression: ABCD-*E/+

Execution 4:

Enter the Infix Expression: A^B^C
Postfix Expression: ABC^^

9. Dry Run – Step-by-Step Explanation

Consider the following infix expression:

Infix Expression: A+B*(C-D)

Scanned symbol

Operation

Stack

Postfix

A

Append operand

Empty

A

+

Push operator

+

A

B

Append operand

+

AB

*

Push operator

+*

AB

(

Push parenthesis

+*(

AB

C

Append operand

+*(

ABC

-

Push operator

+*(-

ABC

D

Append operand

+*(-

ABCD

)

Pop - and discard (

+*

ABCD-

End

Pop *

+

ABCD-*

End

Pop +

Empty

ABCD-*+

The stack contents in the above table are represented from bottom to top, from left to right.

Final Postfix Expression: ABCD-*+

10. Explanation of Functions

Function

Description

push()

Inserts an element onto the top of the stack.

pop()

Removes and returns the topmost element of the stack.

precedence()

Returns the priority of an operator.

isOperator()

Determines whether a character is an operator.

isalnum()

Checks whether a character is an alphabet or digit.

isspace()

Identifies whitespace characters.

infixToPostfix()

Converts the infix expression into postfix notation.

main()

Accepts the input and displays the converted expression.

11. Complexity Analysis

Time Complexity: O(n)

Each character in the expression is scanned once. Each operator is pushed onto and popped from the stack at most once.

Auxiliary Space Complexity: O(n)

In the worst case, the stack may store a number of operators and parentheses proportional to the length of the input expression.

Here, n represents the length of the infix expression. The implementation uses fixed-size arrays with a capacity of 100 characters each.

12. Additional Test Cases

Students can execute the program using the following expressions and verify the results.

Sl. No.

Infix expression

Expected postfix expression

1

A+B

AB+

2

A+B-C

AB+C-

3

A*B+C/D

AB*CD/+

4

(A+B)*(C+D)

AB+CD+*

5

A+B*C-D/E

ABC*+DE/-

6

A^B^C

ABC^^

7

(A^B)^C

AB^C^

8

((A+B)*C)-D

AB+C*D-

9

A+B*(C-D)

ABCD-*+

10

A+B*(C^D-E)^(F+G*H)-I

ABCD^E-FGH*+^*+I-

13. Applications of Infix-to-Postfix Conversion

Infix-to-postfix conversion is widely used in computer science applications such as compiler design, expression evaluation, scientific calculators, syntax analysis, interpreters, mathematical computation and programming language processing.

14. Limitations

The above program is designed for understanding the fundamental application of the stack data structure.

It assumes valid infix expressions containing single-character operands, balanced parentheses, supported binary operators and a maximum input length of 99 characters. It does not perform complete expression validation or support multi-digit numbers, multi-character variables or unary operators.

15. Extended Laboratory Exercises

For postgraduate students, the following modifications can be considered as additional programming exercises:

  1. Modify the program to support multi-digit numbers.

  2. Implement validation for unbalanced parentheses.

  3. Identify invalid infix expressions.

  4. Implement infix-to-prefix conversion.

  5. Implement postfix expression evaluation.

  6. Implement infix-to-postfix conversion using a linked-list-based stack instead of an array.

  7. Modify the program to display the stack contents after processing every input character.

  8. Extend the program to support unary operators.

16. Viva Voce Questions

No.

Question

1

What is a stack data structure?

2

What is the LIFO principle?

3

What is an infix expression?

4

What is a postfix expression?

5

What is a prefix expression?

6

Why is postfix notation called Reverse Polish Notation?

7

Why is a stack used for expression conversion?

8

What is operator precedence?

9

What is operator associativity?

10

Differentiate between precedence and associativity.

11

Why is exponentiation right-associative?

12

What is stack overflow?

13

What is stack underflow?

14

Why are parentheses not required in postfix expressions?

15

How can a postfix expression be evaluated?

16

What is the time complexity of infix-to-postfix conversion?

17

Can a linked list be used to implement a stack?

18

How is expression conversion used in compiler design?

17. Result

Thus, the C program to convert an Infix Expression into its equivalent Postfix Expression using the Stack Data Structure has been implemented. The expected results are illustrated through suitable test cases.