int main () { int a[3] = {2,7,3}; for (int i=0; i<3; i++){ a[i]-=i; } cout<<a[i]; } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

int main () { int a[3] = {2,7,3}; for (int i=0; i<3; i++){ a[i]-=i; } cout<<a[i]; }

Can someone explain how the answer is 6?

3rd Aug 2016, 4:43 PM
Hakatek
6 Answers
+ 4
since i's scope is lost it should show error, but since you asked how 6,--- when first iteration is executed, i=0, the first number( a[0] ) 2 is deducted by 0, second iteration second number ( a[1])7 gets deducted by 1(i ), next iteration is not executed as i is greater than 2 now. hence now i=1 only hence prints second number a[1]
3rd Aug 2016, 5:20 PM
Praveen Jayakumar
Praveen Jayakumar - avatar
+ 1
This should actually throw an compilation error. The scope of i ends with the for loop and in the next statement, i is not a valid variable.
4th Aug 2016, 3:10 AM
Nick D.
Nick D. - avatar
0
Showing error😕
4th Aug 2016, 10:50 AM
Anjali B Prasad
Anjali B Prasad - avatar
0
That curly brace above cout should come after cout ryt???
5th Aug 2016, 6:00 AM
Anjali B Prasad
Anjali B Prasad - avatar
0
The answer is then 261
17th Aug 2016, 12:46 PM
Oumar sidibe
- 1
like it
3rd Aug 2016, 6:53 PM
wicky Waqar
wicky Waqar - avatar