how to

数组

May 27, 2025
notesjulyfun工作kedaya
3 Minutes
571 Words

C++数组基础知识用法表格

操作代码示例说明
声明数组int a[5];创建一个长度为5的整型数组,未初始化。
初始化数组int b[3] = {1, 2, 3};声明时直接赋值,长度可省略:int b[] = {1, 2, 3};
访问元素cout << b[0];输出下标为0的元素(第一个元素,值为1)。
修改元素b[1] = 5;将下标为1的元素改为5。
遍历数组(for循环)for(int i=0; i<3; i++) cout << b[i];输出所有元素,注意下标从0开始到长度-1

应用题及数组写法

题目1:输入5个数,输出它们的和

1
#include <iostream>
2
using namespace std;
3
4
int main() {
5
int a[5], sum = 0;
6
// 输入
7
for(int i=0; i<5; i++) {
8
cin >> a[i];
9
sum += a[i]; // 累加
10
}
11
// 输出
12
cout << "Sum: " << sum;
13
return 0;
14
}

题目2:输出数组中的最大值

1
#include <iostream>
2
using namespace std;
3
4
int main() {
5
int a[5] = {3, 9, 2, 7, 5};
6
int max = a[0]; // 假设第一个是最大值
7
for(int i=1; i<5; i++) {
8
if(a[i] > max) max = a[i]; // 更新最大值
9
}
10
cout << "Max: " << max;
11
return 0;
12
}

题目3:逆序输出数组

1
#include <iostream>
2
using namespace std;
3
4
int main() {
5
int a[] = {1, 2, 3, 4, 5};
6
for(int i=4; i>=0; i--) { // 下标从大到小
7
cout << a[i] << " ";
8
}
9
return 0;
10
}

题目4:统计数组中某个数的出现次数

1
#include <iostream>
2
using namespace std;
3
4
int main() {
5
int a[6] = {2, 3, 2, 5, 2, 1};
6
int target = 2, count = 0;
7
for(int i=0; i<6; i++) {
8
if(a[i] == target) count++;
9
}
10
cout << "Count of " << target << ": " << count;
11
return 0;
12
}

题目5:数组元素翻倍(修改原数组)

1
#include <iostream>
2
using namespace std;
3
4
int main() {
5
int a[4] = {1, 2, 3, 4};
6
for(int i=0; i<4; i++) {
7
a[i] *= 2; // 每个元素乘2
8
}
9
// 输出结果
10
for(int i=0; i<4; i++) {
11
cout << a[i] << " ";
12
}
13
return 0;
14
}

关键提示

  1. 下标从0开始a[0]是第一个元素,a[n-1]是最后一个。
  2. 越界检查:避免访问a[-1]a[n],可能导致程序崩溃。
  3. 初始化习惯:局部数组未初始化时值是随机的,建议显式赋值(如int a[5] = {0};)。

通过这些例题,学生可以掌握数组的声明、遍历、修改和基本应用。后续可逐步过渡到二维数组或字符串(字符数组)。

Article title:数组
Article author:Julyfun
Release time:May 27, 2025
Copyright 2025
Sitemap