# How to Declare a Matrix in C++

In this article, we will discuss how to declare Matrix in C++.

We will use array to represent Matrix.

A Matrix is nothing but a 2-D array.

We can declare Matrix in C++ in 2 ways

1. Static Allocation
2. Dynamic Allocation

## Declare a Matrix in C++ (Static Allocation)

Static Allocation means memory is fixed.

The memory is assigned during compile time.

But Static allocation of Matrix may lead to inefficient use of memory.

`int Matrix;`

The above code declares a Matrix of 200 X 200. But our program only use Matrix of order 4 X 5. A lot of memory remains unused.

``````#include<iostream>
#include<vector>
using namespace std;

int main() {
int Matrix;
int n,m;

cout<<"Enter Number of Rows of Matrix: ";
cin>>n;
cout<<"Enter Number of Columns of Matrix: ";
cin>>m;

for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
Matrix[i][j] = i*m + j;
}
}

cout<<"\nMatrix: \n";
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
cout<<Matrix[i][j]<<' ';
}
cout<<endl;
}

}
``````

Output

## Declare a Matrix in C++ (Dynamic Allocation)

``````int** Matrix;
Matrix = (int**)malloc(n*sizeof(int*));
for(int i=0;i<n;++i)
Matrix[i] = (int*)malloc(m*sizeof(int));``````

The above code declares a Matrix of order n X m dynamically.

The main advantage of using dynamic allocation is that no memory is wasted.

``````#include<iostream>
#include<vector>
using namespace std;

int main() {
int n,m;
int** Matrix;

cout<<"Enter Number of Rows of Matrix: ";
cin>>n;
cout<<"Enter Number of Columns of Matrix: ";
cin>>m;

Matrix = (int**)malloc(n*sizeof(int*));
for(int i=0;i<n;++i)
Matrix[i] = (int*)malloc(m*sizeof(int));

for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
Matrix[i][j] = i*m + j;
}
}

cout<<"\nMatrix: \n";
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
cout<<Matrix[i][j]<<' ';
}
cout<<endl;
}

}``````

Output

Note: Instead of using arrays, we can also use 2D vector as Matrix.

What to Study Next?

References

Matrix Representation