Home >>C++ Tutorial >C++ Multi-Dimensional Arrays

C++ Multi-Dimensional Arrays

C++ Multi-Dimensional Arrays

Multi-Dimensional Arrays in C++ can be of two or three dimensional and also known as the rectangular arrays as the data is stored in them in the form of matrix. This array returns the element sequentially.

Here is an example of the multi-dimensional arrays in C++ that will explain you the things in deep:

#include <iostream>  
using namespace std;  
int main()  
{  
    int arr[2][2];  //declaration of array   
    arr[0][0]=10;  //initialization  of array  
    arr[0][1]=11;   
    arr[1][0]=12;  
    arr[1][1]=13;  
    for(int i = 0; i < 2; ++i)  
    {  
        for(int j = 0; j < 2; ++j)  
        {  
            cout<< arr[i][j]<<" ";  
        }  
        cout<<"\n";    
    }  
    return 0;  
}  
Output :
10 11
12 13

Here is another example of the 2-dimensional arrays(Sum of 2-D array)

#include <iostream>  
using namespace std;  
int main()  
{  
	int sum=0;
    int arr[2][2];  //declaration of array   
    arr[0][0]=10;  //initialization  of array  
    arr[0][1]=11;   
    arr[1][0]=12;  
    arr[1][1]=13;  
    for(int i = 0; i < 2; ++i)  
    {  
        for(int j = 0; j < 2; ++j)  
        {  
            sum=sum+arr[i][j];  
        }     
    }  
	cout<<"Sum of 2-D array="<<sum; 
    return 0;  
}  
Output :
Sum of 2-D array=46

Here is another example of the 2-dimensional arrays(Sum of even and odd of 2-D array)

#include <iostream>  
using namespace std;  
int main()  
{  
	int even=0;
	int odd=0;
    int arr[2][2];  //declaration of array   
    arr[0][0]=10;  //initialization  of array  
    arr[0][1]=11;   
    arr[1][0]=12;  
    arr[1][1]=13;  
    for(int i = 0; i < 2; ++i)  
    {  
        for(int j = 0; j < 2; ++j)  
        {  
			if(arr[i][j]%2==0)
			{
            even=even+arr[i][j];
			}	
			else
			{
			odd=odd+arr[i][j];
			}
        }     
    }  
	cout<<"Sum of even 2-D array="<<even<<"\n";
	cout<<"Sum of odd 2-D array="<<odd;	
    return 0;  
}  
Output :
Sum of even 2-D array=22
Sum of odd 2-D array=24

No Sidebar ads