Select Page

C program to insert an element

 

C programming to insert an element into an Array-In this topic we will explain that procedure of inserting new element or number into an array at specified position given by the user .

The following program source code is implemented using three unique manner

  •  for Loop
  • while Loop
  • do..while Loop

Follow the Algorithm

Step 1: Declare four variable size, insert, i, pos and an array named arr[50].

step 2: The size of array  an array will given by the user

step 3: Input Element  of an array will be given by the user as long as i<size

step 4: Enter element  to insert into an array

step 5: Enter position or index no to insert element 

step 6: initialize i=size;            

step 7:  loop will be performed as long as  i>pos

step 8: changing the position in following way

arr[i]=arr[i-1];

step 9: decrease the value of i and go to step 5 ;

step 10: insert the new element at specified position given by user

arr[pos]= insert;

step 11: Arrange new array in following way

initialize i=0

step 12:   loop will be performed as long as  i<size+1

step13:    Display element into an array

step 14: increase value of i and go to step 12

step 9: End 

 

Source Code using For Loop

void main()
{
int arr[50], size, insert, i, pos;
printf("Enter Array Size : ");
scanf("%d",&size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter element to be insert : ");
scanf("%d",&insert);
printf("At which position (Enter index number) ? ");
scanf("%d",&pos);
for(i=size; i>pos; i--)
{
arr[i]=arr[i-1];
}
arr[pos]=insert;
printf("Element inserted successfully..!!\n");
printf("Now the new array is : \n");
for(i=0; i<size+1; i++)
{
printf("%d\n",arr[i]);
}

}

 

OUTPUT

Source Code Using While Loop

 void main()
{
	int arr[50], size, insert, i, pos;
	printf("Enter Array Size : ");
	scanf("%d",&size);
	printf("Enter array elements : ");
	for(i=0; i<size; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter element to be insert : ");
scanf("%d",&insert);
printf("At which position (Enter index number) ? ");
scanf("%d",&pos);
for(i=size; i>pos; i--) { arr[i]=arr[i-1]; } arr[pos]=insert; printf("Element inserted successfully..!!\n"); printf("Now the new array is : \n"); for(i=0; i<size+1; i++) { printf("%d\n",arr[i]); } }  

Source Code using Do..While Loop

void main()
{
int arr[50], size, insert, i, pos;
printf("Enter Array Size : ");
scanf("%d",&size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
  {
     scanf("%d",&arr[i]);
  }
printf("Enter element to be insert : ");
scanf("%d",&insert);
printf("At which position (Enter index number) ? ");
scanf("%d",&pos);
for(i=size; i>pos; i--)
   {
    arr[i]=arr[i-1];
   }
 arr[pos]=insert;
printf("Element inserted successfully..!!\n");
printf("Now the new array is : \n");
for(i=0; i<size+1; i++)
  {
     printf("%d\n",arr[i]);
  }

}