Insert An Element In An Array And C Code - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Sunday, 10 March 2013

Insert An Element In An Array And C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to insert an element in the Front of an 1-D array. Let me explain you by this example:
Let we have an array Arr[10] having four elements initially  Arr[0] = 1, Arr[1] = 2, Arr[2] = 3, Arr[3] = 4 and you want to insert a number 59 at first location, that is, at Arr[0] = 59. So we have to move elements one step below so after insertion Arr 1] = 1 which was Arr[0] initially, and Arr 2] = 2, Arr 3] = 3 and Arr[4] = 4. Array insertion does not mean increasing its size i.e array will not be containing 11 elements, but instead inserting an element.

NOTE:- If you want to insert an element into a full Array, that is, all elements are already present in the array, then element will be inserted but the last element will be terminated. 


Here is the C Code for Inserting An Element In The Beginning Of An 1-D Array:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[100],n,num,i;
 clrscr();
 printf("Enter the number of elements in the Array: ");
 scanf("%d",&n);
 printf("\nEnter %d elements:\n\n",n);

 for(i=0 ; i<n ; i++)
 {
  printf(" Array[%d] = ",i);
  scanf("%d",&arr[i]);
 }
 
 printf("\nEnter the Number to be Inserted At the Front: ");
 scanf("%d",&num);
 
 printf("\nOld Array: ");  
 for(i = 0; i < n; i++)
 {
  printf("%4d", arr[i]);
 }
 
 for(i=n ; i>=0 ; i--)
 {
  arr[i+1] = arr[i];
 }
 arr[0] = num;
 n=n+1;
 
 printf("\n\nNew Array:");  
 for(i = 0; i < n; i+)
 {
  printf("%4d", arr[i]);
 }
 
 getch();
}


Output of Program:

Insert Element In Array C Code


Please Comment If You Liked This Post !!



Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: