C程序输入一个由空格分隔的整数序列的数组

PHPz
PHPz 转载
2023-08-25 11:33:08 987浏览

C程序输入一个由空格分隔的整数序列的数组

问题陈述

编写一个C程序,以空格分隔的整数作为数组输入。

Sample Examples

输入

1 2 3 4 5

输出

‘Array elements are -’ 1, 2, 3, 4, 5

Explanation

的中文翻译为:

解释

输入包含5个以空格分隔的整数。

输入

99 76 87 54 23 56 878 967 34 34 23

输出

‘Array elements are -’ 99, 76, 87, 54, 23, 56, 878, 967, 34, 34, 23

Explanation

的中文翻译为:

解释

输入包含11个以空格分隔的整数。

方法一

在这种方法中,我们将把输入中的以空格分隔的整数存储在单维数组中。

算法

  • 步骤 1 − 创建一个特定长度的数组。在这里,我们创建了一个长度为100的数组。

  • 第二步 - 在输入框中,我们要求用户输入以空格分隔的元素。

  • 第三步 - 我们使用scanf()函数接受整数输入,并将其存储在数组的“current index”索引位置。

  • 第四步 - 我们继续接受输入,直到用户按下回车键或输入总共100个元素。

  • 第五步 - 遍历数组并打印所有元素。

Example

#include <stdio.h>
int main(){
   int currentIndex = 0;
   // Initialize an array
   int arr[100];
   printf("Enter maximum 100 numbers and stop\n");
   // Take input, and stop the loop if the user enters a new line or reaches 100 elements
   do{
      // store an array index
      scanf("%d", &arr[currentIndex++]);
   } while (getchar() != '\n' && currentIndex < 100);
   // change the size of the array equal to the number of elements entered.
   arr[currentIndex];
   // Print the array elements
   printf("Array elements are: ");
   for (int i = 0; i < currentIndex; i++) {
      printf("%d, ", arr[i]);
   }
   return 0;
}

输出

Enter maximum 100 numbers and stop
1 2 3 4 5 6 7 8
Array elements are: 1, 2, 3, 4, 5, 6, 7, 8,
  • 时间复杂度 - 从输入中取出N个元素的时间复杂度为O(N)。

  • 空间复杂度 - 在数组中存储N个元素的空间复杂度为O(N)。

方法2(将数组输入到二维数组中)

In this approach, we will take space separated integer values as input and store them in a 2D array. We can take space separated integers as input as we did in the first approach and manage array indexes to store elements in a 2D array.

算法

  • 步骤 1 − 创建一个 2D 数组。

  • 第二步 - 使用两个嵌套循环来管理2D数组的索引。

  • 第三步 - 要求用户通过空格分隔输入数组元素。

  • 第4步 − 从输入中获取元素,并将其存储在2D数组的特定索引位置。

  • 第5步 - 使用两个嵌套循环打印一个2D数组。

Example

#include <stdio.h>
int main(){
   int currentIndex = 0;
   //    taking input from 2d array
   int array[3][3];
   printf("Enter 9 values for 3x3 array : \n");
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         scanf("%d", &array[i][j]);
      }
   }
   printf("Array values are : \n");
   //    printing 2d array
   for (int i = 0; i < 3; i++)  {
      printf("\n");
      for (int j = 0; j < 3; j++) {
         printf("%d ", array[i][j]);
      }
   }
   return 0;
}

输出

Enter 9 values for 3x3 array : 
1 2 3 4 5 6 7 8 9
Array values are : 

1 2 3 
4 5 6 
7 8 9
  • 时间复杂度 - O(N*M),其中N是行的总数,M是列的总数。

  • 空间复杂度 − O(N*M)

结论

我们学会了将以空格分隔的整数作为输入,并将它们存储在数组中。此外,我们还学会了将以空格分隔的输入元素存储在多维数组中。用户可以从用户输入中以任何类型的以空格分隔的元素作为数组。

以上就是C程序输入一个由空格分隔的整数序列的数组的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除