Ds Assignment 4
Ds Assignment 4
Ds Assignment 4
4. WAP to convert Infix expression into equivalent Postfix and Prefix format
using Stack.
1. Infix to Prefix
# include <stdio.h>
# include <string.h>
# define MAX 20
int top=-1
char stack[MAX];
char pop() {
char a;
a=stack[top];
top--;
return a;
}
int precedence(char symbol) // returns the value that helps in the precedence
{
switch(symbol) {
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '$':
case '^':
return 6;
break;
case '#':
case '(':
case ')':
return 1;
break;
}
}
symbol=infix[i];
if (isOperator(symbol)==0) {
prefix[j]=symbol;
j++;
}
else {
if (symbol==')') {
push(symbol);
}
else if(symbol == '(') {
while (stack[top]!=')') {
prefix[j]=pop();
j++;
}
pop();
}
else {
if (precedence(stack[top])<=precedence(symbol)) {
push(symbol);
}
else {
while(precedence(stack[top])>=precedence(symbol)) {
prefix[j]=pop();
j++;
}
push(symbol);
}
}
}
while (stack[top]!='#') {
prefix[j]=pop();
j++;
}
prefix[j]='\0';
}
int main() {
char infix[20],prefix[20],postfix[20],temp;
printf("\nEnter infix operation: ");
gets(infix);
printf("\nInfix to Prefix Conversion: ");
infixtoprefix(infix,prefix);
strrev(prefix);
puts((prefix));
Output:
2. Infix to Postfix
3. # include <stdio.h>
4. # include <string.h>
5. #include <stdlib.h>
6. #define MAX 100
7.
8. char stack[MAX];
9. char infix[MAX],postfix[MAX];
10.int top=-1;
11.
12.void push(char);
13.char pop();
14.int isEmpty();
15.void inToPost();
16.int space(char);
17.void print();
18.int precedence(char);
19.
20.int main(){
21. printf("\nEnter infix operation: ");
22. gets(infix);
23. inToPost();
24. print();
25. return 0;
26.}
27.
OUTPUT: