Home / Programs / C Program to Insert an element in an Array
Programming Example

C Program to Insert an element in an Array

👁 23,565 Views
💻 Practical Program
📘 Step by Step Learning
This C Program will Insert an element in an Array. It will take a new element and a location where we want to insert that new element. After the execution of this program, the new element will get its right position

Program Code

 /*
C Program to Insert an element in an Array
 Author: atnyla Developer
 */

  
#include<stdio.h>
 
int main() {
   int arr[30], element, num, i, location;
 
   printf("\nEnter no of elements :");
   scanf("%d", &num);
 
   for (i = 0; i < num; i++) {
      scanf("%d", &arr[i]);
   }
 
   printf("\nEnter the element to be inserted :");
   scanf("%d", &element);
 
   printf("\nEnter the location");
   scanf("%d", &location);
 
   //Create space at the specified location
   for (i = num; i >= location; i--) {
      arr[i] = arr[i - 1];
   }
 
   num++;
   arr[location - 1] = element;
 
   //Print out the result of insertion
   for (i = 0; i < num; i++)
      printf("  %d", arr[i]);
 
   return (0);
}

Output

Enter no of elements :5
1
2
3
4
5

Enter the element to be inserted :9

Enter the location2
  1  9  2  3  4  5 

Explanation

To solve this problem of the array, we just take a new element which we want to insert in the array and the location where we want to insert that element as a input. To insert that element we have to create a new space inside the array for that we shifted all the elements to its right position up to that location. which will give you a new space inside the array. now on that free position, you can easily insert that element,

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.