+ 2
How this code executes : 4 ?
public class Program { public static void main(String[] args) { int k=1, sum=0; while(k!=5){ if((k%2)!=0){ sum+=k; } k++; } System.out.println(sum); } }
3 Respostas
+ 5
iteration 1
k=1
k!=5 is true
(k%2)!=0 is true
sum becomes 1
iteration 2
k=2
k!=5 is true
(k%2)!=0 is false
sum remains 1
iteration 3
k=3
k!=5 is true
(k%2)!=0 is true
sum becomes 1+3=4
iteration 4
k=4
k!=5 is true
(k%2)!=0 is false
sum remains 4
iteration 5
k=5
k!=5 is false
loop breaks
sum remains 4
0
k=0 (5 loop), k=1 ( 4 loop) ... calculate from 0 to 5, then k=5 loop breake.
- 2
ans is 4