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[200][200];

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[200][200];
	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?

  1. Matrix Multiplication
  2. Matrix Addition

References

Matrix Representation

Leave a Comment

Your email address will not be published. Required fields are marked *