2 次元配列の中で最も大きな偶数の行を見つける

C++Beginner
オンラインで実践に進む

はじめに

この実験では、2 次元配列を使って、配列の中で偶数が最も多い行を見つける C++ プログラムを作成します。

必要な変数を宣言する

以下のコマンドを使って、~/project ディレクトリに新しいファイル main.cpp を作成します。

touch ~/project/main.cpp

必要な変数を宣言して始めます。それには anlij、および count が含まれます。

int a[10][10], n, l, i, j, count = 0;

行列のサイズと行番号を取得する

次に、ユーザーから行列のサイズと行番号を取得します。ユーザー入力値を取得するために cin 関数を使用します。

cout << "Enter matrix size(l * l): ";
cin >> l;
cout << "Enter row number of matrix: ";
cin >> n;

ユーザー入力の妥当性を確認する

n が行列サイズの範囲内であるかどうかをチェックすることで、ユーザー入力の妥当性をチェックします。そうでない場合、エラーメッセージを表示してプログラムを終了します。

if (n < 0 || n > l) {
  cout << "Error: Row exceeds matrix size. Please enter a value > 0 and less than or equal to the size of matrix." << endl;
  exit(0);
}

行列の値を取得する

ユーザーから行列の値を取得するために、ネストした for ループを使用します。

cout << "Enter the matrix values: " << endl;

for (i = 1; i <= l; i++) {
  for (j = 1; j <= l; j++) {
    cin >> a[i][j];
  }
}

偶数の数が最も多い行を見つける

行をループして偶数の数をカウントするために、for ループを使用します。現在の数が偶数の場合、count 変数をインクリメントします。

for (i = 1; i <= l; i++) {
  if (a[n][i] % 2 == 0) {
    count++;
  }
}

結果を出力する

その行の行値と偶数の数を出力します。

cout << "\nRow is given below:\n";

for (i = 1; i <= l; i++) {
  cout << a[n][i] << " ";
}

cout << "\n\nNo. of even numbers in row is: " << count << endl;

プログラムをコンパイルして実行する

g++ コンパイラを使用してプログラムをコンパイルし、端末で実行します。

$ g++ main.cpp -o main
$./main
完全なコード
#include<iostream>
using namespace std;

int main() {
  int a[10][10], n, l, i, j, count = 0;

  cout << "Enter matrix size(l * l): ";
  cin >> l;
  cout << "Enter row number of matrix: ";
  cin >> n;

  if (n < 0 || n > l) {
    cout << "Error: Row exceeds matrix size. Please enter a value > 0 and less than or equal to the size of matrix." << endl;
    exit(0);
  }

  cout << "Enter the matrix values: " << endl;

  for (i = 1; i <= l; i++) {
    for (j = 1; j <= l; j++) {
      cin >> a[i][j];
    }
  }

  for (i = 1; i <= l; i++) {
    if (a[n][i] % 2 == 0) {
      count++;
    }
  }

  cout << "\nRow is given below:\n";

  for (i = 1; i <= l; i++) {
    cout << a[n][i] << " ";
  }

  cout << "\n\nNo. of even numbers in row is: " << count << endl;

  return 0;
}

まとめ

この実験では、二次元配列の中で偶数の数が最も多い行を見つけるための C++ のプログラムをどのように実装するかを学びました。これは、一連の変数を作成し、配列をループ処理することで達成しました。条件文を使用して、プログラムの結果を出力しました。