We use array initialization to create a list of values stored together in memory. It helps us organize data so we can use it easily later.
Array initialization in C++
class ArrayExample { public: int numbers[5]; // Declare an array of 5 integers void initialize() { // Method 1: Initialize with values at declaration int fixedNumbers[5] = {1, 2, 3, 4, 5}; // Method 2: Initialize all elements to zero int zeros[5] = {}; // Method 3: Initialize some elements, rest are zero int partial[5] = {10, 20}; // Method 4: Initialize using a loop for (int i = 0; i < 5; i++) { numbers[i] = i * 10; } } };
Arrays have fixed size, so you must decide how many elements it holds when you declare it.
If you initialize fewer elements than the size, the rest are set to zero automatically.
int emptyArray[3] = {};
int oneElement[1] = {42};
int startEnd[4] = {5, 0, 0, 10};
int loopArray[5]; for (int i = 0; i < 5; i++) { loopArray[i] = i + 1; }
This program shows two ways to initialize arrays: directly with values and by filling with a loop. It prints both arrays to show the results.
#include <iostream> int main() { // Declare and initialize an array with values int fixedNumbers[5] = {1, 2, 3, 4, 5}; // Declare an empty array and fill it with a loop int loopNumbers[5]; for (int index = 0; index < 5; index++) { loopNumbers[index] = (index + 1) * 10; } // Print fixedNumbers std::cout << "fixedNumbers: "; for (int index = 0; index < 5; index++) { std::cout << fixedNumbers[index] << " "; } std::cout << std::endl; // Print loopNumbers std::cout << "loopNumbers: "; for (int index = 0; index < 5; index++) { std::cout << loopNumbers[index] << " "; } std::cout << std::endl; return 0; }
Time complexity to initialize with a loop is O(n), where n is the array size.
Space complexity is O(n) because the array stores n elements.
Common mistake: forgetting to initialize elements, which can leave garbage values if not zero-initialized.
Use direct initialization when values are known; use loops when values depend on calculations.
Arrays hold multiple values of the same type in a fixed size.
You can initialize arrays directly with values or fill them later using loops.
Uninitialized elements default to zero if you use empty braces {}.