c++ Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

c++ Array

Given the Array int a[4] = {2,3,5,7}; I want to output the last item by using cout << a[-1] . But the output is 1983713634. Why is that the case? Thanks

31st Dec 2017, 2:38 AM
linus_md
linus_md - avatar
4 Answers
+ 13
For an array of size 4, the valid indices are: 0,1,2,3 So, if you want to access the last element, use a[3] instead. -1 is invalid index, so it's printing garbage value.
31st Dec 2017, 2:41 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 7
As has been pointed out, C++ does not provide the feature of accessing the last element of the array via -1 array index, unlike how some other languages do.
31st Dec 2017, 3:54 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Indexing of an array starts from 0. in your program a[0]=2; a[1]=3; a[2]=5; a[3]=7; to print last item .use cout<<a[3]; since a[-1]; , does not exist. cout<<a[-1]; gives out garbage output.
31st Dec 2017, 2:43 AM
Mukul
Mukul - avatar
+ 3
We cannot directly access the last element in the array if u want the last element try this code cout<<a[(sizeof(a)/sizeof(a[0]))-1];
31st Dec 2017, 2:45 AM
NAGANDLA.LEELA PAVAN KUMAR
NAGANDLA.LEELA PAVAN KUMAR - avatar