+ 5

Arrays in for loop

Sololearn uses this code as an example: void printArray(int arr[], int size) { for(int x=0; x<size; x++) { cout <<arr[x]<< endl; } } int main() { int myArr[3]= {42, 33, 88}; printArray(myArr, 3); } Why is 'x <size' used and not 'x<=size'? Because it should only print two numbers with 'x <size'. Or is it refered to the Index Number of the array?

22nd Mar 2019, 6:12 AM
tobiasth2003
tobiasth2003 - avatar
4 Respostas
+ 9
Array indexes start from 0. For three elements, the indexes are 0, 1 and 2. The index 3 is not part of the array, and so should not be accessed. Accessing such indices can lead to undefined behaviour, segmentation faults and other unwanted events. The value at that index from the array, if the code was able to retrieve somehow, will probably be a garbage value not relevant for use.
22nd Mar 2019, 6:32 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
array index starts from0 here if size =n then array size will n-1
22nd Mar 2019, 10:31 AM
Kamaljit Kaur
Kamaljit Kaur - avatar
+ 2
Because last array element index is always array_length - 1.
22nd Mar 2019, 8:13 AM
Seb TheS
Seb TheS - avatar
0
Yes..i'm like web language programming
25th Mar 2019, 3:32 PM
Dean AJ
Dean AJ - avatar