用于分割数组并将第一部分添加到末尾的 C 程序


2022 年 12 月 13 日, Learn eTutorial
2460

什么是数组?

数组是数据项的集合,它们具有相同的数据类型,存储在连续的内存位置中,并通过一个共同的变量进行索引。一维数组是列表,二维数组是矩阵。

例如,int arr[20] 是一维数组,int mat[10][10] 是二维数组。这里我们给定一个数组,我们必须使用键值将其分割成两部分,然后将前半部分添加到后半部分的末尾。

如何在 C 程序中实现数组分割逻辑?

为此,我们从用户那里接受数组的值。现在我们接受用户想要分割的位置,并将该值保存在一个变量中。开始一个嵌套的 for 循环

  • 在外层循环中,我们必须循环直到需要分割数组的位置。将第一个数字添加到末尾。
  • 在内层循环中,将一个元素与其后面的元素交换。这意味着 a[j] 必须替换为 a[j+1]。这意味着将整个数组向左移动一个位置。

最后,显示结果。

算法

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

步骤 2: 声明整数变量 i, j, n, split_index 和数组 number[30]

步骤 3:n 的值读入变量 'n'。

步骤 4: 从用户那里读取数字,并使用 for 循环将其保存到 number[i] 中。

步骤 5: 将用户想要分割的位置读入变量 split_index

步骤 6: 使用条件为 i < split_indexfor 循环

步骤 7: number[n] = number[0]

步骤 8: 使用条件为 j < n 的另一个 for 循环

步骤 9: number[j] = number[j+1]

步骤 10:j 增加 1 并执行步骤 8。

步骤 11:i 增加 1 并执行步骤 6。

步骤 12: 使用 for 循环显示结果为 number[i]


为了分割数组,我们在 C 编程中使用以下概念,我们建议您学习这些概念以便更好地理解。

C 语言源代码

                                          #include <stdio.h>

void main()
{
  int number[30];
  int i, n, split_index, j;
  printf("Enter the value of n\n"); /* enter the value */
  scanf("%d", & n);
  printf("enter the numbers\n");
  for (i = 0; i < n; ++i)
    scanf("%d", & number[i]);
  printf("Enter the position of the element to split the array \n"); /* accept the position where user wants to split */
  scanf("%d", & split_index );
  for (i = 0; i < split_index ; ++i)
  {
    number[n] = number[0];
    for (j = 0; j < n; ++j)
    {
      number[j] = number[j + 1]; /* changing the position of the elements */
    }
  }

  printf("The resultant array is\n");
  for (i = 0; i < n; ++i)
  {
    printf("%d\n", number[i]);
  }

} /* End of main() */
                                      

输出

Enter the value of n
5

enter the numbers
30
10
40
50
60

Enter the position of the element to split the array
2

The resultant array is
40
50
60
30
10