Infix To Postfix Conversion.
CODE:-1
π
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX 20
- typedef struct
- {
- int data[MAX];
- int top;
- }STACK;
- void initstack(STACK *ps)
- {
- ps->top=-1;
- }
- void push(STACK *ps, int num)
- {
- ps->top++;
- ps->data[ps->top]=num;
- }
- int pop(STACK *ps)
- {
- return(ps->data[ps->top--]);
- }
- int isempty(STACK *ps)
- {
- return(ps->top==-1);
- }
- int isfull(STACK *ps)
- {
- return(ps->top=MAX-1);
- }
- void main()
- {
- void postfix(char in[], char post[]);
- char in[20], post[20];
- printf("Enter The Fully Parenthesized Infix Expression:\t");
- scanf("%s", in);
- postfix(in, post);
- printf("\n The Postfix String Is: %s",post);
- }
- void postfix(char in[], char post[])
- {
- int i, j=0;
- char ch1;
- STACK s1;
- initstack(&s1);
- for(i=0; in[i]!='\0'; i++)
- {
- switch(in[i])
- {
- case '+':
- case '-':
- case '*':
- case '/':
- case '%':
- case '(': push(&s1, in[i]);
- break;
- case ')': while((ch1=pop(&s1)) != '(')
- post[j++]=ch1;
- break;
- default: post[j++]=in[i];
- }
- }
- while(!isempty(&s1))
- post[j++]=pop(&s1);
- post[j]='\0';
- }
πExecuteπ
//OUTPUT
/*
Enter The Fully Parenthesized Infix Expression: (A+B)*(C-D)
The Postfix String Is: AB+CD-*
*/
CODE:-2
π
- #include<stdio.h>
- char ifix[200],pfix[200],stack[100];
- int p=0,s=0,i=0;
- void fun()
- {
- if(ifix[i]==')')
- {
- s--;
- while(stack[s]!='(')
- pfix[p++]=stack[s--];
- }
- if(ifix[i]=='+' || ifix[i]=='-')
- {
- if(!s)
- stack[s++]=ifix[i];
- else if(stack[s-1]=='(')
- stack[s++]=ifix[i];
- else
- {
- s--;
- while(s!=-1 && stack[s]!='(')
- {
- pfix[p++]=stack[s--];
- }
- stack[++s]=ifix[i];
- s++;
- }
- }
- }
- int main()
- {
- printf("Enter your infix expression(using operators +, -, %%, /, *) : ");
- scanf("%s",ifix);
- for(i;ifix[i]!='\0';i++)
- {
- if(ifix[i]!='*' && ifix[i]!='/' && ifix[i]!='-' && ifix[i]!='+' && ifix[i]!='(' && ifix[i]!=')' && ifix[i]!='%')
- pfix[p++]=ifix[i];
- else if(ifix[i]=='(' || ifix[i]=='*' || ifix[i]=='/' || ifix[i]=='%')
- stack[s++]=ifix[i];
- else
- fun();
- }
- if(ifix[i]=='\0')
- {
- if(s)
- {
- s--;
- while(s!=-1)
- {
- if(stack[s]==')' || stack[s]=='(')
- s--;
- pfix[p++]=stack[s--];
- }
- }
- pfix[p]='\0';
- }
- printf("The postfix expression is : %s",pfix);
- return 0;
- }
πExecuteπ
//OUTPUT
/*
Enter your infix expression(using operators +, -, %, /, *) :( A+B)*C(A-B)
The postfix expression is : AB+CAB-*
*/
//ThE ProFessoR
Comments
Post a Comment