Reputation: 41
Can anyone help me understand how this equals to 400? I can't figure it out how the for
works.
import java.util.*; //for class Scanner
public class Exercise
{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int value =0;
for (int num = 10; num<= 40; num +=2){
value =value+num;
}
System.out.println(value);
}
Upvotes: 2
Views: 71
Reputation: 97212
It's probably easiest to understand if you look at the actual values that will be used when the loop is evaluated. Given that num
is initialized to 10, and the loop will end when it equals or exceeds 40, these are the 16 iterations the loop goes through:
value = value + num
-------------------
value = 0 + 10
value = 10 + 12
value = 22 + 14
value = 36 + 16
value = 52 + 18
value = 70 + 20
value = 90 + 22
value = 112 + 24
value = 136 + 26
value = 162 + 28
value = 190 + 30
value = 220 + 32
value = 252 + 34
value = 286 + 36
value = 322 + 38
value = 360 + 40
The final value of value
being 400.
Upvotes: 6
Reputation: 291
first pass
value = value + num;
10 = 0 + 10;
second pass:
value = value + num;
22 = 10 + 12
third pass:
value = value + num;
36 22 + 14
in a for loop
for(initializer, condition, increment){
do something!
}
initializer is the beginning number
condition is what will cause the loop to stop
increment is how much you want to add to the initializer in order to meet the condition at the correct time.
Upvotes: 1
Reputation: 201467
A Java for
loop is an example of a Traditional for
loop, from the linked Wikipedia page,
for(INITIALIZATION; CONDITION; INCREMENT/DECREMENT){
// Code for the for loop's body
// goes here.
}
So, your posted example is equivalent to
int value = 0;
int num = 10;
while (num <= 40) {
value += num;
num += 2;
}
System.out.println(value);
Of course, you could simply add output to see it in action with,
for (int num = 10; num <= 40; num += 2) {
System.out.printf("value = %d, num = %d%n", value, num);
value = value + num;
}
Upvotes: 5