Ads by ProfitSence
Close

Inserting an element in an array in C

Last Updated on Wednesday 5th Oct 2022

add element to array c

			
					#include<stdio.h>

#define max 100
void main() {
   int p[max], n, i, k, j;
   printf("Enter length of array:");
   scanf("%d", & n);
   printf("Enter the %d elements One by Onen", n);
   for (i = 0; i <= n - 1; i++)
      scanf("%d", & p[i]);
   printf("nThe array is:n");
   for (i = 0; i <= n - 1; i++)
      printf("%dn", p[i]);
   printf("nEnter the Position where to insert:");
   scanf("%d", & k);
   k--;
   for (j = n - 1; j >= k; j--)
      p[j + 1] = p[j];
   printf("nEnter the Value to insert:");
   scanf("%d", & p[k]);
   printf("nArray after insertion of element: n");
   for (i = 0; i <= n; i++)
      printf("%dn", p[i]);
}

			
	

c program to insert an element in an array at desired position

			
					Enter length of array:4
Enter the 4 elements One by One
11
22
33
44

The array is:
11
22
33
44

Enter the Position where to insert: 3
Enter the Value to insert: 99

Array after insertion of element:
11
22
99
33
44

			
	

Arrays in C are zero-based, position 3 means that you want to insert a new value at index location 2.

To create space for the new element at the specified index location, all the elements are shifted one position down