How to input n pieces of data in the C language?

One common method to input n data items is to use a loop statement.

  1. Firstly, define an array to store the input data. The size of the array can be set according to the requirements, but it should be able to hold at least n pieces of data.
  2. Use a loop statement to input n pieces of data. You can choose between a for loop or a while loop depending on the specific situation.
  3. In each iteration, use the scanf function to input data and store it in the corresponding position in the array.

Here is a sample code:

#include <stdio.h>

int main() {
    int n;
    printf("请输入数据的个数:");
    scanf("%d", &n);

    int nums[n];  // 定义一个大小为n的数组

    printf("请输入%d个数据:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &nums[i]);  // 输入数据并存储到数组中
    }

    printf("输入的%d个数据为:\n", n);
    for (int i = 0; i < n; i++) {
        printf("%d ", nums[i]);  // 输出已输入的数据
    }
    printf("\n");

    return 0;
}

The code above first takes the value of n as input, then loops n times to input data and store it in an array. Finally, it outputs the data that has been entered.

bannerAds