+ 2

Can someone explain me this code. It will be really help.

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

23rd Jan 2023, 2:21 AM
Bhagwat
Bhagwat - avatar
4 Answers
+ 5
Do dry run int[ ] b={5, 6, 3, 8, 7}; int sum = 0; for(int i=0; i<5; i++) { if(i%2==0){ sum += b[i]; } Inside if condition u have written i%2 ==0 so between 0<5 there r 0 ,2,4 are the number which are completely divisible by 2 Inside if body the sum will be of these 0 ,2 ,4 divisible index values 0th index value is 5. 0%2 ==0 1th index value 6 2nd index value 3 // 2%2==0 3rd value 8 4th value 7 // 4%2==0 0th index value+ 2nd index value+ 4th value 5 + 3 + 7
23rd Jan 2023, 5:46 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 7
What might help you is to put in some print statements. Find out what "i" is and which number in the array that corresponds to. Then, you'll get it.
23rd Jan 2023, 3:13 AM
Ausgrindtube
Ausgrindtube - avatar
+ 3
ASR Thank you so much. I was doing operations on the actual values and not on their index. The way you explained was really good. Thanks againšŸ‘šŸ»ā¤ļø
23rd Jan 2023, 5:58 AM
Bhagwat
Bhagwat - avatar
+ 2
Ausgrindtube thanks bro. šŸ‘šŸ»
23rd Jan 2023, 5:59 AM
Bhagwat
Bhagwat - avatar