C Programming language

adplus-dvertising
C - Insert value into array
Previous Home Next

How can we insert values in an Array?

The values in an array can be inserted in the following two manner :

  • Insertion at the end of the array.
  • Insertion at the specified location in the array.

Insertion at the end of the Array can be carried out very easily. As value has to be inserted at the end so we just need to traverse the whole array till the end and then inserted our desired value at the end by setting the value pointed by the last element of the array to the new node which we desired to insert.

A program to insert value at a specified location in the array :

To insert a value in an array  at a desired position firstly we will have to shift all the elements forward so as to accommodate the new element, then we  place the element at the required place.

#include <stdio.h>
#include<conio.h>
int i, len, num, num_pos; /* declared some global variables */
void main()
{
int arr[50];
clrscr();
add_element(arr, len, num, num_pos); /* calling the function to add an element in the array */
getch();
}
void add_element(int a[], len, num, num_pos)
{
printf("Enter the length of the array :");
scanf("\n%d", &len);
printf("\nEnter the array elements :");
scanf("\n%d",&a[i]);
printf("\nEnter the number you want to insert :");scanf("%d",&num);
printf("\nEnter the position of the number at you want to insert :");
scanf("%d", &num_pos);
--num_pos;
if(num_pos>len)/*checking whether insertion outside array*/ 
{
    printf("insertion outside the array");
}
else
{
     for(i=len; i>=num_pos; i--)
{
     a[i]=a[i+1];/* shifting all the elements backwards to create a space for new element */
}
a[num_pos]=num; len=len+1;
printf("\n After insertiion now the array is :");
for(i=0; i<len; i++)
{
     printf("%d", a[i]);/* printing the newly formed array */
}
}
}

Output : The output of the above program would something like this

Enter the length of the array : 5

Enter the array elements :

1

2

3

4

5

Enter the number you want to insert :7

Enter the position of the number at you want to insert : 3

After insertion now the array is :

1

2

7

3

4

5

Previous Home Next