はじめに
この実験では、2 次元配列を使って 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";
// 変数を初期化する
int row, col, i, j;
// 3 つの行列(2 次元配列)を宣言する
int m1[10][10], m2[10][10], sum[10][10];
// ユーザーから行列の行数と列数を取得する
cout << "\nEnter the number of Rows and Columns of matrix : ";
cin >> row >> col;
// 最初の行列の要素をユーザーから取得する
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];
}
}
// 2 番目の行列の要素をユーザーから取得する
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];
}
}
// 和の行列を計算する
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
sum[i][j] = m1[i][j] + m2[i][j];
}
}
// 行列を表示する
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
これにより、プログラムが実行され、2 つの行列を加算した結果が出力されます。
出力を検証する
プログラムを実行した後、以下のような出力が表示されるはずです。
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 次元配列を用いて 2 つの行列を加算する方法を学びました。2 つの行列を入力として受け取り、それらの対応する要素を加算し、和の行列を出力するプログラムを作成しました。



