Reputation: 97
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!
Upvotes: 0
Views: 191
Reputation: 1075327
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:
i = 0
i < number
is not true, exit the loop; otherwise, continue to Step 3sum += i
(i
is still 0
)i++
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
Upvotes: 4
Reputation: 2385
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;
}
Upvotes: 1
Reputation: 79550
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);
Upvotes: 1