Friday, 4 November 2016

Program 8 - Infix to Postfix Conversion



#include <stdio.h>
#include <ctype.h>
char stack[100];
int top = -1;
int priority(char ch){
if(ch == '*' || ch == '/'){
return 2;
} else if (ch == '+' || ch == '-'){
return 1;
} else {
//ch = '('
return 0;
}
}
void infix_to_postfix(char infix[], char postfix[]){
int i, j = 0;
char ch;
for(i = 0; infix[i] != '\0'; i++){
ch = infix[i];
//If scanned character is operand put it in postfix
if(isdigit(ch) || isalpha(ch)){
postfix[j++] = ch;
} else if(ch == '('){
// If scanned char is ( push it in stack
stack[++top] = ch;
} else if (ch == ')'){
// If scanned char is ) pop everthing till we get ( and discard that (
while(top != -1 && stack[top] != '('){
postfix[j++] = stack[top--];
}
// Now discard the (
if(top == -1){
printf("Invalid expression\n");
exit(0);
} else {
ch = stack[top--];
}
} else if(ch == '*' || ch == '/' || ch == '+' || ch == '-'){
/* If scanned char is operator and stack is empty then push into stack
* unless the char on top has higher or equal priority
* than the scanned char then go on popping
* till we get an operator which has less priority than ch
* then push the scanned operator on the stack
*/
if(top == -1 || priority(ch) > priority(stack[top])){
stack[++top] = ch;
} else {
while(priority(stack[top]) >= priority(ch) && top != -1){
postfix[j++] = stack[top--];
}
stack[++top] = ch;
}
} else {
printf("Invalid character\n");
exit(0);
}
}
//Now that the infix expression is totally scanned we empty the stack
while(top != -1 && stack[top] != '('){
postfix[j++] = stack[top--];
}
postfix[j++] = '\0';
}
int main(){
char infix[40], postfix[40];
printf("Enter infix expression: \n");
gets(infix);
infix_to_postfix(infix, postfix);
printf("The postfix equivalent is: \n");
printf("%s", postfix);
}






























































































































































No comments:

Post a Comment