Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
my code doesnt work please help?! i am beginner. this is a code for prefix expression evaluation using stack in c
C++
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define MAX 20
int stack[MAX],opp1,opp2,top=-1;
void push(int x)
	{   
		top++;
		stack[top]=x;
	}
int pop()
	{   
	    char c;
	    c=stack[top];
	    top=top-1;
	    printf("%c",c);
	}
int prefixeval()
{ 
    int len;
	char prefix[20];
	int res,i;
	gets(prefix);
	len=strlen(prefix);
	for(i=len-1;prefix[i]>=0;i--)
	{
		if(isdigit(prefix[i]))
		{
		 push(prefix[i]-48);
		}
		else
		{
		opp1=pop();
		opp2=pop();
		switch(prefix[i])
		{
			case '+':push(opp1+opp2);
			         break;
			case '-':push(opp1-opp2);
			         break;
		    case '*':push(opp1*opp2);
			         break;
			case '/':push(opp1/opp2);
			         break;
			case '^':res=pow(opp1,opp2);
			         push(res);
			         break;
		}
		
	   }
   }   
	printf("result is %d",pop());
}
int main()
{   
    char prefix[20];
	printf("enter string");
	scanf("%s",prefix);
	prefixeval(prefix);
	
}


What I have tried:

i have tried the above code but everytime i enter a prefix expression result is coming 0
Posted
Updated 18-Aug-22 8:51am
v2
Comments
jeron1 18-Aug-22 13:08pm    
It shouldn't compile, you call

prefixeval(prefix); // calling with input parameter 'prefix'

but that method implementation takes no input parameters.

int prefixeval() <== No input parameters specified and should return an int
{
..... /// also I don't see where an int is being returned

}
palak rathore 18-Aug-22 13:30pm    
thankyou so much it did solve my problem!!though i am getting the correct output now but there are some characters(emojis to be more specific) appended with the output. can you please helo me with that?!
jeron1 18-Aug-22 13:41pm    
I would update your original post with your current version of code, then try and give a specific scenario with a specific input, and the desired output, and the actual output that you are seeing. There are many people here that are willing to help if given proper data to work with.

1 solution

This code (for goodness sake, put some spaces in there)
C
for(i = len - 1; prefix[i] >= 0; i--)
will end up using a negative index (i == -1 and below) until a prefix[i] that is negative is reached. When that will happen is unpredictable, because you're looking at memory that is out-of-bounds for the prefix array. Try this instead:
C
for(i = len - 1; i >= 0; i--)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900