C Program to insert an Element in an Array

In this tutorial, i am going to show you how to add or insert elements in an array with the help of for and while loop in c programs.

All C Programs to insert an Element in an Array

  • C Program to insert an Element in an Array using For Loop
  • C Program to insert an Element in an Array using While Loop

C Program to insert an Element in an Array using For Loop

#include <stdio.h>
 
int main()
{
  int Array[10], Position, i, Number, Value;
 
  printf("\nPlease Enter Number of elements in an array\n");
  scanf("%d", &Number);
 
  printf("\nPlease Enter %d elements of an Array \n", Number);
  for (i = 0; i < Number; i++)
   {
     scanf("%d", &Array[i]);
   }     
 
  printf("\nPlease Enter the location of a Element you want to insert\n");
  scanf("%d", &Position);
 
  printf("\nPlease Enter the value of an Array Emenent to insert\n");
  scanf("%d", &Value);
 
  for (i = Number - 1; i >= Position - 1; i--)
   {
	     Array[i+1] = Array[i];
   }
  Array[Position-1] = Value;
  
 printf("\n Final Array after Inserting an  Elemnt is:\n");
 for (i = 0; i <= Number; i++)
  {
 	printf("%d\t", Array[i]);
  }     
 
 return 0;
}

The result of the above c program; as follows:

Please Enter Number of elements in an array
5
Please Enter 5 elements of an Array 
1 2 3 4 5
Please Enter the location of a Element you want to insert
5
Please Enter the value of an Array Emenent to insert
10
Final Array after Inserting an  Elemnt is:
1	2	3	4	10	5	

C Program to insert an Element in an Array using While Loop

#include <stdio.h>
 
int main()
{
  int Array[10], Position, i, Number, Value;
 
  printf("\nPlease Enter Number of elements\n");
  scanf("%d", &Number);
 
  printf("\nPlease Enter %d elements \n", Number);
  for (i = 0; i < Number; i++)
   {
     scanf("%d", &Array[i]);
   }     
 
  printf("\nPlease Enter the location of a Element you want to insert\n");
  scanf("%d", &Position);
 
  printf("\nPlease Enter the value to insert\n");
  scanf("%d", &Value);
 
  i = Number - 1;
  while(i >= Position - 1)
   {
	 Array[i+1] = Array[i];
	 i--;
   }
 Array[Position-1] = Value;
  
 printf("\n Final after Inserting an  Element is:\n");
 for (i = 0; i <= Number; i++)
  {
 	printf("%d\t", Array[i]);
  }     
 
 return 0;
}

The result of the above c program; as follows:

Please Enter Number of elements
5
Please Enter 5 elements 
1 2 3 4 5
Please Enter the location of a Element you want to insert
6
Please Enter the value to insert
45
Final after Inserting an  Element is:
1	2	3	4	5	45	

Be First to Comment

Leave a Reply

Your email address will not be published.