C Program to Insert Number in Given Position in Array

Questions: Write a program in C to read an array containing n elements. Also read position and a number then insert this number to the given position.

Inserting Element in Array C Program


#include<stdio.h>

int main()
{
 int a[100], i, n, pos, num;

 printf("Enter n:\n");
 scanf("%d", &n);
 /* Reading array */
 printf("Enter numbers:\n");
 for(i=0;i< n;i++)
 {
  printf("a[%d]=",i);
  scanf("%d", &a[i]);
 }
 /* Displaying original array */
 printf("Given array is:\n");
 for(i=0;i< n;i++)
 {
  printf("%d\t",a[i]);
 }
 /* Reading number and position */
 printf("\nEnter number to be inserted:\n");
 scanf("%d", &num);
 printf("Enter position to insert:\n");
 scanf("%d", &pos);
 /* Insertion */
 for(i=n;i>=pos;i--)
 {
  a[i] = a[i-1];
 }
 a[pos-1] = num;
 
/* Displaying final array */
 printf("Array after insertion is:\n");
 for(i=0;i<=n;i++)
 {
  printf("%d\t",a[i]);
 }

 return 0;
}