Overview:
Before starting this article, I will give you the general overview of this article. This Article included Array Definition and Why we use an array? Moreover, I will show the Demonstration for the Insertion of elements in a specific index. and write the logic for How to insert an element at a specific index? Furthermore, I will write code for C program to insert an element in an array. After all, I will show you the work of this program with the output as the conclusion.
Table of contents:
- What is an Array?
- What is a index of an Array?
- Why we use array in comparison to many variables?
- Demonstration for Insertion of element in a specific index
- How to insert an element at specific index?
- C program to insert an element in an array
- Conclusion
What is an Array?
An array is a container for the collection of items that stores these items at contiguous memory locations.
What is an index of an Array?
The index of an array is basically a pointer that is used to indicate which element in the array will be used.
Why do we use an array in comparison to many variables?
The array is a time-saving container in programming that saves time and memory storage when we write a program. Suppose, You want to store 100 numbers in memory than you will declare 100 specific variables to store it but it is a very time-consuming and lengthy process that increases the lines of code. Therefore, We will store these 100 numbers in a single variable known as an array that continuously stores it. Suppose, You want to save 1, 2, and 3 into memory.
The traditional method to store it is: int a=1; int b=2; int c=3; The alternative way to store it is as follows: int arr[3]= {1,2,3};
Demonstration for Insertion of element in a specific index.
How to insert an element at specific index?
- Step 1: First get the element to be inserted, say x
- Step 2: Then get the position at which this element is to be inserted, say pos
- Step 3: Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos.
- Step 4: Insert the element x now at the position pos, as this is now empty.Take a variable and store a year into it as integer.
C program to check leap year
#include <stdio.h> int main() { int arr[100] = { 0 }; int i, x, pos, n = 10; // initial array of size 10 for (i = 0; i < 10; i++) arr[i] = i + 1; // print the original array for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); /*element to be inserted x = 50; position at which element is to be inserted pos = 5; increase the size by 1 n++; then shift elements forward*/ for (i = n-1; i >= pos; i--) arr[i] = arr[i - 1]; // insert x at pos arr[pos - 1] = x; // print the updated array for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); return 0; }
Conclusion:
This Program insert 50 at 4th index to the given array.