C program which converts given expression into its post-fix format

Below C program converts a given expression into its post-fix format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
char s[20];
int top=-1;
void main()
{
    char str[20];
    char ch;
    int i;
    char pop();
    void push(char);
    int precd(char);
    s[top]='#';
    clrscr();
    printf("\n\t\tOUTPUT");
    printf("\n\tEnter the expression:");
    gets(str);
    printf("\n\tpostfix notation:");
    for(i=0;str[i]!='\0';i++)
    {
        if(isalpha(str[i]))
        {
            printf("%c",str[i]);
            continue;
        }
        if(str[i]==')')
        {
            while((ch=pop())!='(')
                printf("%c",ch);
        }
        else if(str[i]=='(')
            push(str[i]);
        else if(precd(str[i])<=precd(s[top]))
        {
            printf("%c",pop());
            push(str[i]);
        }
        else
            push(str[i]);
    }
    while(top>=0)
        printf("%c",pop());
    getch();
}
void push(char st)
{
    s[++top]=st;
}
char pop()
{
    char st;
    st=s[top--];
    return(st);
}
 
int precd(char s)
{
    switch(s)
    {
    case '$':return(4);
    case '*':
    case '/': return(3);
    case '+':
    case '-': return(2);
    case '(': return(1);
    case '#': return(-1);
    }
    return(0);
}

One Response to “C program which converts given expression into its post-fix format”

Leave a Reply