0

Explain me the answer

What is the output of this code? int [] b = {5, 6, 3, 8, 7} int sum = 0; for (int i = 0; i < 5; i ++) { if (i % 2 == 0); sum += b[i]; } System.out.print(sum); Answer: 15

2nd Jun 2020, 8:09 AM
Терещенко Дмитрий
Терещенко Дмитрий - avatar
4 odpowiedzi
+ 2
When i = 0, 0 % 2 == 0, b[i] = b[0] = 5 When i = 2, 2 % 2 == 0, b[i] = b[2] = 3 When i = 4, 4 % 2 == 0, b[i] = b[4] = 7 Finally 5 + 3 + 7 = 15
2nd Jun 2020, 8:14 AM
A͢J
A͢J - avatar
+ 2
If i%2==0 means if 0,1,2,3,4 divided by 2 results in remainder 0 add the value at the i index of array b to the variable sum so first 0%2 is equal to 0 ,so Loop starts again And same for 2%2 ,4%2 results in 0 So the value at index 2 and 4 also get added to sum sum+=b[i] it's like sum+=b[0] sum=sum+b[0] sum=0+5 sum=5 Again sum+=b[2] sum=sum+b[2] sum=5+3 sum=8 Again sum+=b[4] sum=sum+b[4] sum=8+7 sum=15
2nd Jun 2020, 8:16 AM
Abhay
Abhay - avatar
+ 1
Терещенко Дмитрий The code will be public class array{ public static void main(String args[]) { int [] b = {5, 6, 3, 8, 7} int sum = 0; for (int i = 0; i < 5; i ++) { if (i % 2 == 0){ continue; } sum += b[i]; } System.out.print(sum); } } The logic here is if the i th elementof the array is an even number then it skips the current iteration and proceeds to next but if it is a odd number it adds it to sum variable. So output=5+3+7=15
2nd Jun 2020, 8:16 AM
Souptik Nath
Souptik Nath - avatar