大纲要求
•【1】数组定义,数组与数组下标的含义
•【1】数组的读入与输出
•【2】纯一维数组的综合运用
•【3】纯二维数组与多维数组的综合应用
为什么使用数组
int a, b, c, d;int a1, a2, a3, a4, a5, a6, a7....;int a[100]; //定义100个int类型a[0], a[1], a[2], a[3], a[4]...[0][1][2][3][4][5][6][7]...//连续地址空间存储的//静态数组,大小是静态固定的,上来就要告诉计算机,我需要100个连续的int空间//然后,我想用几个就用几个。但是,千万不能要超。//a[0] ... a[99],这些是100个,但不能用a[100],这是第101个//因为,a[101]这个位置,计算机可能存储了其他的东西,有可能是危险的东西(越界访问)
一维数组
#include <iostream>using namespace std;int a[10]; //全局变量,初始值默认是0int n;int main(){int b[10]; //局部变量,初始值是计算机随机给的cin >> n;for (int i = 0; i < n; i++) cin >> a[i];for (int i = 0; i < n; i++) cout << a[i] << ' ';cout << '\n';return 0;}
// 逐步养成下面的代码编写风格// 学习三个月以上的,需要强制转变自己的代码风格,无需多言#include <iostream>#include <cstdio>using namespace std;const int N = 1e5 + 10;int a[N], b[N];int n;int main(){cin >> n;for (int i = 0; i < n; i++) cin >> a[i];for (int i = 0; i < n; i++) cout << a[i] << ' ';puts("");return 0;}
int a[5] = {1, 2, 3, 4, 5};a[-1]; //这是不对的,下标不能是负数memset(a, 0, sizeof a); //把a[i]全部置成0
例题,与指定数字相同的数的个数
#include <bits/stdc++.h>using namespace std;int a[110];int n, k;int main(){cin >> n;for (int i = 0; i < n; i++) cin >> a[i];cin >> k;int cnt = 0;for (int i = 0; i < n; i++) if (a[i] == k)cnt++;cout << cnt << endl;return 0;}
例题,年龄与疾病
#include <bits/stdc++.h>using namespace std;int n;int a, b, c, d;int main(){cin >> n;for (int i = 0; i < n; i++){int x;cin >> x;if (x <= 18) a++;if (x >= 19 && x <= 35) b++;if (x >= 36 && x <= 60) c++;if (x >= 61) d++;}printf("%.2lf%%\n", 1.0 * a / n * 100);printf("%.2lf%%\n", 1.0 * b / n * 100);printf("%.2lf%%\n", 1.0 * c / n * 100);printf("%.2lf%%\n", 1.0 * d / n * 100);return 0;}
例题,校门外的树
// 原题// 用一个数组,来表示这一段马路// 一个一个点,就可以表示是否有树的状态了
例题,【例5.3】开关门
// 方法一,模拟// 方法二,数学
例题,直方图
// 认真读题,看来,我们要预处理出来fmax
二维数组
// 关键词:逐行逐列#include <iostream>using namespace std;const int N = 110;int a[N][N];int n, m; //n行m列int main(){cin >> n >> m;for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)cin >> a[i][j];//逐行逐列扫描for (int i = 0; i < n; i++){for (int j = 0; j < m; j++) cout << a[i][j] << ' ';puts("");}return 0;}
例题,矩阵加法
#include <bits/stdc++.h>using namespace std;int a[110][110];int main(){int n, m;cin >> n >> m;for (int i = 1; i <= n; i++)for (int j = 1; j <= m; j++)cin >> a[i][j];for (int i = 1; i <= n; i++)for (int j = 1; j <= m; j++){int x;cin >> x;a[i][j] += x;}for (int i = 1; i <= n; i++){for (int j = 1; j <= m; j++)cout << a[i][j] << ' ';puts("");}return 0;}
例题,图像旋转
// 观察,规律
空间复杂度



