C Program to insert an element into an array


This content was proof-read by Grammarly. You can Try Grammary for FREE

This post helps to insert an element into an array using the C programming language.

C Program to insert an element into an array

#include <stdio.h> 
  
int main() 
{ 
    int arr[100] = { 0 }; 
    int i, x, pos, n = 10; 
    for (i = 0; i < 10; i++) 
        arr[i] = i + 1;  
    for (i = 0; i < n; i++) 
        printf("%d ", arr[i]); 
    printf("\n");  
    x = 50; 
    pos = 5;  
    n++; 
  
    // shift elements forward 
    for (i = n; i >= pos; i--) 
        arr[i] = arr[i - 1];
        arr[pos - 1] = x; 
  
    // print the updated array 
    for (i = 0; i < n; i++) 
        printf("%d ", arr[i]); 
    printf("\n"); 
  
    return 0; 
} 

Output

Explanation

In this C program, we learn to insert an element in an array. So we first start with initializing variables to store the values of the inserted element in the following array. First, get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos.

	int arr[100] = { 0 }; 
    int i, x, pos, n = 10; 
    for (i = 0; i < 10; i++) 
        arr[i] = i + 1;  
    for (i = 0; i < n; i++) 
        printf("%d ", arr[i]); 
    printf("\n");  
    x = 50; 
    pos = 5;  
    n++; 

Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos. Insert the element x now at the position pos, as this is now empty.

	// shift elements forward 
    for (i = n; i >= pos; i--) 
        arr[i] = arr[i - 1];
        arr[pos - 1] = x; 

Now we advance considerably to print the inserted element in an array.

 	// print the updated array 
    for (i = 0; i < n; i++) 
        printf("%d ", arr[i]); 
    printf("\n"); 

We have now provided the fancied output.

%d bloggers like this: