一维数组名称的用途:
1. 可以统计整个数组在内存中的长度
2. 可以获取数组在内存中的首地址
注意:数组名是常量,不可以赋值
总结1:直接打印数组名,可以查看数组所占内存的首地址
总结2:对数组名进行sizeof,可以获取整个数组占内存空间的大小
数组中元素的个数=sizeof(数组)/sizeof(数组[0]);
在一个数组中记录了五只小猪的体重,如:int arr[5] = {300,350,200,400,250};
找出并打印最重的大猪体重。
#include<iostream>
using namespace std;
int main()
{
int arr[5] = { 300,350,200,400,250 };
int max = 0;
for (int i = 0; i < 5; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
cout << "最重的猪是:" << max << endl;
system("pause");
return 0;
}
案例2:请声明一个5个元素的数组,并且将元素逆置.
#include<iostream>
using namespace std;
int main()
{
int start = 0;
int arr[] = { 1,3,2,5,4 };
int end = sizeof(arr) / sizeof(arr[0]) - 1;
int temp = 0;
if (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++; end--;
}
cout << "逆置后 的数组" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
案例3:冒泡排序
1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2. 对每一对相邻元素做同样的工作,执行完毕后,找到第一个最大值。
3. 重复以上的步骤,每次比较次数-1,直到不需要比较
4.总的排序轮数=元素个数-1
5.每轮对比的次数=元素个数-排序轮数-1
int main() {
int arr[9] = { 4,2,8,0,5,7,1,3,9 };
for (int i = 0; i < 9 - 1; i++)
{
for (int j = 0; j < 9 - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < 9; i++)
{
cout << arr[i] << endl;
}
system("pause");
return 0;
}