How to use scanf in C language to input arrays?

In C language, you can use the scanf function to input an array. Here is an example:

#include <stdio.h>

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

    int arr[n];
    printf("请输入数组的元素:");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("数组的元素为:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In the example above, first, we use the scanf function to input the size of the array n, then we define an integer array arr of size n. Next, we use a for loop and the scanf function to input each element of the array one by one. Finally, we use a for loop to print the elements of the array.

Please note that the format specifiers in the scanf function should match the type of variables being inputted, such as %d for integers. If inputting other types of data, you will need to adjust the format specifiers accordingly.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds