How to Initialize multidimensional array with zeros in C++
In this tutorial, we will learn to initialize the multidimensional array with zeros in C++. There are multiple approaches to do this task. Two of them are given below:
First Approach: using assignment operator
We can use the assignment operator to assign the value to zero as described in the below code.
#include<iostream>
using namespace std;
int main() {
int array[10][10] = {0}; // initialize all the elments to zero
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
cout << array[i][j] << " ";
}
cout << endl;
}
}
Output:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Second Approach: using memset STD
We can also use std::memset to initialize all the elements of 2D array.
To use std::memset, we have to include the header file named “#include<cstring>“.
The implementation is given below:
#include<iostream>
#include<cstring>
using namespace std;
int main() {
int arr[3][3];
memset( arr, 0, sizeof(arr) ); // initialize all the elments to zero
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
Output:
0 0 0 0 0 0 0 0 0
Also Check: find the largest file in folder using c++
Leave a Reply