Home > Backend Development > C++ > Insert elements into array using C language

Insert elements into array using C language

王林
Release: 2023-08-28 12:09:06
forward
2440 people have browsed it

Insert elements into array using C language

We can insert elements at any position, which means we can insert at the beginning, middle, last or anywhere in the array.

After inserting an element into the array, the position or index position increases, but it does not mean that the size of the array increases.

The logic of inserting elements is

  • Input the size of the array

  • Input the element to be inserted position

  • Next enter the number you want to insert at that position

for(i=size-1;i>=pos-1;i--)
   student[i+1]=student[i];
   student[pos-1]= value;
Copy after login

The final array should be printed using a for loop.

Program

Live demonstration

#include<stdio.h>
int main(){
   int student[40],pos,i,size,value;
   printf("enter no of elements in array of students:");
   scanf("%d",&size);
   printf("enter %d elements are:</p><p>",size);
   for(i=0;i<size;i++)
      scanf("%d",&student[i]);
   printf("enter the position where you want to insert the element:");
   scanf("%d",&pos);
   printf("enter the value into that poition:");
   scanf("%d",&value);
   for(i=size-1;i>=pos-1;i--)
      student[i+1]=student[i];
   student[pos-1]= value;
   printf("final array after inserting the value is</p><p>");
   for(i=0;i<=size;i++)
      printf("%d</p><p>",student[i]);
   return 0;
}
Copy after login

Output

enter no of elements in array of students:6
enter 6 elements are:
12
23
34
45
56
67
enter the position where you want to insert the element:3
enter the value into that poition:48
final array after inserting the value is
12
23
48
34
45
56
67
Copy after login

The above is the detailed content of Insert elements into array using C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template