INFIX TO POSTFIX AND PREFIX
//NAME – DIVYA PATWA |IT SEC 2|DSA | 24U030070
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
typedef struct {
char arr[MAX];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
void push(Stack *s, char ch) {
if (s->top < MAX - 1)
s->arr[++s->top] = ch;
char pop(Stack *s) {
return (s->top != -1) ? s->arr[s->top--] : '\0';
}
INFIX TO POSTFIX AND PREFIX
char peek(Stack *s) {
return (s->top != -1) ? s->arr[s->top] : '\0';
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
if (op == '^') return 3; // Right associative
return 0;
void reverse(char *str) {
int i, len = strlen(str);
for (i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
void infixToPostfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i, j = 0;
for (i = 0; infix[i] != '\0'; i++) {
char ch = infix[i];
INFIX TO POSTFIX AND PREFIX
if (isalnum(ch)) {
postfix[j++] = ch;
else if (ch == '(') {
push(&s, ch);
else if (ch == ')') {
while (s.top != -1 && peek(&s) != '(') {
postfix[j++] = pop(&s);
pop(&s);
else {
while (s.top != -1 && precedence(peek(&s)) >= precedence(ch)) {
postfix[j++] = pop(&s);
push(&s, ch);
while (s.top != -1) {
postfix[j++] = pop(&s);
postfix[j] = '\0';
void infixToPrefix(char *infix, char *prefix) {
reverse(infix);
for (int i = 0; infix[i] != '\0'; i++) {
INFIX TO POSTFIX AND PREFIX
if (infix[i] == '(') infix[i] = ')';
else if (infix[i] == ')') infix[i] = '(';
infixToPostfix(infix, prefix);
reverse(prefix);
int main() {
char infix[MAX], postfix[MAX], prefix[MAX];
printf("Enter an infix expression: ");
scanf("%s", infix);
infixToPostfix(infix, postfix);
infixToPrefix(infix, prefix);
printf("Infix Expression: %s\n", infix); OUTPUT
printf("Postfix Expression: %s\n", postfix);
printf("Prefix Expression: %s\
n", prefix);
return 0;