coding (1)
coding (1)
coding (1)
ROLL:-35000120003
DEPARTMENT:-COMPUTER SCIENCE
TOPIC:- STACK
1.Conversion of infix expression to postfix expression using stack.
Ans:-
#include<stdio.h>
#include<ctype.h>
char stack[20];
int top=-1;
void push(char x)
{
stack[++top]=x;
}
char pop()
{
if(top==-1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x=='(')
return 0;
else if(x=='+'||x=='-')
return 1;
else if(x=='*'||x=='/')
return 2;
}
int main()
{
char exp[20];
char *e,x;
printf("Enter the expression\n");
scanf("%s",exp);
e=exp;
while(*e!='\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e=='(')
push(*e);
else if(*e==')')
{
while((x=pop())!='(')
printf("%c",x);
}
else
{
while(priority(stack[top])>=priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top!=-1)
{
printf("%c",pop());
}
}
Output:-
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct Stack
{
int top;
unsigned capacity;
int* array;
};
stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}
int main()
{
char exp[] = "475*+9-";
printf ("postfix evaluation: %d", evaluatePostfix(exp));
return 0;
}
Output:-
……………………………..X………………………………………