ホームページ  >  記事  >  バックエンド開発  >  C言語を使用して配列に要素を挿入する

C言語を使用して配列に要素を挿入する

王林
王林転載
2023-08-28 12:09:062321ブラウズ

C言語を使用して配列に要素を挿入する

要素は任意の位置に挿入できます。つまり、配列の先頭、中間、最後、または任意の場所に要素を挿入できます。

配列に要素を挿入すると、位置またはインデックス位置が増加しますが、それは配列のサイズが増加することを意味するわけではありません。

要素を挿入するロジックは次のとおりです

  • 配列のサイズを入力します

  • 入力挿入する要素の位置

  • 次に、その位置に挿入する番号を入力します

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

最終的な配列は、 forループ。

プログラム

ライブデモンストレーション

#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;
}

出力

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

以上がC言語を使用して配列に要素を挿入するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。