整个数组可以非常简单地初始化为零。如下所示。
int arr[10] = {0};但是,使用上述方法无法将整个数组初始化为非零值。如下所示。
int arr[10] = {5};在上面的示例中,仅第一个元素将被初始化为5。所有其他元素将被初始化为0。
for循环可用于初始化一个默认值不为零的数组。如下所示。
for(i = 0; i<10; i++) {
arr[i] = 5;
}在上面的示例中,所有数组元素都初始化为5。
给出了演示以上所有示例的程序,如下所示。
#include <iostream>
using namespace std;
int main() {
int a[10] = {0};
int b[10] = {5};
int c[10];
for(int i = 0; i<10; i++) {
c[i] = 5;
}
cout<<"Elements of array a: ";
for(int i = 0; i<10; i++) {
cout<< a[i] <<" ";
}
cout<<"\n";
cout<<"Elements of array b: ";
for(int i = 0; i<10; i++) {
cout<< b[i] <<" ";
}
cout<<"\n";
cout<<"Elements of array c: ";
for(int i = 0; i<10; i++) {
cout<< c[i] <<" ";
}
cout<<"\n";
return 0;
}输出结果
上面程序的输出如下。
Elements of array a: 0 0 0 0 0 0 0 0 0 0 Elements of array b: 5 0 0 0 0 0 0 0 0 0 Elements of array c: 5 5 5 5 5 5 5 5 5 5