C Program to insert an array element using pointers.


Problem

Write a C program to insert the elements into an array at runtime by the user and the result to be displayed on the screen after insertion. If the inserted element is greater than the size of an array, then, we need to display Invalid Input.

Solution

An array is used to hold the group of common elements under one name.

The array operations are as follows −

  • Insert
  • Delete
  • Search

Algorithm

Refer an algorithm to insert the elements into an array with the help of pointers.

Step 1: Declare and read the number of elements.

Step 2: Declare and read the array size at runtime.

Step 3: Input the array elements.

Step 4: Declare a pointer variable.

Step 5: Allocate the memory dynamically at runtime.

Step 6: Input the position, where an element should be inserted.

Step 7: Insert the new element at that position and of the elements to right are to be shifted by one position.

Example

Size of array is: 5

Array elements are as follows −

1 2 3 4 5

Insert new element: 9

At position: 4

The output is as follows −

After insertion the array elements are:
1 2 3 9 4 5

Example

Following is the C program to insert the elements into an array with the help of pointers −

 Live Demo

#include<stdio.h>
#include<stdlib.h>
void insert(int n1, int *a, int len, int ele){
   int i;
   printf("Array elements after insertion is:
");    for(i=0;i<len-1;i++){       printf("%d
",*(a+i));    }    printf("%d
",ele);    for(i=len-1;i<n1;i++){       printf("%d
",*(a+i));    } } int main(){    int *a,n1,i,len,ele;    printf("enter size of array elements:");    scanf("%d",&n1);    a=(int*)malloc(n1*sizeof(int));    printf("enter the elements:
");    for(i=0;i<n1;i++){       scanf("%d",a+i);    }    printf("enter the position where the element need to be insert:
");    scanf("%d",&len);    if(len<=n1){       printf("enter the new element that to be inserted:");       scanf("%d",&ele);       insert(n1,a,len,ele);    } else {       printf("Invalid Input");    }    return 0; }

Output

When the above program is executed, it produces the following output −

enter size of array elements:5
enter the elements:
1
3
5
7
2
enter the position where the element need to be insert:
5
enter the new element that to be inserted:9
Array elements after insertion are:
1
3
5
7
9
2

Updated on: 26-Mar-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements