Вы находитесь на странице: 1из 4

Assignment: 4

1. Write a C program to convert an infix expression into postfix expression.


2. Write a C program to evaluate a postfix expression.

SOURCE CODE

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define Blank ' '
#define Tab '\t'
#define MAX 50

long int pop ();


long int eval_post();
char infix[MAX], postfix[MAX];
long int stack[MAX];
int top;
void infix_to_postfix();
int prec(char symbol );
void push(long int symbol);
long int pop();
int white_space(char symbol);

int main()
{
long int value;
char choice='y';
while(choice == 'y')
{
top = 0;
printf("Enter infix : ");
fflush(stdin);
gets(infix);
infix_to_postfix();
printf("THE POSTFIX EXPRESSION IS : %s\n",postfix);
getch();
value=eval_post();
printf("Value of expression : %ld\n",value);
printf("Want to continue(y/n) : ");
fflush(stdin);
scanf("%c",&choice);

}
}

void infix_to_postfix()
{
int i,p=0,type,precedence,len;
char next ;

stack[top]='#';
len=strlen(infix);
infix[len]='#';
for(i=0; infix[i]!='#';i++)
{

if( !white_space(infix[i]))
{
switch(infix[i])
{
case '(':
push(infix[i]);
break;

case ')':
while((next = pop()) != '(')
postfix[p++] = next;

break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
precedence = prec(infix[i]);
while(stack[top]!='#' && precedence<= prec(stack[top]))
postfix[p++] = pop();
push(infix[i]);
break;
default:
postfix[p++] = infix[i];
}
}
}
while(stack[top]!='#')
postfix[p++] = pop();
postfix[p] = '\0' ;
}

int prec(char symbol )


{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
}

void push(long int symbol)


{
if(top > MAX)
{
printf("Stack overflow\n");
exit(0);
}
else
{
top=top+1;
stack[top] = symbol;
}
}

long int pop()


{
if (top == -1 )
{
exit(0);
}
return (stack[top--]);
}

int white_space(char symbol)


{
if( symbol == Blank || symbol == Tab || symbol == '\0')
return 1;
else
return 0;
}

long int eval_post()


{
long int a,b,temp,result,len;
int i;
len=strlen(postfix);
postfix[len]='#';

for(i=0;postfix[i]!='#';i++)
{
if(postfix[i]<='9' && postfix[i]>='0')
push( postfix[i]-48 );
else
{
a=pop();
b=pop();

switch(postfix[i])
{
case '+':
temp=b+a; break;
case '-':
temp=b-a;break;
case '*':
temp=b*a;break;
case '/':
temp=b/a;break;
case '%':
temp=b%a;break;
case '^':
temp=pow(b,a);
}
push(temp);
}
}
result=pop();
return result;
}
OUTPUT

Enter infix : 2*(3+4)-6

THE POSTFIX EXPRESSION IS : 234+*6-

Value of expression : 8

Want to continue(y/n) : y

Enter infix : (a+b)*(c+d)

THE POSTFIX EXPRESSION IS : ab+cd+*

--------------------------------

Process exited after 38.02 seconds with return value 0

Press any key to continue . . .

Вам также может понравиться