This tutorial will discuss multiple ways to initialize an array in C++.
Table Of Contents
Initialize an Array with hard coded values
You can initialize an array while declaring it. In the example below, we have an initialized an array with 5 integer elements.
int arr[] = {78, 89, 10, 61, 55};
If we provide hardcoded values in the curly braces, then we do not need to explicitly provide the size of the array while declaring it. This expression will create an array of 5 elements.
In the example below, we will iterate over this array and print each element:
for (int i = 0; i < 5; ++i) { std::cout << "arr[" << i << "] = " << arr[i] << std::endl; }
Important points to note here are that the size of the array is 5. If we try to access any element in the array outside its size or limit, then it can cause undefined behavior.
Let’s see the complete example,
Frequently Asked:
- Check If Index Exists in an Array in C++
- Check if all elements in array are unique in C++
- Check if Any element in Array matches a condition in C++
- Check if an Array is Palindrome in C++
#include <iostream> int main() { // Initializ an Array with values during declaration // Array of integers with 5 elements int arr[] = {78, 89, 10, 61, 55}; // Print Array Elements line by line for (int i = 0; i < 5; ++i) { std::cout << "arr[" << i << "] = " << arr[i] << std::endl; } return 0; }
Output
arr[0] = 78 arr[1] = 89 arr[2] = 10 arr[3] = 61 arr[4] = 55
Initialize an Array with same Values
To initialize all elements of an array with the same value, we can pass a single value in the curly braces and initialize the array with it while declaring it. For example, to initialize all the 5 elements in the array with the value zero:
int arr[5] = {0};
Important point to note here is that these days in this kind of scenario, we need to provide the size in the square brackets while declaring the array. In previous example, we were able to just pass the elements, and compiler was able to deduce the size of array based on arguments provided while initialization. But now the compiler needs to know the size of the array during initialization.
Here’s an example where we declare and initialize an array of 5 integers with the value zero, and then we will iterate over it and print each value:
Let’s see the complete example,
#include <iostream> int main() { // Initializes all elements in Array with 0 int arr[5] = {0}; // Print Array Elements line by line for (int i = 0; i < 5; ++i) { std::cout << "arr[" << i << "] = " << arr[i] << std::endl; } return 0; }
Output
arr[0] = 0 arr[1] = 0 arr[2] = 0 arr[3] = 0 arr[4] = 0
Summary
We learned about two ways to initialize an Array in C++.
Summary
Today, we learned about multiple ways to initialize an array in C++.