infixtopostfix.c
67 linesc
DOWNLOAD
1// Aim: Program to perform Infix to Postfix conversion.
2#include<stdio.h>
3#include<stdlib.h>
4#include<ctype.h>
5char stack[10];
6int top=-1;
7
8void push(char x)
9{
10    stack[++top]=x;
11}
12
13char pop()
14{
15    return (stack[top--]);
16}
17
18int prec(char op){
19    switch (op){
20        case '+':
21        case '-':
22            return 1;
23        case '*':
24        case '/':
25            return 2;
26        case '(':
27        case '#':
28            return 0;
29    }
30}
31
32int main(){
33    char infix[20],postfix[20],symbol;
34    int i,k;
35    printf("Enter the infix expression\n");
36    scanf("%s",infix);
37
38    stack[++top]='#';
39    for(i=0,k=0;infix[i]!='\0';i++){
40        symbol=infix[i];
41        if(isalpha(symbol)){
42            postfix[k++]=symbol;
43            continue;
44        }
45        if(symbol=='('){
46            push(symbol);
47            continue;
48        }
49        if(symbol==')'){
50            while((symbol = pop()) != '('){
51                postfix[k++]=symbol;
52            }
53            continue;
54        }
55        while(prec(symbol)<=prec(stack[top])){
56            postfix[k++]=pop();
57        }
58        push(symbol);
59    }
60    while(stack[top]!='#'){
61        postfix[k++]=pop();
62    }
63    postfix[k]='\0';
64    printf("Infix expression is %s\n",infix);
65    printf("Postfix expression is %s\n",postfix);
66    return 0;
67}