Develop a Program in C for converting an Infix Expression to Postfix Expression. Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char c) {
stack[++top] = c;
}
char pop() {
return (top == -1) ? '\0' : stack[top--];
}
char peek() {
return (top == -1) ? '\0' : stack[top];
}
int precedence(char op) {
switch (op) {
case '^': return 3;
case '*': case '/': case '%': return 2;
case '+': case '-': return 1;
default: return 0;
}
}
int isRightAssociative(char op) {
return (op == '^');
}
void infixToPostfix(char *infix, char *postfix) {
int i = 0, k = 0;
char ch;
while ((ch = infix[i++]) != '\0') {
if (isalnum(ch)) {
postfix[k++] = ch;
}
else if (ch == '(') {
push(ch);
}
else if (ch == ')') {
while (peek() != '(')
postfix[k++] = pop();
pop(); // remove '('
}
else { // operator
while (precedence(peek()) > precedence(ch) ||
(precedence(peek()) == precedence(ch) && !isRightAssociative(ch))) {
postfix[k++] = pop();
}
push(ch);
}
}
while (top != -1)
postfix[k++] = pop();
postfix[k] = '\0';
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter Infix Expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
printf("Postfix Expression is: %s\n", postfix);
return 0;
}
Enter Infix Expression: (A+B)*C^D
Postfix Expression is: AB+CD^*
Replay !
Share Your Thoughts