Google

Program to insert a value in an array at a given position

Written on:August 20, 2012
Comments are closed

Insert a value at a given position in an array:

For inserting a value at a given position, the elements are shifted from the last element by one position to the right, and the element at the specified position is overwritten with the new value to be inserted.

/* Insertion at a position in an array */

#include <stdio.h>

#define MAX 10

int main(){
int arr[MAX],n,i,pos,val;
printf(“nEnter total numbers?”);
scanf(“%d”,&n);
for(i=0;i<n;i++){
printf(“nEnter number?”);
scanf(“%d”,&arr[i]);
}
printf(“nEnter the value to insert?”);
scanf(“%d”,&val);
printf(“nEnter the position where to insert?”);
scanf(“%d”,&pos);
for(i=n-1;i>=pos;i–)
arr[i+1] = arr[i];
arr[pos] = val;
printf(“nArray elements after insertion:”);
for(i=0;i<n+1;i++)
printf(“%dt”,arr[i]);
}

 

Sorry, the comment form is closed at this time.