0
public class Program { public static void main(String[] args) { int result = 0; for (int i=0; i<5; i++) { if (i==3) { result += 10; } else { result += i; } } System.out.println(result); } } The result is 17. But how? I want to understand. please help.
3 odpowiedzi
+ 6
initially we declare the result variable =0
then the for loop starts with int i=0
0<5 so it increments i by I++ then i becomes 1
then inside the loop it checks for the if condition now I=0 which is not equal to 3 then goes to else statement where result +=i means result =result +i now the result value is 0+1=1. like this it goes working on loop upto 4 which is less than 5 for only I=3 the if condition is true then the result +=10 is use so the ans becomes
0+0=0,when I=0
0+1=1,when I=1
1+2=3,when I=2
3+10=13 ,where I=3 tis operation takes place
13+4=17,when I=4.
I hope this will help u
+ 5
you must debug the algorithm.
the for is going to enter 5 times (0,1,2,3,4), when i is equal to 5, don't enter in the for loop.
the result variable start in 0, after that add 10 to de variable "result" just one time (when i is equal to 3), the others times add 0, 1, 2 and 4 (seven in total).
the final add is:
result + 0 = 0,
result + 1 = 1,
result + 2 = 3,
result + 3 = 13,
result + 4 = 17.
I don't know if is clear.
0
17