📜  C++数组

📅  最后修改于: 2020-09-25 04:45:06             🧑  作者: Mango

###### 在本教程中，我们将学习如何使用数组。我们将借助示例学习如何在C++编程中声明，初始化和访问数组元素。

``double grade[27];``

#### C++数组声明

``dataType arrayName[arraySize];``

``int x[6];``

#### C++数组中的访问元素

``````// syntax to access array elements
array[index];``````

### 几件事要记住：

#### C++数组初始化

``````// declare and initialize and array
int x[6] = {19, 10, 8, 17, 9, 15};``````

``````// declare and initialize an array
int x[] = {19, 10, 8, 17, 9, 15};``````

### 空成员的C++数组

``````// store only 3 elements in the array
int x[6] = {19, 10, 8};``````

#### 如何插入和打印数组元素？

``````int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9
mark[3] = 9;

// take input from the user
// store the value at third position
cin >> mark[2];

// take input from the user
// insert at ith position
cin >> mark[i-1];

// print first element of the array
cout << mark[0];

// print ith element of the array
cout >> mark[i-1];``````

#### 示例1：显示数组元素

``````#include
using namespace std;

int main() {
int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

//  Printing array elements
// using range based for loop
for (const int &n : numbers) {
cout << n << "  ";
}

cout << "\nThe numbers are: ";

//  Printing array elements
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << "  ";
}

return 0;
}``````

``````The numbers are: 7  5  6  12  35
The numbers are: 7  5  6  12  35``````

1. 使用`int n`只需在每次迭代期间将数组元素复制到变量`n`中。这不是高效的内存。

但是， `&n`使用数组元素的内存地址来访问其数据，而无需将其复制到新变量中。这样可以节省内存。

2. 我们只是在打印数组元素，而不修改它们。因此，我们使用`const`以免意外更改数组的值。

#### 示例2：从用户那里获取输入并将其存储在数组中

``````#include
using namespace std;

int main() {
int numbers[5];

cout << "Enter 5 numbers: " << endl;

//  store input from user to array
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}

cout << "The numbers are: ";

//  print array elements
for (int n = 0; n < 5; ++n) {
cout << numbers[n] << "  ";
}

return 0;
}``````

``````Enter 5 numbers:
11
12
13
14
15
The numbers are: 11  12  13  14  15``````

#### 示例3：使用for循环显示数组元素的总和和平均值

``````#include
using namespace std;

int main() {

// initialize an array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;

cout << "The numbers are: ";

//  print array elements
// use of range-based for loop
for (const double &n : numbers) {
cout << n << "  ";

//  calculate the sum
sum += n;

// count the no. of array elements
++count;
}

// print the sum
cout << "\nTheir Sum = " << sum << endl;

// find the average
average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}``````

``````The numbers are: 7  5  6  12  35  27
Their Sum = 92
Their Average = 15.3333``````