Program 4
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.
Algorithm:
Step 1: Start.
Step 2: Read an infix expression with parenthesis and without parenthesis.
Step 3: convert the infix expression to postfix expression.
Step 4: Stop
Program:-
#define SIZE 50 /* Size of Stack */
#include <ctype.h>
#include <stdio.h>
char s[SIZE];
int top = -1; /* Global declarations */
push(char elem) /* Function for PUSH operation */
s[++top] = elem;
char pop() /* Function for POP operation */
return (s[top--]);
1
Program 4
int pr(char elem) /* Function for precedence */
switch (elem)
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
case '%':
return 3;
case '^':
return 4;
void main() /* Main Program */
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("\n\nEnter the Infix Expression ");
2
Program 4
scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0')
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')')
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
else /* Operator */
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
3
Program 4
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
Output 1:
Enter the Infix Expression: (a+b)*c/d^5%1
Given Infix Expn: (a+b)*c/d^5%1
Postfix Expn: ab+c*d5^/1%
Output 2:
Enter the valid infix expression: (a+b)+c/d*e
The entered infix expression is : (a+b)+c/d*e
The corresponding postfix expression is : ab+cd/e*+