Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การเริ่มต้นอาเรย์ทั่วไปด้วยค่าเริ่มต้นเดียวใน C++


การเริ่มต้นอาเรย์ด้วยค่าเริ่มต้น

สามารถเริ่มต้นอาเรย์ทั้งหมดเป็นศูนย์ได้ง่ายๆ ดังนี้:

int arr[10] = {0};

แต่ไม่สามารถเริ่มต้นอาเรย์ทั้งหมดเป็นค่าที่ไม่ใช่ศูนย์ด้วยวิธีนี้ได้:

int arr[10] = {5};

ในตัวอย่างนี้ จะมีแค่ element แรกเป็น 5 ส่วนที่เหลือเป็น 0

สามารถใช้ for loop เริ่มต้นอาเรย์ด้วยค่าเดียวที่ไม่ใช่ศูนย์ได้:

for(int i = 0; i < 10; i++) {
    arr[i] = 5;
}

ตัวอย่างนี้ element ทั้งหมดจะเป็น 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