在数组的指定位置插入元素的 C 语言程序


2022 年 2 月 19 日, Learn eTutorial
1800

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

数组在 C 语言中如何工作?

在这个 C 语言示例中,我们将讨论在数组的指定位置插入元素的方法。我们通常知道数组以从位置 1n 的顺序添加元素。在这个 C 语言程序中,我们首先从用户那里接收元素的数量和元素。将输入添加到数组中;我们需要将数组按升序排序,以便将元素添加到正确的位置。

如何排序并向数组中插入元素?

通过使用外部和内部 for 循环嵌套循环),我们对数组中的元素进行排序。现在我们从用户那里接收关键元素,将其插入到已排序的数组中。检查关键元素是否小于数组中的第一个元素,如果是,则将关键元素添加到第一个位置。如果不是,则设置“m = n - pos + 1”,并使用 for 循环,直到“m”,并在循环内部应用“x[n-i+2] = x[n-i+1]”以获得添加 key x[pos] = key 的位置。显示带有正确位置的关键元素的数组。

此程序的逻辑是声明一个数组并读取元素。然后,我们使用 for 循环对数组中的数字进行排序。然后显示排序后的列表。最后,我们将检查插入给定元素的位置,并将该元素放入该位置并显示数组。

算法

步骤1:包含头文件以使用C语言程序中的内置函数。

步骤 2: 声明数组 x[10] 和一些整数变量 I、j、n、m、Keypos

步骤 3: 接受数字元素到 'n' 中。

步骤 4: 使用 For 循环将元素读取到数组 x[i] 中。

步骤 5: 使用 for 循环显示数组元素。

步骤 6: 使用内部 for 循环对数组进行排序。

步骤 7: 然后使用 for 循环将排序后的数组显示为 x[i]

步骤 8: 将数字 t 读取到变量 Key 中。

步骤 9: 使用 for 循环检查 key。

步骤 10: 将 'i' 增加 1 并执行步骤 9。

步骤 11: m = n - pos + 1

步骤 12: 使用条件 'i <= m' 的 for 循环执行步骤 13。

步骤 13:  x[n-i+2] = x[n-i+1]

步骤 14: 然后将数字放置在位置 x[pos] = key

步骤 15: 然后使用 for 循环将最终列表显示为 x[i[]

C 语言源代码

                                          #include <stdio.h>

void main()
{
  int x[10];
  int i, j, n, m, temp, key, pos;
  printf("Enter how many elements\n"); /* gets the elements */
  scanf("%d", &n);
  printf("Enter the elements\n");
    for (i = 0; i < n; i++)
        {
            scanf("%ld", & x[i]);
            fflush(stdin);
        }
  printf("Input array elements are\n");
  for (i = 0; i < n; i++)
  {
    printf("%d\n", x[i]);
  }

  for (i = 0; i < n; i++)
  {
    for (j = i + 1; j < n; j++) /* sort the array to add the key number in correct position */
    {
      if (x[i] > x[j])
      {
        temp = x[i];
        x[i] = x[j];
        x[j] = temp;
      }
    }
  }
  printf("Sorted list is\n");
   for (i = 0; i < n; i++)
    {
        printf("%d\n", x[i]);
    }
  printf("Enter the element to be inserted \n");
    scanf("%d", & key);        
  for (i = 0; i < n; i++)
  {
    if (key < x[i]) /* checking key is less than the first element of array */
    {
      pos = i;
      break;
    }
  }
  m = n - pos + 1;
  for (i = 0; i <= m; i++)
  {
    x[n - i + 2] = x[n - i + 1]; /* add the key number in the correct position */
  }
  x[pos] = key;
  printf("Final list is\n");
  for (i = 0; i < n + 1; i++)
  {
    printf("%d\n", x[i]); /* display the output array with the key number added  */
  }
} /* End of main() */
                                      

输出

Enter how many elements

5

Enter the elements

2

14

67

83

29

Input array elements are

2

14

67

83

29

Sorted list is

2

14

29

67

83

Enter the element to be inserted

34

Final list is

2

14

29

34

67

83