You are not logged in. Please login at www.codechef.com to post your questions!

×

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; }

asked 14 Apr '15, 11:34

kiran1995's gravatar image

1★kiran1995
1
accept rate: 0%

1

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

(14 Apr '15, 12:02) dragonemperor3★

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; }
link

answered 14 Apr '15, 12:01

dragonemperor's gravatar image

3★dragonemperor
89321135
accept rate: 10%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • 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:

×4

question asked: 14 Apr '15, 11:34

question was seen: 307 times

last updated: 14 Apr '15, 12:02