整数の合計を求める C++ プログラム

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

はじめに

この実験では、ユーザーから 'n' 個の整数を読み取り、それらの合計を出力する C++ プログラムを作成する方法を学びます。

n 個の数の合計を求めるコードの作成

WebIDE では、メニューバーから Terminal > New Terminal を選択して新しいターミナルを開きます。ターミナルで、以下のコマンドを入力して main.cpp という新しいファイルを作成します。

touch ~/project/main.cpp

次に、main.cpp ファイルを開き、以下のコードを貼り付けます。

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the program to find the Sum of n numbers entered by the user :-)\n\n\n";

    // 変数宣言
    int n, i, temp;

    // 和を 0 で初期化
    int sum = 0;

    // ユーザーから 'n' を入力として受け取る
    cout << "Enter the number of integers you want to add : ";
    cin >> n;
    cout << "\n\n";

    // ユーザーから n 個の整数を入力として受け取り、それらを加算して最終的な和を求める
    for (i = 0; i < n; i++)
    {
        cout << "Enter number " << i + 1 << " :  ";
        cin >> temp;

        // 各数をすべての前の数の和に加算して最終的な和を求める
        sum += temp;
    }

    // 和を出力する
    cout << "\n\nSum of the " << n << " numbers entered by the user is : " << sum << endl;
    cout << "\n\n\n";

    return 0;
}

コードのコンパイルと実行

コードをコンパイルするには、ターミナルに次のコマンドを入力します。

g++ ~/project/main.cpp -o main

次に、実行可能ファイルを実行するには、次のコマンドを入力します。

./main

以下のような出力が表示されます。

Welcome to the program to find the Sum of n numbers entered by the user :-)

Enter the number of integers you want to add : 4


Enter number 1 : 2
Enter number 2 : 3
Enter number 3 : 5
Enter number 4 : 10


Sum of the 4 numbers entered by the user is : 20


まとめ

この実験では、ユーザーから 'n' 個の整数を読み取り、それらの合計を出力する C++ プログラムを作成する方法を学びました。あなたは無事にこの実験を完了しました。おめでとうございます!