+ 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); } }

10th Sep 2018, 4:50 AM
Abhishek Shirawale
Abhishek Shirawale - avatar
3 ответов
+ 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
10th Sep 2018, 4:58 AM
Dibas Behera
Dibas Behera - avatar
0
k=0 (5 loop), k=1 ( 4 loop) ... calculate from 0 to 5, then k=5 loop breake.
10th Nov 2018, 9:33 AM
alanmishin
- 2
ans is 4
24th Sep 2018, 5:48 PM
Sumit