C Program to insert element in array

Simple C program to insert element in array : To insert element at a particular position,first we have to shift element and then insert element. For example if array is arr[]={12,13,43,27}; then to insert element at position 1 then we have to shift array element towards right and then insert element at position 1.
 
/* C program to insert element in array */
#include<stdio.h>
int main()
{
 int arr[100],i,n,position,num;
 printf("Enter number of elements : ");
 scanf("%d",&n);
 printf("Enter %d array elements: \n",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 printf("Enter position at which you want to insert number: ");
 scanf("%d",&position);
 printf("Enter number: ");
 scanf("%d",&num);
 for(i=n;i>=position;i--)
 {
  arr[i]=arr[i-1];
 }
 arr[position-1]=num;
 printf("array is :\n");
 /* Now total elements in array is n+1 */
 for(i=0;i<n+1;i++)
 {
  printf("%d ",arr[i]);
 }
 return 0;
}
/* End of the program */
 

Another C program to insert element in array
 
/* C program to insert element in array */
#include<stdio.h>
int main()
{
 int arr[100],i,n,position,num,temp,temp1;
 printf("Enter number of elements : ");
 scanf("%d",&n);
 printf("Enter %d array elements: \n",n);
 for(i=0;i<n;i++)
 {
  scanf("%d",&arr[i]);
 }
 printf("Enter position at which you want to insert number: ");
 scanf("%d",&position);
 printf("Enter number: ");
 scanf("%d",&num);
 temp=arr[position-1];
 for(i=position;i<=n;i++)
 {
 // temp=arr[i-1];
  temp1=arr[i];
  arr[i]=temp;
  temp=temp1;
 
 }
 arr[position-1]=num;
 printf("array is :\n");
 /* Now total elements in array is n+1 */
 for(i=0;i<n+1;i++)
 {
  printf("%d ",arr[i]);
 }
 return 0;
}
/* End of the program */


Popular posts from this blog