How to assign values to arrays in the C language?
In the C language, there are two methods to assign values to an array:
- Assign values one by one: assigning values to each element of the array through a loop.
#include <stdio.h>
int main() {
int arr[5];
int i;
for (i = 0; i < 5; i++) {
arr[i] = i + 1;
}
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The output is:
1 2 3 4 5
- Use curly braces initialization: when declaring an array, use curly braces to initialize the array’s elements.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The output is:
1 2 3 4 5