+ 1

From Where does the last 5 come?

#include <iostream> using namespace std; int main() { int arr[]={11,17,15,15,85}; for(int i=0;i<=5;i++) { cout<< arr[i] << endl ; } return 0; } /* output 11 17 15 15 15 85 5 */ /* From Where does the last 5 come? */

26th Jan 2017, 9:53 PM
Sayem Mohammad
Sayem Mohammad - avatar
4 Answers
+ 7
Your array has 5 elements which have numbers 0 to 4, but in for condition there is i<=5, so it processes elements 0 to 5. Since the 5th element of the array does not exist, the program shows the content of the byte in ram which is five bytes right from the first byte of array. Actually, the program must raise runtime error, but c++ is always unpredictable.
26th Jan 2017, 10:17 PM
ŠŠ½Ń‚Š¾Š½ ŠžŠ±Š¾Š¶ŠøŠ½
ŠŠ½Ń‚Š¾Š½ ŠžŠ±Š¾Š¶ŠøŠ½ - avatar
+ 6
Replace <= with < and your program should run fine. Ahtoh (?) has explained the reason behind this occurrence, it's always good to know that arrays may store stray values so take heed.
27th Jan 2017, 1:27 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
thank you
27th Jan 2017, 4:22 AM
Sayem Mohammad
Sayem Mohammad - avatar
0
remove 'greater than or equal to' to' greater than'
5th Feb 2017, 11:25 AM
Ron Mathew Jacob
Ron Mathew Jacob - avatar