Experiment 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Experiment No.

2
Infix to Postfix Conversion

Write a program to convert an Infix expression to the Postfix expression using


Stack

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

#define SIZE 100 // Define maximum size of the stack

// Stack structure for operators


struct Stack {
char items[SIZE];
int top;
};

// Initialize the stack


void initialize(struct Stack* stack) {
stack->top = -1;
}

// Check if the stack is full


int isFull(struct Stack* stack) {
return (stack->top == SIZE - 1);
}

// Check if the stack is empty


int isEmpty(struct Stack* stack) {
return (stack->top == -1);
}

// Push an element onto the stack


void push(struct Stack* stack, char value) {
if (isFull(stack)) {
printf("Stack is full! Cannot push %c\n", value);
} else {
stack->items[++(stack->top)] = value;
}
}

// Pop an element from the stack


char pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty! Cannot pop\n");
return -1;
} else {
return stack->items[(stack->top)--];
}
}

// Peek the top element of the stack


char peek(struct Stack* stack) {
if (isEmpty(stack)) {
return -1;
} else {
return stack->items[stack->top];
}
}

// Function to check if a character is an operator


int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}

// Function to define precedence of operators


int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
// Function to convert infix expression to postfix
void infixToPostfix(char* infix, char* postfix) {
struct Stack stack;
initialize(&stack);
int i, j = 0;

for (i = 0; i < strlen(infix); i++) {


char ch = infix[i];

// If the character is an operand, add it to the output


if (isalnum(ch)) {
postfix[j++] = ch;
}
// If the character is '(', push it onto the stack
else if (ch == '(') {
push(&stack, ch);
}
// If the character is ')', pop and output from the stack until '(' is found
else if (ch == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[j++] = pop(&stack);
}
pop(&stack); // Pop '(' from the stack
}
// If the character is an operator
else if (isOperator(ch)) {
while (!isEmpty(&stack) && precedence(peek(&stack)) >= precedence(ch)) {
postfix[j++] = pop(&stack);
}
push(&stack, ch);
}
}

// Pop all the remaining operators from the stack


while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}
postfix[j] = '\0'; // Null-terminate the postfix expression
}
// Main function
int main() {
char infix[SIZE], postfix[SIZE];

printf("Enter an infix expression: ");


scanf("%s", infix);

infixToPostfix(infix, postfix);

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

return 0;
}

OUTPUT
Enter an infix expression: A*(B+C)/D

Postfix expression: ABC+*D/

You might also like