Vous êtes sur la page 1sur 6

//12.

PROGRAM TO CONVERT AN INFIX EXPRESSION TO POSTFIX EXPRESSION


#include<ctype.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>

char infix[30],postfix[30],stack[30],ch;
int top=-1,i=0,j=0;

void push(char symbol)


{
top++;
stack[top]=symbol;
}

char pop()
{
char op;
op=stack[top];
top--;
return op;
}

//function to assign precedence to operators


int prec(char op)
{
if(op=='('||op==')')
return 0;
else if(op=='^')
return 3;
else if(op=='/'||op=='*'||op=='%')
return 2;
else if(op=='+'||op=='-')
return 1;
else
return -1;
}

void main()
{
clrscr();

stack[++top]='#'; //initialize the stack

printf("Enter valid infix expression\n");


gets(infix);

for(i=0;i<strlen(infix);i++)
{
ch=infix[i];

//1. if scanned symbol is an operand - add to postfix


if(isalpha(ch)||isdigit(ch))
postfix[j++]=ch;
//2. if scanned symbol is left parenthesis - pust to stack
else if(ch=='(')
push(ch);
//3. if scanned symbol is right parentheses - pop and add to postfix
else if(ch==')')
{
while(stack[top]!='(')
postfix[j++]=pop();
pop(); //to remove ( from stack
}
//4. if the infix has an invalid operator
else if(prec(ch)<=0)
{
printf("\nINVALID INFIX EXPRESSION\n");
getch();
exit(0);
}
//5. if the scanned symbol is a valid arithmetic operator
else
{
if(prec(ch)>prec(stack[top]))
push(ch);
else
{
while(prec(stack[top])>=prec(ch))
postfix[j++]=pop();

push(ch);
}
}
} //end of for loop

//to remove remaining operators from stack


while(stack[top]!='#')
postfix[j++]=pop();

//to terminate postfix


postfix[j]='\0';
printf("\nPOSTFIX EXPRESSION \n");
printf("%s",postfix);

getch();
}

//13. PROGRAM TO EVALUATE A POSTFIX EXPRESSION


#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>

char stack[50],postfix[50],ch;
int top=-1,i;
float value,result,a,b,final_value;

void push(float oper)


{
top++;
stack[top]=oper;
}

float pop()
{
float oper;
oper=stack[top];
top--;
return oper;
}
void main()
{
clrscr();
printf("Enter a valid postfix expression\n");
gets(postfix);
for(i=0;i<strlen(postfix);i++)
{
ch=postfix[i];
if(isdigit(ch))
push(ch-'0'); //To convert from string type to integer
else if(isalpha(ch))
{
printf("Enter value of %c",ch);
scanf("%f",&value);
push(value);
}
else
{
a=pop();
b=pop();
switch(ch)
{
case '+':result=b+a;
push(result);
break;
case '-':result=b-a;
push(result);
break;
case '*':result=b*a;
push(result);
break;
case '/':result=b/a;
push(result);
break;
case '%':result=(int)b%(int)a;
push(result);
break;
default: printf("\nInvalid postfix expression");
getch();
exit(0);
}
}
}
final_value=pop();
printf("\nRESULT OF EXPRESSION IS : %f",final_value);
getch();
}

Vous aimerez peut-être aussi