數(shù)組
所謂數(shù)組伍掀,就是?個(gè)集合曼月,??存放了相同類型的數(shù)據(jù)元素
特點(diǎn)1:數(shù)組中的每個(gè)數(shù)據(jù)元素都是相同的數(shù)據(jù)類型
特點(diǎn)2:數(shù)組是由連續(xù)的內(nèi)存位置組成的
?維數(shù)組
定義方式:
1. 數(shù)據(jù)類型 數(shù)組名[數(shù)組長度];
2. 數(shù)據(jù)類型 數(shù)組名[數(shù)組長度] = {值1, 值2, ...}
3. 數(shù)據(jù)類型 數(shù)組名[] = {值1, 值2, ...}
```c
#include <iostream>
using namespace std;
int main(){
int a = 10;
int b;
cout<< b <<endl;
// 數(shù)組
// 1. 數(shù)據(jù)類型 數(shù)組名[數(shù)組長度];
int scores[10];
// 2. 數(shù)據(jù)類型 數(shù)組名[數(shù)組長度] = {值1, 值2, ...}
int arr1[3] = {11,22, 33};
// 3. 數(shù)據(jù)類型 數(shù)組名[] = {值1, 值2, ...}
int arr2[] = {11,22, 33, 44};
// 訪問數(shù)組元素 索引訪問
cout<< arr1[0] <<endl;
cout<< "+====++=========================="<<endl;
// 將數(shù)組元素規(guī)律的操作,, 我們通常叫遍歷數(shù)組(一個(gè)一個(gè)取出)
//數(shù)據(jù)的修改
for (int i = 0; i < 10; ++i) {
cout<< scores[i]<<"\t";
}
cout<<endl;
cout<< "+====++=========================="<<endl;
for (int i = 0; i < 10; ++i) {
scores[i] = i*i;// 數(shù)組元素的修改
}
cout<<endl;
cout<< "+====++=========================="<<endl;
for (int i = 0; i < 10; ++i) {
// 數(shù)組沒有進(jìn)行初始化是一個(gè)不確定的值
cout<< scores[i]<<"\t";
}
cout<<endl;
cout<< arr1 <<endl;// 0x7ffedfeec934直接打印數(shù)組的名字不會(huì)顯示數(shù)組
// 元素而是數(shù)組元素的首地址(16進(jìn)制地址 0x)
}
?維數(shù)組數(shù)組名
?維數(shù)組名稱的?途:
可以統(tǒng)計(jì)整個(gè)數(shù)組在內(nèi)存中的?度
可以獲取數(shù)組在內(nèi)存中的?地址
#include <iostream>
using namespace std;
int main(){
int a = 100;
cout<<sizeof(int)<<endl;
cout<<sizeof(a)<<endl;
// 可以獲取數(shù)組在內(nèi)存中的?地址
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
cout<<sizeof(arr)<<endl; // 整個(gè)數(shù)組占40字節(jié)
cout<<sizeof(arr[0])<<endl; // 一個(gè)元素占的字節(jié)
cout<<sizeof(arr)/sizeof(arr[0])<<endl; //數(shù)組中元素的個(gè)數(shù)
for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i) {
cout<<arr[i]<<"\t";
}
}
數(shù)組的最大值
練習(xí):五只?豬稱體重 案例描述: 在?個(gè)數(shù)組中記錄了五只?豬的體重焰扳,如:int arr[5] = {300,350,200,400,250}; 找出并打印最重的?豬體重
int main(){
// 五只小豬稱重 誰最重
// 就是求數(shù)組中的最大值
int arr[6] = {300,350,200,400,250, 200};
int maxWeight = arr[0]; // 假設(shè)第一只豬最重
for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i) {
if (arr[i] > maxWeight)
maxWeight = arr[i]; // 更新最重的
}
cout << "maxWeight = " <<maxWeight <<endl;
}
數(shù)組元素逆置
案例描述:請(qǐng)聲明?個(gè)5個(gè)元素的數(shù)組辆琅,并且將元素逆置. (如原數(shù)組元素為:1,3,2,5,4;逆置后輸出結(jié)果為:4,5,2,3,1);