Following is the code from www.tutorialspoint.com, where i am learning basics of algorithm & data structure. This tutorial code gives an ex. of insertion operation on array.
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
n = n + 1;
while( j >= k){
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
I understand the code that it adds new item at give value of k as index of array. And it runs fine without any error when compiled & runs. What confuses me is logic of line LA[j+1] = LA[j]
in while loop.
My understanding is that in c you have to declare the size of array. But in ex. code int LA[] = {1,3,5,7,8};
bracket [ ] is empty. So i am not sure if it's a fixed size or more elements can be added to array.
Now j
is given the value of n
which is 5(length of array). Array declaration has 5 element, and index of array is 0 to 4.
(On first iteration of while loop)So LA[j + 1]
is LA[5 + 1]
is LA[6]
. Now array has only 5 elements indexed 0 to 4. So according to me even after assuming that more element can be added to array, how can it assign value of LA[j]
which is 5 to LA[j + 1]
. it's saying LA[6] = LA[5] but there is nothing at index 5 as last index is 4.
I have tried to search on google but I am not sure what to search except the code or part of code. And searching with code wasn't helpful.
Please help me understand. Thank You.