C++自学笔记(数组)

    科技2022-08-19  122

    数组

    一维数组

    定义方式

    数据类型 数组名[数组长度];数据类型 数组名 [数组长度] = {值1,值2,…};数据类型 数组名[ ] = {值1,值2,…}; int arry1[3]; int arry2[3] = { 3,4,5}; int arry3[] = { 3,4,5,6,7};

    练习

    练习案例1

    在一个数组中记录五只小猪的体重,找出并打印出来最重的小猪 #include<string> #include<iostream> using namespace std; int main() { int arry[5] = {260,350,280,300,320}; int max = arry[0]; //初始化一个max int i = 0; //用于遍历数组 int j = 1; //用于记录第几只体重最大 for (; i < 5; i++) { if (max < arry[i]) { max = arry[i]; j = i + 1; } } cout << "第" << j << "只小猪最重:" << max << endl; system("pause"); }

    练习案例2

    定义五个元素的数组,并将元素逆置 #include<string> #include<iostream> using namespace std; int main() { int arry[5] = {13,15,17,19,21}; int tmp[5]; int j = 4; for (int i = 0; i < 5; i++) { tmp[j] = arry[i]; j -= 1; } cout << "{"; for (int i = 0; i < 5; i++) { cout << tmp[i] << ","; } cout << "}" << endl; system("pause"); }

    冒泡排序

    #include<string> #include<iostream> using namespace std; int main() { int a[10] = {3,6,2,7,8,1,4,9,5,0}; //外层循环:总共排序轮数 = 元素个数-1 for (int i = 0; i < 9; i++) { //内层循环:对比次数 = 元素个数-当前轮数-1 for (int j = 0; j < 9 - i - 1; j++) { //如果前面的数字大,则交换位置 if (a[j] > a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } for (int i = 0; i < 9; i++) { cout << a[i] << " "; } cout << endl; system("pause"); }

    二维数组

    定义方式

    数组类型 数组名[] [];数组类型 数组名[] [] = { {数据1,数据2 } , {数据3,数据4 } };

    练习

    考试成绩统计:三名同学的语数英三门成绩,并输出三名同学的总成绩 #include<string> #include<iostream> using namespace std; int main() { int score[3][3] = { {100,100,100},{90,50,100},{60,70,90} }; for (int i = 0; i < 3; i++) { int sum = 0; for (int j = 0; j < 3; j++) { sum+= score[i][j]; } cout << sum << endl; } system("pause"); }
    Processed: 0.009, SQL: 9