#include <iostream>
using namespace std;
void array_exercise() {
// 数组基础
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
cout << "整个数组所占内存空间:" << sizeof(arr) << endl;
cout << "每个数组所占内存空间:" << sizeof(arr[0]) << endl;
cout << "数组的个数为:" << sizeof(arr) / sizeof(arr[0]) << endl;
cout << "数组首地址为:" << arr << endl; // 16进制地址
cout << "数组首地址为:" << (int)arr << endl; // 10进制地址
cout << "数组第1个元素地址为:" << (int)&arr[0] << endl;
cout << "数组第1个元素地址为:" << (int)&arr[1] << endl;
// 数组求最大值
int arr_set[] = { 300,489,512,357,500 };
int length01 = sizeof(arr_set) / sizeof(arr_set[0]);
int max = 0;
for (int i = 0; i < length01; i++)
{
if (arr_set[i] > max) {
max = arr_set[i];
}
}
cout << "最大值为:" << max << endl;
// 数组互逆
int arr_A[] = { 1,2,3,4,5 };
int start = 0;
int length = sizeof(arr_A) / sizeof(arr_A[0]);
int end = length - 1;
int temp = 0;
cout << "数组互逆前:";
for (int i = 0; i < length; i++)
{
cout << arr_A[i] << ",";
}
cout << endl;
while (start < end) {
temp = arr_A[start];
arr_A[start] = arr_A[end];
arr_A[end] = temp;
start++;
end--;
}
cout << "数组互逆后:";
for (int i = 0; i < length; i++)
{
cout << arr_A[i] << ",";
}
cout << endl;
// 冒泡排序
int array_a[] = { 1,4,5,2,3,8,7,9,6 };
int len = sizeof(array_a) / sizeof(array_a[0]);
int temp02;
cout << "原始数组:";
for (int i = 0; i < len; i++)
{
cout << array_a[i] << ",";
}
cout << endl;
// 升序
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (array_a[j] > array_a[j + 1]) {// < 为降序 >为升序
temp02 = array_a[j];
array_a[j] = array_a[j + 1];
array_a[j + 1] = temp02;
}
}
}
cout << "升序数组:";
for (int i = 0; i < len; i++)
{
cout << array_a[i] << ",";
}
cout << endl;
// 降序
for (int i = 0; i < len - 1; i++)
{
for (int j = 0; j < len - 1 - i; j++)
{
if (array_a[j] < array_a[j + 1]) { // < 为降序 >为升序
temp02 = array_a[j];
array_a[j] = array_a[j + 1];
array_a[j + 1] = temp02;
}
}
}
cout << "降序数组:";
for (int i = 0; i < len; i++)
{
cout << array_a[i] << ",";
}
cout << endl;
}
25 C++ 数组练习
最新推荐文章于 2024-03-31 22:26:07 发布