How to use scanf to assign values to an array in C language?
In C language, the scanf function can be used to assign values to an array. The specific steps are as follows:
- Declare an array.
- Use the scanf function to read the input values and assign them to each element of the array.
Here is an example code:
#include <stdio.h>
#define SIZE 5
int main() {
int arr[SIZE];
int i;
printf("请输入%d个整数:\n", SIZE);
for (i = 0; i < SIZE; i++) {
scanf("%d", &arr[i]);
}
printf("数组的值为:");
for (i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In the example code above, we start by declaring an integer array called arr with a size of 5. Then, we use a for loop and the scanf function to read values inputted by the user and assign them to each element of the array. Finally, we use another for loop to iterate through the array and print out its values.