Open In App

How to Initialize an Array in C++?

In C++, an array is a collection of similar datatypes stored in contiguous memory locations in which each element can be accessed using their indices. In this article, we will learn how to initialize an array in C++.

Initializing an Array in C++

To initialize an array in C++, we can use the assignment operator = to assign values to the array at the time of declaration. The values are provided in a comma-separated list enclosed in curly braces {}.

Syntax to Initialize an Array in C++

We can use the below syntax to initialize an array at the time of declaration.

datatype arrayName[arraySize] = {element, element2, ..., elementN};

C++ Program to Initialize an Array

The below program illustrates how we can initialize an array in C++.

// C++ Program to illustrate how to initialize an array
#include <iostream>
using namespace std;

int main()
{
    // Initialize an array using initializer list
    int arr[5] = { 10, 20, 30, 40, 50 };

    // Find the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);

    // Print the elements of the array
    cout << "Array Initialized" << endl;

    cout << "Array Elements:";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output
Array Initialized
Array Elements:10 20 30 40 50 

Time Complexity: O(N), here N denotes the number of elements in the array.
Auxiliary Space: O(1)



Article Tags :