Hy @donnaghai
The problem asks you to to prepare a cumulative sum of given integer sequence and whenever this cumulative sum becomes negative you need to stop. There was an issue in the output format which I have updated in the problem statement so do check it out.
Now discussing your approach, as I saw your current solution you are running an infinite loop and tracking the cumulative sum. So the first thing to notice is that as in the statement of the problem says that you have to stop only when the input becomes negative i.e you have to keep processing the input for positive cumulative sum as well as when cumulative sum becomes zero. So this is the reason why you should put sum >=0 in your If conditional.
But there is one more issue, consider the following test case:
5
6
-11
Here your solution will get a Run Time Error because you are running an infinite loop so when you will process -11 your sum will become 0, you will print -11 and again your loop will execute (as its an infinite loop) now there is no more input but still you will be taking another input and there is no input present so you will get a runtime error. (Try applying this input in your eclipse IDE and also dry run this on paper with this testcase you will get my point). So to avoid this issue there is a concept of reading the input till End Of File.
So what is End Of File in an input? End-of-file is a condition in a computer operating system where no more data can be read from a data source. The data source is usually called a file or stream. So in your case it is a stream (Because you are giving input from console and not from a file).
So instead of an Infinite loop you should process the numbers till End-Of-File.
How to check End-Of-File in JAVA? You can use sc.hasNext()
. This method Returns true if this scanner has another token in its input or simply saying it has reached end of file. This method returns true if and only if this scanner has another token. You can look at the following code: https://ide.codingblocks.com/s/72853. Here I have updated your code and made the proper required changes. If you are not able to understand this feel free to reply to this thread.
Thanks, And Regards
Sanket Singh