English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C Program to add two matrices using multi-dimensional array

Comprehensive Collection of C Programming Examples

In this example, you will learn how to add two matrices using two-dimensional arrays in C programming.

To understand this example, you should be familiar with the followingC Programming LanguageTopic:

Program to add two matrices

#include <stdio.h>
int main() {
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;
    printf("Enter the number of rows (1to10between 0): ");
    scanf("%d", &r);
    printf("Enter the number of columns (1to10between 0): ");
    scanf("%d", &c);
    printf("\nEnter the elements of the first matrix:\n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    printf("Enter the elements of the second matrix:\n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("Enter element a%d%d: ", i + 1, j + 1);
            scanf("%d", &b[i][j]);
        }
    //Add two matrices
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            sum[i][j] = a[i][j] + b[i][j];
        }
    //Print the result
    printf("\nSum of two matrices: \n");
    for (i = 0; i < r; ++i)
        for (j = 0; j < c; ++j) {
            printf("%d   ", sum[i][j]);
            if (j == c - 1) {
                printf("\n\n");
            }
        }
    return 0;
}

Output result

Enter the number of rows (1to10between 0): 2
Enter the number of columns (1to10between 0): 3
Enter the elements of the first matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a13: 4
Enter element a21: 5
Enter element a22: 2
Enter element a23: 3
Enter the elements of the second matrix:
Enter element a11: -4
Enter element a12: 5
Enter element a13: 3
Enter element a21: 5
Enter element a22: 6
Enter element a23: 3
Total of two matrices: 
-2   8   7   
10   8   6

In this program, the user is prompted to enter the number of rows r and columns c, and then the user is prompted to enter the elements of two matrices (r*order).

Then, we added the corresponding elements of two matrices and stored them in another matrix (a two-dimensional array). Finally, the results were printed on the screen.

Comprehensive Collection of C Programming Examples