Jan 24, 2012

Convert Infix to Postfix

Hello friends, holidays have come yes. Hurm, this holiday is very boring because there is no unpleasant. Throughout the day just hanging out in front of my laptop.

How even the vent hehehe, okay rather than bored I wanted to post the C + + program to convert infix notation to postfix notation. Ok check this out :


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
#define N 64
#define LP 10
#define RP 20
#define OPERATOR 30
#define OPERAND 40
#define LPP 0
#define AP 1
#define SP AP
#define MP 2
#define DP MP
#define REMP 2
#define NONE 9
static char infix[N+1],stack[N],postfix[N+1];
static int top;
void infixtopostfix(void);
int gettype(char);
void push(char);
char pop(void);
int getprec(char);
void main()
{
char ch;
do
{
clrscr();
top=-1;
printf("\n\n\n\n\t\t\tMASUKKAN BENTUK INFIX ==> ");
fflush(stdin);
gets(infix);
infixtopostfix();
printf("\t\t\tBENTUK POSTFIX ==> %s\n",postfix);
printf("\n\t\t\tAPAKAH INGIN MENGULANG?[Y/T]? ");
ch=getche();
printf("\n");
}while(ch=='Y' || ch=='y');
}
void infixtopostfix(void)
{
int i,p,l,type,prec;
char next;
i=p=0;
l=strlen(infix);
while(i<l)
{
type=gettype(infix[i]);
switch(type)
{
case LP:
push(infix[i]);
break;
case RP:
while((next=pop())!='(')
postfix[p++]=next;
break;
case OPERAND:
postfix[p++]=infix[i];
break;
case OPERATOR:
prec=getprec(infix[i]);
while(top>-1 && prec <= getprec(stack[top]))
postfix[p++]=pop();
push(infix[i]);
break;
}
i++;
}
while(top>-1)
postfix[p++]=pop();
postfix[p]=' ';
}
int gettype(char sym)
{
switch(sym)
{
case '(':
return(LP);
case ')':
return(RP);
case '+':
case '-':
case '*':
case '/':
case '%':
return(OPERATOR);
default :
return(OPERAND);
}
}
void push(char sym)
{
if(top>N)
{
printf("\nStack sudah penuh\n");
exit(0);
}
else
stack[++top]=sym;
}
char pop(void)
{
if(top<=-1)
{
printf("\nStack masih kosong\n");
exit(0);
}
else
return(stack[top--]);
}
int getprec(char sym)
{
switch(sym)
{
case '(':
return(LPP);
case '+':
return(AP);
case '-':
return(SP);
case '*':
return(MP);
case '/':
return(DP);
case '%':
return(REMP);
default :
return(NONE);
}
}


Well that program, to long right? If told to memorize certainly can not, does the program not to memorize but to understand. Thank you've read my posts, may be useful, so long. 

Share on Facebook
Share on Twitter
Share on Google+
Tags :

Related : Convert Infix to Postfix