在C ++中使用一个默认值初始化普通数组
整个数组可以非常简单地初始化为零。如下所示。
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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿