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

1.

Infix to Postfix Converter Program in C:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 25
int stack[MAX],TOP=-1;

int precedence(char symbol)


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

int operand(char c)
{
return((c >= 'a' && c <= 'z') ||(c >= 'A' && c <= 'Z') ||(c >= '0'
&& c <='9'));
}
int op(char c)
{
int result=0;
switch(c)
{
case '+':
case '-':
case '*':
case '/':
case '^':
result=1;break;
}
return(result);
}
void main()
{
char infix[MAX],postfix[MAX];
int p1,p2;
p1 = p2 = -1;
stack[++TOP]='(';
printf("Infix to Postfix Converter\n");
printf("-----------------------------\n\n");
printf("\nEnter the infix expression : ");
scanf("%s",infix);
while(infix[++p1]!='\0')
{
if(operand(infix[p1]))
{
postfix[++p2]=infix[p1];
}
else if(op(infix[p1]))
{
while(precedence(infix[p1]) <= precedence(stack[TOP]))
{
postfix[++p2]=stack[TOP--];
}
stack[++TOP]=infix[p1];
}
else if(infix[p1]=='(')
{
stack[++TOP]='(';
}
else if(infix[p1]==')')
{
while(stack[TOP]!='(')
{
postfix[++p2]=stack[TOP--];
}
TOP--;
}
else
{
printf("\nInvalid symbol ");
exit(1);
}
}
while(stack[TOP]!='(')
{
postfix[++p2]=stack[TOP--];
}
postfix[++p2]='\0';
printf("\nThe Postfix Expression is: %s\n\n",postfix);
}
2. Postfix Evaluation Program in C:

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

#define MAX 50
float stack[MAX];

int top=-1;

void push(float n)
{
if(top==MAX-1)
return ;
stack[++top]=n;
}

float pop()
{
return stack[top--];
}

void main()
{
char ch[20];
int i=0;
float A,B,C;

printf("A Program of Postfix Evaluation\n");


printf("----------------------------------\n\n");
printf("Enter a Correct Postfix Expression\n");
printf("\n Enter expression: ");
gets(ch);

while(ch[i]!='\0')
{
if(isdigit(ch[i]))
{
push(ch[i]-48);
}
else if(ch[i]!=32)
{
A=pop();
B=pop();
if(ch[i]=='*')
{
C=B*A;
}
else if(ch[i]=='/')
{
C=B/A;
}
else if(ch[i]=='+')
{
C=B+A;
}
else if(ch[i]=='-')
{
C=B-A;
}
push(C);
}
i++;
}
printf("\n Result = %f",stack[0]);

getch();
}

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