How to insert an element in an array at particular position?
C Language
In C , Array is a collection of similar types of item stored at continuous memory location. In this article I will show you how to insert an element in an array in C.
steps :
step 1 :- Take size of an array.
step 2 :- take three integer variable which is i , ele , loc.
i is used for 'for' loop , ele is used for inserted an element and location is used for which location you want to be inserted an element.
Let's Take an example of it :-
#include<stdio.h>
int main()
{
int arr[6] = {1,2,3,4,5,6};
int i , ele , loc;
printf("enter an element to be inserted :");
scanf("%d",&ele); // Read the element from user.
printf("enter location where you want to be inserted an element :");
scanf("%d",&loc); // Read the location from user.
for(i=0;i>=loc;i--)
{
arr[i+1] = arr[i];
}
arr[loc] = ele;
for(i=0;i<6+1;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}
Comments
Post a Comment