+ 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);
4 Respostas
+ 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
+ 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.
+ 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👍🏻❤️
+ 2
Ausgrindtube thanks bro. 👍🏻