Write a C Program to insert an item in an array at a specified index by moving other elements to the right

Admin

Write a C Program to insert an item in an array at a specified index by moving other elements to the right


#include<stdio.h>
#define SIZE 10
int main(void)
{
	int arr[SIZE];
	int i,item,index;
	printf("Enter elements of the array : \n");
	for(i=0; i<SIZE-1; i++) /*rightmost space in the array should be empty*/
			scanf("%d",&arr[i]);
	printf("Enter the item to be inserted : ");
	scanf("%d",&item);
	printf("Enter the index where item is to be inserted : ");
	scanf("%d",&index);

	for(i=SIZE-2; i>=index; i--)
		arr[i+1]=arr[i];    /*Shift elements to the right*/
	arr[i+1]=item;	    /*Insert item at the proper place*/

	for(i=0; i<SIZE; i++)
		printf("%d  ",arr[i]);
	printf("\n");
	return 0;
}
Output
11  12  13  14  15  16  17  18  19 
Enter the item to be inserted : 20
Enter the index where item is to be inserted : 9
11  12  13  14  15  16  17  18  19  20  

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.