+ 6

My 1st C++ problem question

What is the output of this code? int b[ ]={1,4,2,7,3}; int sum=0; for(int i=0; i<5; i++){ if(i%2==0) sum += b[i]; } cout<<sum; My answer is 2 but the real answer is 6 ,why?🤔Thanks for your help.

3rd Mar 2018, 7:02 AM
Eros boulay
Eros boulay - avatar
4 Respostas
+ 5
It runs though the array, and adds each one to the total, but only when the index is even. So what it's adding is b[0], b[2], and b[4]. and the sum is equal to 1 + 2 + 3 = 6.
3rd Mar 2018, 7:08 AM
DaemonThread
DaemonThread - avatar
+ 5
Hi Alice... You've been asking some great questions to learn more about challenges. In case you weren't aware, you can show your appreciation for these great explanations by marking the best answer with a green checkmark. :)
7th Mar 2018, 7:14 AM
David Carroll
David Carroll - avatar
+ 4
@ David Caroll Yes,I executed your order😜
7th Mar 2018, 7:21 AM
Eros boulay
Eros boulay - avatar
+ 1
Oops...I thought we stopped when the index was even 😓 Thanks Thumb up
3rd Mar 2018, 7:16 AM
Eros boulay
Eros boulay - avatar