数组
一维数组
定义方式
数据类型 数组名[数组长度];数据类型 数组名 [数组长度] = {值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];
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};
for (int i
= 0; i
< 9; i
++)
{
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");
}