+ 2

Why there isn't an error in this statement ( a[0-1]) ?

Here is the code ,assume all necessary libraries included: int main() { int a[5] = {1,2,3,4,5}; for (int i=0; i<5; i++) { a[i]= 2* a[i-1]; cout<<i; } return 0; }

10th May 2017, 1:09 PM
mohammad khalaf
mohammad khalaf - avatar
12 Answers
+ 7
compiler ignored error because it is a runtime exception
10th May 2017, 2:05 PM
NimWing Yuan
NimWing Yuan - avatar
+ 6
Start the for loop at 1 to fix. Then change a[0] however you wanted it to be.
10th May 2017, 2:38 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
i=0 a [i-1] = a [ -1] = error; a>=0
10th May 2017, 1:26 PM
NimWing Yuan
NimWing Yuan - avatar
+ 3
There is an error i.e. a [-1]
10th May 2017, 1:30 PM
Vishnu ks
Vishnu ks - avatar
+ 1
Because there is no a[-1]. Arrays starts at index 0. Try this instead : ... for (int i=1; i<5; i++) { a[i] = 2 * a[i-1]; cout << i; } ...
10th May 2017, 1:19 PM
Toky R.
Toky R. - avatar
+ 1
Thank you for your help , I appreciate it.
10th May 2017, 1:23 PM
mohammad khalaf
mohammad khalaf - avatar
+ 1
Sorry for disturbing you , but why this error is ignored by compiler ?
10th May 2017, 2:01 PM
mohammad khalaf
mohammad khalaf - avatar
0
no problem ;)
10th May 2017, 1:23 PM
Toky R.
Toky R. - avatar
0
I thought the same thing , but when i run this program the output is 01234.
10th May 2017, 1:30 PM
mohammad khalaf
mohammad khalaf - avatar
0
@mohammad, the output of this code (if you ignore the a[-1]) is 01234 because you wrote : ... for (int i = 0; i < 5; i++) { ... cout << i; } ...
10th May 2017, 1:33 PM
Toky R.
Toky R. - avatar
0
good question... :/
10th May 2017, 2:04 PM
Toky R.
Toky R. - avatar
0
@NimWing Yuan , thanks :)
10th May 2017, 2:10 PM
mohammad khalaf
mohammad khalaf - avatar