Initialization of multidimensional array of zeros using C++
Hello coders, in this tutorial we will learn about how to initialize a multidimensional array of zeros. Before we proceed let’s discuss what is a multidimensional array, We can say that it is a combination of the number of rows and columns, We can also say that multidimensional array is an array containing one or more arrays.
A multidimensional array with zeros
Now I will show you the whole code for the multidimensional array with zeros then we will discuss the whole code step by step to understand it clearly so be patient.
Write a program to create a multidimensional array of size 3×3 with zeros.
#include<iostream> using namespace std; int main(){ int ar[3][3],i,j; //Initilization of array with zeros for(i=0;i<3;i++){ for(j=0;j<3;j++){ ar[i][j]=0; } } cout<<"Mulyidimensional array with zeros"; for(i=0;i<3;i++){ for(j=0;j<3;j++){ cout<<ar[i][j]<<" ";} cout<<"\n";} }
Let’s start from line 1,
#include<iostream>
This line is used to include the header file of name iostream and iostream is used for standard input\output.
Now line 2,
using namespace std;
“using namespace std” means we use the namespace named std. it provides us scope to the identifiers, functions.
Now line 3
int main()
This is the main function that is executed after the compilation of the code.
Line 4,
int ar[3][3],i,j;
This line creates an array of 3×3.
Now line 6,7,8,
for(i=0;i<3;i++)
for(j=9;j<3;j++)
ar[i][j]=0;
This is a loop first for loop defines for number of row (i,e., i = 0,1,2) and second for loop is for number of columns(i.e ., j = 0,1,2,)
Now when i=0 for this j=0,1,2
this will create combinations of [i][j] that are [0][0],[0][1], [0][2].
Similary when i=1 then combinations are [1][0],[1][1],[1][2]
when i=2 then combinations are [2][0],[2][1],[2][2]
and ar[i][j] stores value 0 for every combination for [i][j]
Now the lines 11,12,13,14 are used to print array.
for(i=0;i<3;i++)
for(j=0;j<3;j++)
cout<<ar[i][j]<<” “; Print each element of index [i][j]
cout<<“\n”;
Command:
For compiling:- g++ filename
For execution:- ./a.exe
Output:-
Multidimensional array with zeros 0 0 0 0 0 0 0 0 0
Leave a Reply