두 행렬 더하기

C++Beginner
지금 연습하기

소개

이 랩에서는 2 차원 배열을 사용하여 두 행렬을 더하는 C++ 프로그램을 작성합니다.

C++ 파일 생성

~/project 디렉토리 안에 add_matrices.cpp라는 C++ 파일을 생성합니다. 이 파일은 코드를 작성할 메인 파일이 됩니다.

cd ~/project
touch add_matrices.cpp

코드 작성

아래 코드를 복사하여 add_matrices.cpp 파일에 붙여넣습니다.

#include <iostream>

using namespace std;

int main() {
    cout << "\n\nWelcome to the Add Matrices Program\n\n\n";

    // Initialize variables
    int row, col, i, j;

    // Declare the three matrices (2D arrays)
    int m1[10][10], m2[10][10], sum[10][10];

    // Get the number of rows and columns of matrix from user
    cout << "\nEnter the number of Rows and Columns of matrix : ";
    cin >> row >> col;

    // Get the elements of the first matrix from user
    cout << "\nEnter the " << row * col << " elements of first matrix : \n";
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            cin >> m1[i][j];
        }
    }

    // Get the elements of the second matrix from user
    cout << "\nEnter the " << row * col << " elements of second matrix : \n";
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            cin >> m2[i][j];
        }
    }

    // Calculate the sum matrix
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            sum[i][j] = m1[i][j] + m2[i][j];
        }
    }

    // Display the matrices
    cout << "\n\nThe first matrix is : \n";
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            cout << m1[i][j] << "  ";
        }
        cout << endl;
    }

    cout << "\n\nThe second matrix is : \n";
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            cout << m2[i][j] << "  ";
        }
        cout << endl;
    }

    cout << "\n\nThe Sum matrix is : \n";
    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            cout << sum[i][j] << "  ";
        }
        cout << endl;
    }

    return 0;
}

코드 컴파일 및 실행

코드를 컴파일하려면 ~/project 디렉토리에서 터미널을 열고 다음 명령을 실행합니다.

g++ add_matrices.cpp -o add_matrices

프로그램을 실행하려면 터미널에 다음 명령을 입력합니다.

./add_matrices

이렇게 하면 프로그램이 실행되고 두 행렬을 더한 결과가 출력됩니다.

출력 결과 검증

프로그램을 실행한 후 다음과 같은 출력을 볼 수 있습니다.

Welcome to the Add Matrices Program

Enter the number of Rows and Columns of matrix : 2 2

Enter the 4 elements of first matrix :
1 2 3 4

Enter the 4 elements of second matrix :
5 6 7 8


The first matrix is :
1  2
3  4


The second matrix is :
5  6
7  8


The Sum matrix is :
6  8
10  12

요약

이 랩에서는 C++ 프로그래밍 언어를 사용하여 2 차원 배열 (2D arrays) 을 사용하여 두 행렬을 더하는 방법을 배웠습니다. 두 행렬을 입력으로 받아 해당 요소들을 더하고 합 행렬을 출력하는 프로그램을 만들었습니다.