How to set all elements of an array to 0 in C++
In this tutorial, we are going to learn how to set all the array elements to 0 (zero) in C++.
Arrays in C++ are defined as a collection of items of a similar type stored at a contiguous memory location. Once, the size is defined for the array it remains fixed and cannot be changed further.
Arrays have some added advantages like they provide random access to the elements, also they have a better cache locality which favors boosting the performance.
To, declare all the array elements to zero we will be using the following approaches-
Approach-1: Using Initializer List
An initializer list in C++ is used to initialize an array with the same value. The array is initialized to zero if we provide an empty initializer list or just put 0 in the list.
#include <iostream> using namespace std; int main() { int arr[5] = { 0 }; // using initializer list for(int i=0;i<5;i++){ cout<<arr[i]<<" ";//printing the elements } return 0; }
Output:
0 0 0 0 0
Approach-2: Using Designated Initializer to set array elements zero
When we want to initialize a range with the same value we use this type of initializer. This is only used with GCC compilers. We can write it as
[first…….last]=value.
int arr[5] = {[0 ... 4] = 1}; // or don't specify the size for the array int arr[] = {[0 ... 4] = 1};
Approach 3: Using for loop
With the help of for loop we can initialize the array with the same value. Here, we will set all the elements to zero.
#include<iostream> using namespace std; int main(void) { int n = 5; int value = 0; int arr[n];// declaring the array // initializing the array for(int i =0; i<n; i++) { arr[i] = value; } //printing the values for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } return 0; }
Output:
0 0 0 0 0
Approach-4: Using std:: fill_n function
In C++ we use the std:: fill_n function, which assigns a value to the first n elements of the array.
#include <bits/stdc++.h> #include <algorithm> using namespace std; int main() { int n = 5; int val = 0;//value to be initialized int arr[n];//declaring array fill_n (arr, n, val); //printing the elements for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } return 0; }
Output:
0 0 0 0 0
Thus, we have learned how to set all the elements of an array to 0.
Leave a Reply