C Program to convert Prefix Expression into Postfix

C Program to convert Prefix Expression into Postfix .
Source: Dr. G T Raju, Professor & Head, Dept. of CSE, RNSIT

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
71
72
#include <string.h>
#include <ctype.h>
char opnds[50][80],oprs[50];
int  topr=-1,topd=-1;
pushd(char *opnd)
{
strcpy(opnds[++topd],opnd);
}
char *popd()
{
return(opnds[topd--]);
}
 
pushr(char opr)
{
oprs[++topr]=opr;
}
char popr()
{
return(oprs[topr--]);
}
int empty(int t)
{
if( t == 0) return(1);
return(0);
}
 
main()
{
char prfx[50],ch,str[50],opnd1[50],opnd2[50],opr[2];
int i=0,k=0,opndcnt=0;
gets(prfx);
printf(" Given Prefix Expression : %s\n",prfx);
while( (ch=prfx[i++]) != '\0')
{
if(isalnum(ch))
{
str[0]=ch; str[1]='\0';
pushd(str); opndcnt++;
if(opndcnt >= 2)
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,opnd1);
strcat(str,opnd2);
ch=popr();
opr[0]=ch;opr[1]='\0';
strcat(str,opr);
pushd(str);
opndcnt-=1;
}
}
else
{
pushr(ch);
if(opndcnt==1)opndcnt=0;  /* operator followed by single operand*/
}
}
if(!empty(topd))
{
strcpy(opnd2,popd());
strcpy(opnd1,popd());
strcpy(str,opnd1);
strcat(str,opnd2);
ch=popr();
opr[0]=ch;opr[1]='\0';
strcat(str,opr);
pushd(str);
}
printf(" Postfix Expression: ");
puts(opnds[topd]);
}
Ansten Lobo

One thought on “C Program to convert Prefix Expression into Postfix

  1. I am Very Thank Ful To this website for helping me to solve many problems in programming.. and to clearing the doubts…!

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in