Because we want to specify the length of the array, we will first define a macro called max and initialize it to a value of 100. I have defined the value of max as 100 because I assume that I will not need to enter more than 100 values in an array, but it can be any value as desired. An array, p, is defined of size max elements. You will be prompted to specify the length of the array. Let's specify the length of the array as 5. We will assign the value 5 to the variable n. Using a for loop, you will be asked to enter the elements of the array.
Let's say you enter the values in the array, as shown in Figure 1.1 given earlier:
In the preceding diagram, the numbers, 0, 1, 2, and so on are known as index or subscript and are used for assigning and retrieving values from an array. Next, you will be asked to specify the position in the array where the new value has to be inserted. Suppose, you enter 3, which is assigned to the variable k. This means that you want to insert a new value at location 3 in the array.
Because the arrays in C are zero-based, position 3 means that you want to insert a new value at index location 2, which is p[2]. Hence, the position entered in k is decremented by 1.
To create space for the new element at index location p[2], all the elements are shifted one position down. This means that the element at p[4] is moved to index location p[5], the one at p[3] is moved to p[4], and the element at p[2] is moved to p[3], as follows:
Once the element from the target index location is safely copied to the next location, you will be asked to enter the new value. Suppose you enter the new value as 99; that value will be inserted at index location p[2], as shown in Figure 1.2, given earlier:
Let’s use GCC to compile the insertintoarray.c program, as shown in this statement:
D:\CBook>gcc insertintoarray.c -o insertintoarray
Now, let’s run the generated executable file, insertintoarray.exe, to see the program output:
D:\CBook>./insertintoarray
Enter length of array:5
Enter 5 elements of array
10
20
30
40
50
The array is:
10
20
30
40
50
Enter target position to insert:3
Enter the value to insert:99
Array after insertion of element:
10
20
99
30
40
50
Voilà! We've successfully inserted an element in an array.