×

C++ Program: Matrix Multiplication

Matrix Multiplication in C++

What is a Matrix?

A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often called entries or elements. Matrix has wide application in the field of engineering and mathematics and is solely intended to solve various business logical problems comprising its applications.

A matrix typically looks like an array where there are N rows and M columns. It also consists of symbols and expressions.

Matrix multiplication has been defined by a set of rules for multiplying. There are although various ways of representing matrix. Below is a pictorial representation of a usual matrix.

Matrix Multiplication in C++

Before proceeding to check how matrix multiplication is carried out in C++, we need prior knowledge of multi-dimensional arrays or say 2-D arrays. A matrix in general, is a multi-dimensional array in C++.

There a multi-dimensional array is of the form

 int arr[rows][columns]

Where rows and columns are integer values that can be initialized or can be taken input.

Let us now look at different approaches of carrying out matrix multiplication in C++.

Example:

#include <bits/stdc++.h>
 using namespace std;
 #define N 4
 void MatrixMultiply(int matrix1[][N],
               int matrix2[][N],
               int result[][N])
 {
     int i, j, k;
     for (i = 0; i < N; i++) {
         for (j = 0; j < N; j++) {
             result[i][j] = 0;
             for (k = 0; k < N; k++)
                 result[i][j] += matrix1[i][k] * matrix2[k][j];
         }
     }
 }
 int main()
 {
     int i, j;
     int result[N][N]; // To store result
     int matrix1[N][N] = { { 1, 1, 1, 1 },
                        { 2, 2, 2, 2 },
                        { 3, 3, 3, 3 },
                        { 4, 4, 4, 4 } };
     int matrix2[N][N] = { { 1, 1, 1, 1 },
                        { 2, 2, 2, 2 },
                        { 3, 3, 3, 3 },
                        { 4, 4, 4, 4 } };
 MatrixMultiply(matrix1, matrix2, result);
 cout << "Matrix after multiplication is:  \n";
     for (i = 0; i < N; i++) {
         for (j = 0; j < N; j++)
             cout << result[i][j] << " ";
         cout << "\n";
 }
 return 0;
 } 

Output:

Matrix Multiplication in C++

Explanation:

In the above code, we have defined a function 'MatrixMultiply' which takes as arguments 'matrix1', 'matrix2', and 'result' to carry out multiplication. The following algorithm is used for the process:

Start

  1. Declare function MatrixMultiply with arguments matrix1,  matrix2, and result.
  2. In the function, iterate thorough the elements using two loops for rows and columns.
  3. Declare the variable result as result=matrix1*matrix2
  4. In the driver code, initialize the matrix1 and matrix2 with their respective values in rows and columns.
  5. Call the function MatrixMultiply in the driver code which multiplies both the matrices.
  6. Print the result in matrix form as console output.

Stop

Logic:

The logic is to iterate through nested loops. If both the matrices are initially defined, we can multiply them using the formula of rows and columns where a1 *b1 and b2*a2 and so on. This brings out the result in the form of another matrix consisting of values which are the results of the multiplication of both the matrices.

Decimal to Binary Conversion in C++

We have come across the term Binary which is the elementary language through which computers communicate with each other. We can use whole numbers and natural numbers to represent our values. But a compiler converts the number to binary to facilitate the computer to understand our input. This is where decimal to binary conversion comes into play.

Binary numbers form the basis of communication in a computer system. Let us know how a decimal number is converted into a binary value through the image below:

Matrix Multiplication in C++

Here, we first find out the LCM of a number, and the remainder is written if it is not a perfect multiple of the number. The obtained value on the right side i.e. the remainder is read from bottom to top which gives us the binary number of 17.

Let us now look at the approaches and logical explanations of doing the same using C++.

Example 1: Using functions

#include <bits/stdc++.h>
 using namespace std;
 void DecimalToBinary(int number)
 {
     int binaryNumber[32];
     int i = 0;
     while (number > 0) {
         binaryNumber[i] = number % 2;
         number = number / 2;
         i++;
     }
     for (int j = i - 1; j >= 0; j--)
         cout << binaryNumber[j];
 }
 int main()
 {
     int number;
     cout<<"Enter number to get binary value: ";
     cin>>number;
     DecimalToBinary(number);
     return 0;
 } 

Output:

Matrix Multiplication in C++

Explanation:

In the above code, we have defined a function 'Decimal to binary' and the variable 'number'. The process can be explained through the following algorithmic explanation:

  1. Store the number when it is divided by 2 in the array.
  • Number needs to be divided by 2
  • Run a loop until the number is less than zero
  • print the remainder in the reverse order.

Example 2: Using recursion

#include <bits/stdc++.h>
 using namespace std;
 void DeciToBin(int number)
 {
     if (number == 0) {
         cout << "0";
         return;
     }
     DeciToBin(number / 2);
     cout << number % 2;
 }
 int main()
 {
     int number;
     cout<<"Enter number to get the binary value: ";
     cin>>number;
     DeciToBin(number);
     return 0;
 } 

Output:

Matrix Multiplication in C++

Explanation:

The above is quite similar to the previous program where we defined a function having the argument as a number which is to be taken as an input by the user. Here, we have similarly used a recursive approach where the function is repeating itself until the given condition is reached.

The recursive approach reduces the code complexity and enhances code-readability. Later, in the driver code, the function automatically call itself as soon as it gets the argument.

Although, the recursive provides better code readability and understanding the time complexity is increased when we use recursion in a code. Since the function keeps calling itself, it keeps repeating until the end condition is reached thereby increasing time consumption as compared to other native approaches.


Related Topics

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

strcat() vs strncat() in C++

In this tutorial, we will explore about strcat() and strncat() in the most usable language C++. We will also look at the difference between them. strcat() C++ is a computer language with...

4 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Input Iterators in C++

What are input iterators? Input iterators are used in sequence for carrying out input operations where each value is read-only. It is pointed by the iterator and further incremented. All the iterators...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.