0

I assume that if I can't convert my while loop into a for loop, then I don't fully understand the concepts here. Here's my working while loop:

(I am trying to implement a program, which calculates the sum 1+2+3+...+n where n is given as user input.)

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int number = Integer.valueOf(scanner.nextLine());

        int sum = 0;
        int i = 0;

        while (i < number) {
            i++;
            sum += i;
        }
        System.out.println(sum);

I was looking at this user's answer here: https://stackoverflow.com/a/36023451/11522261 and tried to implement it, but it's not working.

.....
for (i = 0; i < number; i++){
            sum += i;
        }
        System.out.println(sum);

It looks like the conditions of For Init expression statement and ForUpdate are set right, but I'm having trouble understanding the differences here.

Also, it looks like this exercise is trying to teach loops to solve iterative problems. But I suspect that this isn't helping me practice recursion. Perhaps there is a recursive solution to this problem which would be better. Just thinking out loud here. Thanks!

3
  • Why was my question downvoted? Commented Feb 23, 2020 at 19:27
  • @T.J.Crowder right, I did not want to write it out, just like IMHO is better not worded. Commented Feb 23, 2020 at 20:00
  • Downvoting can also happen on not finding the question very challenging or the problem exemplary. Here incrementing before or after summing i. Nothing important. Commented Feb 23, 2020 at 20:03

3 Answers 3

4

The difference is that in your while loop, you're incrementing i before adding it to sum, but in your for loop, it's after.

If the while is producing the right result, you can adjust your for by starting at 1 instead of 0 and continuing while <= number instead of < number.

For completeness, here's how your current for loop works:

  1. i = 0
  2. If i < number is not true, exit the loop; otherwise, continue to Step 3
  3. sum += i (i is still 0)
  4. i++
  5. Goto Step 2

On the second pass, i < number is 1 < number so still true if number is greater than 1, so you go to Step 3, do sum += i while i is 1, then continue.

Eventually i < number isn't true anymore, and the loop exits.


For problems like this, the best approach is usually to use the debugger built into your IDE to step through the code statement by statement, looking at the values of variables as you go. That can reveal how things work really well. This article may be helpful: How to debug small programs

Sign up to request clarification or add additional context in comments.

Comments

1

Since you are incrementing the value of i before adding it to sum in the while loop, the same thing needs to be done in case of for loop as well. Given below is the implementation using the for loop:

for (i = 0; i++ < number; ){
    sum += i;
}
System.out.println(sum);

Comments

1

Use <= instead of <. This will solve Your problem, and make sure you understand why will the following code would work. I would recommand you to use a paper and pencil and start writing down the values of i and sum after every iteration.

for (i = 1; i <= number; i++) { 
    sum += i;
}

2 Comments

@T.J.Crowder Why is this not sufficient? Including or excluding zero from the loop isn't going to affect the sum.
@khelwood - Ah, you have a good point there! Because i will be 0 and not affect the sum. Still, the extra loop isn't ideal. But you're right, this does solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.