How to define an array and assign values in C language?
In the C language, you can define an array and assign values to it using the following method:
- Define an array and assign values to each element in sequence.
int arr[5]; // 定义一个包含5个整数的数组
arr[0] = 1; // 给数组的第一个元素赋值
arr[1] = 2; // 给数组的第二个元素赋值
arr[2] = 3; // 给数组的第三个元素赋值
arr[3] = 4; // 给数组的第四个元素赋值
arr[4] = 5; // 给数组的第五个元素赋值
- Assign values while defining an array.
int arr[5] = {1, 2, 3, 4, 5}; // 定义一个包含5个整数的数组,并给每个元素赋初值
- Assign values using a loop structure.
int arr[5];
int i;
for (i = 0; i < 5; i++) {
arr[i] = i + 1;
}
The above are some common ways to define and assign arrays, choose the appropriate method based on the specific situation.