i am not getting correct output for this program getting as abcde-*++ for give input in main
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Stack{
int capacity;
int top;
int *array;
};
struct Stack* createstack(int capacity){
struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
stack->top=-1;
stack->capacity=capacity;
stack->array=(int*)malloc(sizeof(int)*capacity);
return stack;
}
char pop(struct Stack* stack){
return(stack->array[stack->top--]);
}
void push(struct Stack* stack,char ch ){
stack->array[++stack->top]=ch;
}
int isempty(struct Stack* stack){
return(stack->top==-1);
}
int isfull(struct Stack* stack){
return(stack->top==stack->capacity-1);
}
int isfront(struct Stack* stack){
return(stack->array[stack->top]);
}
int precedence(char ch){
switch(ch){
case 1: ch=='+';
case 2: ch=='-';
return 1;
case 3: ch=='*';
case 4: ch=='/';
return 2;
case 5: ch=='^';
return 3;
return-1;
}
}
int isoperand(char ch){
return(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z');
}
void infixtopostfix(struct Stack* stack,char* exp){
int i,k=-1;
char res[100];
for(i=0;exp[i];i++){
///if an operand is encountered
if(isoperand(exp[i]))
res[++k]=exp[i];
///if an operator is encountered
else{
// if(isempty(stack)||precedence(isfront(stack))<precedence(exp[i]))
//else
while(!isempty&&precedence(isfront(stack))>=precedence(exp[i]))
res[++k]=pop(stack);
push(stack,exp[i]);
}
}
while(!isempty(stack))
res[++k]=pop(stack);
res[++k]='\0';
printf("%s",res);
}
int main(){
struct Stack* stack=createstack(100);
char arr[100]="a+b+c*d-e";
infixtopostfix(stack,arr);
}
This program is to convert the expression from infix to postfix Here is the Algorithm
Algorithm 1. Scan the infix expression from left to right.
If the scanned character is an operand, output it.
Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it. …..
3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
- Repeat steps until infix expression is scanned.
- Pop and output from the stack until it is not empty.
i Am not getting correct output getting as
abcde-*++
for the given input in my main function
abcde-*++
; it should be more likeabcd*e-++
, shouldn't it? You have to do the subtraction after the multiplication, not before. Theabcde-*++
expression in infix would bea+b+c*(d-e)
, I think. – Jonathan Lefflerprecedence
function is not going to work the way you think it does. The value in thecase
label is the value of the control variable which causes the clause to be selected. So, for example,case 1: ch == '+';
will trigger ifch
is 1 (which is highly unlikely, since that doesn't correspond to any normal character), and if it does trigger, it will then execute the statementch=='+';
, which does nothing. – rici