×

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

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

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.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 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.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

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.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.