Skip to content
Advertisement

confused about java looping

I just started learning programming and java is my first language. I’ve come across an exercise involving for loop, I’d like to know how the result is found:

int result = 0;
for (int i = 0; i < 5; i++){
    if(i == 3){ 
        result += 10;
    }
    else{
        result += i;
    }
}
System.out.println(result);

the output is: 17

I know this is a silly basic question but I really need to understand how the result is 17.

Advertisement

Answer

In your loop :

  • the i starts at 0, so the first value is 0
  • it stops when i<5 is not true, so when i=5 it doesn’t loop, so the last value is 4

So iwill take the values:

i -> action
0 -> go into else : result +=  0 so result is 0
1 -> go into else : result +=  1 so result is 1 
2 -> go into else : result +=  2 so result is 3
3 -> go into if   : result += 10 so result is 13
4 -> go into else : result +=  4 so result is 17
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement