Click here to Skip to main content
15,513,489 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
After I have added 'sum++' to the code, the output has changed from 5 to 7, I wonder why?

'Keyboard.readInput()' is to read user input. In this case, the input are 3, 2, and -1 to stop the loop.



C#
public class MyProgram
{
    public void start()
    {
        int sum = 0;
        System.out.println("Enter number: ");
        int num = Integer.parseInt(Keyboard.readInput());

        while (num >= 0)
        {
            sum = sum + num;
            System.out.print("Enter number: ");
            num = Integer.parseInt(Keyboard.readInput());
            sum++;
        }

        System.out.println("Sum: " + sum);
    }
}
Posted

To understand, just cycle the while loop, and you will see that:
first loop, num = 3
sum = sum + num  // sum becomes 3
sum++ // sum becomes 4


second loop, num = 2
sum = sum + num // sum becomes 6
sum++ // sum becomes 7
 
Share this answer
 
Comments
_Asif_ 10-Jul-14 2:43am    
+5 :)
Peter Leow 10-Jul-14 5:24am    
Thank you, Asif.
there is nothing to wonder, Only you need to know what is increment operator and what it does.
read few article/tutorials about this operator and try to learn
Assignment, Arithmetic, and Unary Operators[^]
Java increment & decrement operator[^]
 
Share this answer
 

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