0
Why the output is coming as 17?
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); } }
5 odpowiedzi
+ 9
Like my other answer (same question):
Normally it loops through and adds i to result, except when i is 3, in which case it adds 10. Here it is:
Loop # i val. result val.
1. 0. 0
2. 1. 1 (0+1)
3. 2. 3 (1+2)
4. 3. 13 (3+10 because i is 3)
5. 4. 17 (13+4)
6. 5. i is not < 5 so the loop body is not executed. It exits the loop and prints result, which is 17. I hope this helps.
+ 1
Because in the for loop, if I is equal to 3 then add 10 to the variable result, else add I to the variable result.
So, 0 + 1 + 2 + 10 + 4 = 17
0
@Mohamad Abdelhafiz Sorry actual source code was this and the output is 17 can you explain this?
0
In starting result = 0, according to if condition result += i, means you add i in result where i=3 therefore result += 3 , result = 3.
0
@Mohit Kumar the question is modified pls check.