数组元素
时间: 2023-07-03 09:19:27 浏览: 49
数组元素指的是数组中的一个个数据单元,每个元素都有自己的编号(或称下标)和值。在 C/C++ 语言中,数组的编号从 0 开始,依次递增。
例如,定义一个整型数组 `a`,其中有 5 个元素:
```c++
int a[5] = {1, 2, 3, 4, 5};
```
则数组 `a` 的元素如下所示:
| 下标 | 元素值 |
| ---- | ------ |
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 5 |
我们可以通过下标来访问数组中的元素,例如 `a[2]` 表示数组 `a` 中下标为 2 的元素,其值为 3。
相关问题
数组元素数目
要获取数组元素的数目,可以使用数组的 length 属性。例如,如果数组名为 arr,则可以使用 arr.length 获取该数组的元素数目。例如:
```javascript
const arr = [1, 2, 3, 4, 5];
console.log(arr.length); // 输出 5
```
在上面的例子中,数组 arr 包含了 5 个元素,所以 arr.length 的值为 5。注意,数组的下标是从 0 开始的,所以如果要访问最后一个元素,应该使用 arr[arr.length - 1]。
C语言用常规下标法、数组名作为指针访问数组元素、指针变量下标法访问数组元素、使用指针变量访问数组元素4种方法编写从键盘输入数组元素和显示数组元素。
以下是四种方法编写从键盘输入数组元素和显示数组元素的C语言代码:
1. 常规下标法:
```c
#include <stdio.h>
int main() {
int array[10];
int i;
// 从键盘输入数组元素
for (i = 0; i < 10; i++) {
printf("请输入第 %d 个元素:", i+1);
scanf("%d", &array[i]);
}
// 显示数组元素
printf("数组元素为:");
for (i = 0; i < 10; i++) {
printf("%d ", array[i]);
}
return 0;
}
```
2. 数组名作为指针访问数组元素:
```c
#include <stdio.h>
int main() {
int array[10];
int *ptr = array;
int i;
// 从键盘输入数组元素
for (i = 0; i < 10; i++) {
printf("请输入第 %d 个元素:", i+1);
scanf("%d", ptr);
ptr++;
}
// 显示数组元素
printf("数组元素为:");
ptr = array;
for (i = 0; i < 10; i++) {
printf("%d ", *ptr);
ptr++;
}
return 0;
}
```
3. 指针变量下标法访问数组元素:
```c
#include <stdio.h>
int main() {
int array[10];
int *ptr = array;
int i;
// 从键盘输入数组元素
for (i = 0; i < 10; i++) {
printf("请输入第 %d 个元素:", i+1);
scanf("%d", &ptr[i]);
}
// 显示数组元素
printf("数组元素为:");
for (i = 0; i < 10; i++) {
printf("%d ", ptr[i]);
}
return 0;
}
```
4. 使用指针变量访问数组元素:
```c
#include <stdio.h>
int main() {
int array[10];
int *ptr = array;
int i;
// 从键盘输入数组元素
for (i = 0; i < 10; i++) {
printf("请输入第 %d 个元素:", i+1);
scanf("%d", ptr);
ptr++;
}
// 显示数组元素
printf("数组元素为:");
ptr = array;
for (i = 0; i < 10; i++) {
printf("%d ", *ptr);
ptr++;
}
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)