Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Setting Up Your Development Environment for C Programming
3.
C Program to Multiply Two Matrices
3.1.
C
4.
Complexity Analysis of Matrix Multiplication in C
5.
Frequently Asked Questions
5.1.
What happens if the matrices are not compatible for multiplication?
5.2.
Can matrix multiplication be done in place?
5.3.
How can I optimize matrix multiplication for better performance?
6.
Conclusion
Last Updated: Jun 1, 2024
Easy

C Program for Matrix Multiplication

Author Gaurav Gandhi
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Matrix multiplication is a basic yet crucial operation in the field of computer science, particularly when dealing with algorithms that involve data manipulation and mathematical computations. In C programming, implementing matrix multiplication can enhance understanding of array handling and loops. 

C Program for Matrix Multiplication

This article will help you learn the process of multiplying two matrices using C, highlighting the initialization, multiplication process, and display of the result. We'll learn about the setup of the development environment, provide a basic outline to writing the code, and discuss the output to ensure you can integrate these concepts into larger projects.

Setting Up Your Development Environment for C Programming

To start programming in C, especially for tasks like matrix multiplication, you need to set up a proper development environment. First, you need a code editor where you can write & compile your C programs. Some popular choices include GCC (GNU Compiler Collection) for Linux & MinGW for Windows. After installing your compiler, you also need a text editor. Beginners can use simpler editors like Notepad++ or more integrated environments like Code::Blocks, which include a compiler & a debugger.

To compile a C program for matrix multiplication, open your terminal or command prompt, navigate to the directory containing your C file, and use the command gcc -o matrix_multiply matrix_multiply.c to compile. If there are no errors, you can run your program by typing ./matrix_multiply in Linux or matrix_multiply.exe in Windows.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

C Program to Multiply Two Matrices

To multiply two matrices in C, you must first understand the basics of matrix operations. A matrix is essentially a rectangular array of numbers arranged in rows & columns. For multiplication, the number of columns in the first matrix must match the number of rows in the second matrix.

Here’s a simple C program to demonstrate matrix multiplication:

  • C

C

#include <stdio.h>

int main() {
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;

printf("Enter rows & columns for the first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows & columns for the second matrix: ");
scanf("%d %d", &r2, &c2);

// Checking if multiplication is possible
if (c1 != r2) {
printf("Matrix multiplication not possible.\n");
return 0;
}

// Taking input for the first matrix
printf("Enter elements of matrix 1:\n");
for (i = 0; i < r1; i++)
for (j = 0; j < c1; j++)
scanf("%d", &a[i][j]);

// Taking input for the second matrix
printf("Enter elements of matrix 2:\n");
for (i = 0; i < r2; i++)
for (j = 0; j < c2; j++)
scanf("%d", &b[i][j]);

// Initializing elements of result matrix to 0
for (i = 0; i < r1; i++)
for (j = 0; j < c2; j++)
result[i][j] = 0;

// Multiplying matrices a & b & storing in result
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
for (k = 0; k < c1; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}

// Displaying the result
printf("Output Matrix:\n");
for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++)
printf("%d ", result[i][j]);
printf("\n");
}

return 0;
}

Output

Output

 

 

This program first checks if the multiplication is feasible by matching the columns of the first matrix with the rows of the second. It then takes user inputs for both matrices, performs the multiplication, & displays the resulting matrix.

Complexity Analysis of Matrix Multiplication in C

When we multiply matrices, it's important to understand how much computational work is being done. This is often described in terms of complexity. For matrix multiplication, the complexity mainly depends on the number of rows and columns in the matrices.

Assuming you are multiplying two matrices, A and B, where A is of size m x n and B is n x p, the resultant matrix C will be of size m x p. To compute each element in C, we perform n multiplications and n-1 additions. This calculation needs to be done for every element of the resulting matrix.

Here's a simple breakdown:
 

  • For each of the m rows in matrix A, and for each of the p columns in matrix B, the innermost loop runs n times.
     
  • Therefore, the total number of operations (both multiplications and additions) is approximately m * n * p.


In terms of big O notation, we describe this complexity as O(mnp). This means the time to compute the matrix multiplication increases linearly with the number of operations required, which is a direct product of the dimensions of the involved matrices.

Frequently Asked Questions

What happens if the matrices are not compatible for multiplication?

If the number of columns in the first matrix does not match the number of rows in the second matrix, multiplication cannot proceed. In C, this will typically not result in a compiler error but may cause runtime errors or incorrect results. Always check the dimensions of your matrices before attempting to multiply them to ensure they are compatible.

Can matrix multiplication be done in place?

In matrix multiplication, the result matrix is usually separate because the dimensions of the result might not match either of the original matrices. Moreover, trying to use one of the original matrices to store the result can overwrite data that is still needed for calculations, leading to incorrect results.

How can I optimize matrix multiplication for better performance?

To optimize matrix multiplication, consider using more advanced algorithms like Strassen's algorithm, which reduces the complexity from O(n^3) to approximately O(n^2.81). Additionally, optimizing memory access patterns and using parallel processing techniques, such as multithreading or employing GPU computations, can significantly speed up the multiplication process, especially for large matrices.

Conclusion

In this article, we have learned how to multiply two matrices using C programming. We started by setting up the development environment necessary for compiling and running C programs. Then, we moved on to discussing how to declare and initialize matrices in C, followed by a detailed explanation of the multiplication process using nested loops. We also discussed the complexity analysis of matrix multiplication, helping you understand the computational effort involved. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass