0% found this document useful (0 votes)
30 views

Lab Sheet 3 - Infix to Postfix Conversion

Uploaded by

zakwan1292003
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Lab Sheet 3 - Infix to Postfix Conversion

Uploaded by

zakwan1292003
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab Sheet 3: Infix to Postfix Conversion

Lab Objective:

LO1: Interpret the rules of operator precedence and associativity in the context of infix
expressions.

LO2: Implement a stack-based algorithm to convert infix expressions to postfix format,


demonstrating correct handling of operators and parentheses

Theory:

Infix Expression:
In an infix expression, operators are placed between operands. For example, A + B * C is an
infix expression where the operator + is between operands A and B, and * is between B and
C.

Postfix Expression:
In postfix expressions, operators are placed after their operands. For example, the infix
expression A + B * C would be converted to ABC*+.

Algorithm:
1. Operands (letters or digits): Directly add them to the output.
2. Operators:
- If the stack is empty or contains only parentheses, push the operator onto the stack.
- If the precedence of the current operator is higher than the operator at the top of the
stack, push it onto the stack.
- Otherwise, pop operators from the stack and add them to the output until an operator of
lower precedence is found or the stack is empty.
3. Parentheses:
- If you encounter an opening parenthesis `(`, push it onto the stack.
- When a closing parenthesis `)` is found, pop and add operators to the output until the
corresponding opening parenthesis is encountered.
Procedure:

Step 1: Import Java Utilities


Import Scanner from java.util for reading input from the user.

Step 2: Define the Stack Class


The Stack class is used to manage the operators and parentheses during the conversion
process. Include methods for push(), pop(), topElement(), isEmpty(), and isFull().

Step 3: Define the InfixToPostfix Class


In the main() method, take an infix expression as input. Use a loop to read each character of
the expression. Apply the algorithm to convert the infix expression to postfix. Print the
postfix expression.

Step 4: Define the Operator Precedence Method


The priority() method determines the precedence of operators. Higher precedence
operators (like *, /) are pushed onto the stack after operators of lower precedence (+, -).

Step 5: Handle Input and Output


Ensure that the input expression is correctly processed, and the converted postfix
expression is printed as output.

Code Implementation:

Stack Class

package infixtopostfix;

public class Stack {


int size;
char stack[];
int top;

public Stack(int size) {


this.size = size;
stack = new char[size];
top = -1;
}

// isEmpty() checks if the stack is empty by returning true if top is -1.


public boolean isEmpty() {
return top == -1;
}
// isFull() checks if the stack is full by comparing the top index to size - 1.
public boolean isFull() {
return top == size - 1;
}

// topElement() returns the top element of the stack without removing it.
public char topElement() {
if (!isEmpty()) {
return stack[top];
}
return '\0'; // null character to indicate empty stack
}

// push() adds an element to the stack if it is not full.


public void push(char symbol) {
if (isFull()) {
System.out.println("Stack Overflow");
} else {
stack[++top] = symbol;
}
}

// pop() removes and returns the top element from the stack.
public char pop() {
if (!isEmpty()) {
return stack[top--];
}
return '\0'; // null character to indicate empty stack
}
}

InfixToPostfix Class

package infixtopostfix;

import java.util.Scanner;

public class InfixToPostfix {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
String infix;
System.out.println("Enter the Infix Expression:");
infix = scanner.nextLine();
scanner.close(); // Closing scanner to avoid resource leak

Stack stack = new Stack(infix.length());


int index = 0;
- char cs;

// While loop iterates through the infix expression one character at a time.
while (index < infix.length()) {
cs = infix.charAt(index);

// If the current character is an operand (letter or digit), print it.


if (Character.isLetterOrDigit(cs)) {
System.out.print(cs);
}
// If it's an opening parenthesis, push it onto the stack.
else if (cs == '(') {
stack.push(cs);
}
// If it's a closing parenthesis, pop and print until '(' is found.
else if (cs == ')') {
while (!stack.isEmpty() && stack.topElement() != '(') {
System.out.print(stack.pop());
}
stack.pop(); // Discard the opening '('
}
// If it's an operator, check for precedence and pop accordingly.
else {
while (!stack.isEmpty() && priority(cs) <= priority(stack.topElement())) {
System.out.print(stack.pop());
}
stack.push(cs);
}
index++;
}

// After reading the entire expression, pop remaining operators in the stack.
while (!stack.isEmpty()) {
System.out.print(stack.pop());
}
}
// priority() returns precedence levels for operators.
public static int priority(char op) {
switch (op) {
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1; // For unknown operators
}
}

Sample Input/Output:

Test Case 1:
Input:
Enter the Infix Expression:
A+B*C

Output:
ABC*+

Test Case 2:
Input:
Enter the Infix Expression:
(A+B)*(C+D)

Output:
AB+CD+*

Post-Lab Questions:
1. What is the main advantage of using postfix notation over infix notation?
2. Explain how the stack is used to handle operator precedence in this algorithm.
3. What happens when parentheses are used in the infix expression?
4. Write the postfix expression for the infix expression A*B-(C+D)/E.

Conclusion:
In this lab, you have implemented a program to convert infix expressions to postfix using a
stack data structure. You learned how to handle operator precedence, parentheses, and the
order of evaluation in mathematical expressions.

Test Cases:

Test Case 1:
Input:
Enter the Infix Expression:
((A+B)*(C-D)/(E+F))^(G+H)

Output:
AB+CD-*EF+/GH+^

Test Case 2:
Input:
Enter the Infix Expression:
A+(B*C-(D/E^F)*G)*H

Output:
ABC*DEF^/G*-H*+

Test Case 3:
Input:
Enter the Infix Expression:
A*B+C/D-E^F^G

Output:
AB*CD/+EFG^^-

Test Case 4:
Input:
Enter the Infix Expression:
((A+B)*C-(D-E))^(F+G/H)

Output:
AB+C*DE--FGH/+^
Test Case 5:
Input:
Enter the Infix Expression:
A%B*C^D+(E-F/G)

Output:
AB%D*CD^EFG/-+

You might also like