×

# what is the problem in my code??

hi..i am getting runtime error in this program plz help...

# include<stdio.h>

int main() { int cases,i,top=0; char exp[400],stack[200]; scanf("%d",&cases); while(cases) { scanf("%s",exp); printf("\n"); for(i=0;exp[i];i++) { if(exp[i]=='(') continue; if(exp[i]==')') { printf("%c",stack[top]); top--; } else if(exp[i]=='+' || exp[i]=='-' || exp[i]=='*' || exp[i]=='/') { top++; stack[top]=exp[i]; } else { printf("%c",exp[i]); } }

cases--; } return 0; }

1
accept rate: 0%

1

Please always provide a link to the problem or at least the problem code.

(14 Apr '15, 12:02)

 0 I wasn't able to figure out the error (sorry about that) but I found several errors in your code. 1) the printf("\n") should be there after the evaluation and printing. You have put it at the top. 2) Change the size of exp and stack to exp[401],stack[201]; The extra 1 is to store '\0' when exp length is 400. 3) Change the if statement to if(exp[i]==')' && top>=0) //to avoid underflow 4) Inside else statement where you print exp[i], add an if condition if(exp[i]!=')' && exp[i]!='(') printf("%c",exp[i]) Otherwise you are getting a ')' in the output 5) Initialize top to -1 not zero as you are always increasing it before storing the value in stack. Also initialize it for each test case inside the while loop. You have only initialized it once during declaration. 6) Even after this, your code is giving wrong answer for the third sample test case. I hope someone else can point out the error behind that.  #include< stdio.h> int main() { int cases,i,top=-1; char exp[401],stack[201]; //extra 1 to store \0 scanf("%d",&cases); while(cases) { scanf("%s",exp); //printf("\n"); //remove from here top=-1; for(i=0;exp[i];i++) { if(exp[i]=='(') continue; if(exp[i]==')' && top>=0) //to avoid underflow { printf("%c",stack[top]); top--; } else if(exp[i]=='+' || exp[i]=='-' || exp[i]=='*' || exp[i]=='/') { top++; stack[top]=exp[i]; } else { if(exp[i]!=')' && exp[i]!='(') printf("%c",exp[i]); } } printf("\n"); cases--; } return 0; }  answered 14 Apr '15, 12:01 893●2●11●35 accept rate: 10%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

question asked: 14 Apr '15, 11:34

question was seen: 307 times

last updated: 14 Apr '15, 12:02