See Similar Post: Infix to Postfix Calculator
#include<stdio.h>
#include<string.h>
char stack[100];
int top = -1;
void push(char c)
{
top++;
stack[top] = c;
}
char pop()
{
char c = stack[top];
top--;
return c;
}
void show()
{
printf("\nStack: ");
for(int i=0;i<=top;i++)
printf("%c, ", stack[i]);
printf("\n");
}
bool isOperator(char c)
{
if(c == '+'||c == '-'||c == '*'||c == '/'||c == '^')
return true;
return false;
}
int precedence(char c)
{
if(c == '+' || c == '-')
return 1;
else if(c == '*' || c == '/')
return 2;
else if(c == '^')
return 3;
else return 0;
}
int main()
{
char infix[100], postfix[100];
int length, k = 0, i;
printf("Enter Postfix Expression:\n");
gets(infix);
length = strlen(infix);
infix[length] = ')';
push('(');
for(i=0;i<=length;i++)
{
if(infix[i] == '(')
{
printf("\nLeft Parenthesis Detected. Push it to STACK\n");
push(infix[i]);
show();
}
else if(infix[i] == ')')
{
printf("\nRight Parenthesis Detected. POP until ( detected.\n");
char p = pop();
while(p != '(')
{
postfix[k++] = p;
p = pop();
}
show();
}
else if(isOperator(infix[i]))
{
printf("\nOperator Detected. POP until we get same or higher precedence operator.\n");
while(isOperator(stack[top]) &&
precedence(stack[top]) >= precedence(infix[i]))
{
postfix[k++] = pop();
}
push(infix[i]);
show();
}
else
{
printf("\nOperand Detected. Add it to POSTFIX\n");
postfix[k++] = infix[i];
show();
}
}
postfix[k] = '\0';
puts(postfix);
return 0;
}
#include<string.h>
char stack[100];
int top = -1;
void push(char c)
{
top++;
stack[top] = c;
}
char pop()
{
char c = stack[top];
top--;
return c;
}
void show()
{
printf("\nStack: ");
for(int i=0;i<=top;i++)
printf("%c, ", stack[i]);
printf("\n");
}
bool isOperator(char c)
{
if(c == '+'||c == '-'||c == '*'||c == '/'||c == '^')
return true;
return false;
}
int precedence(char c)
{
if(c == '+' || c == '-')
return 1;
else if(c == '*' || c == '/')
return 2;
else if(c == '^')
return 3;
else return 0;
}
int main()
{
char infix[100], postfix[100];
int length, k = 0, i;
printf("Enter Postfix Expression:\n");
gets(infix);
length = strlen(infix);
infix[length] = ')';
push('(');
for(i=0;i<=length;i++)
{
if(infix[i] == '(')
{
printf("\nLeft Parenthesis Detected. Push it to STACK\n");
push(infix[i]);
show();
}
else if(infix[i] == ')')
{
printf("\nRight Parenthesis Detected. POP until ( detected.\n");
char p = pop();
while(p != '(')
{
postfix[k++] = p;
p = pop();
}
show();
}
else if(isOperator(infix[i]))
{
printf("\nOperator Detected. POP until we get same or higher precedence operator.\n");
while(isOperator(stack[top]) &&
precedence(stack[top]) >= precedence(infix[i]))
{
postfix[k++] = pop();
}
push(infix[i]);
show();
}
else
{
printf("\nOperand Detected. Add it to POSTFIX\n");
postfix[k++] = infix[i];
show();
}
}
postfix[k] = '\0';
puts(postfix);
return 0;
}
Sample Input:
(a+b)
Sample Ouput:
ab+
Tags:
C