このレッスンの内容

順番に足して合計を出す

合計をゼロから始めて、数を一つ読むたびに足していきます。

簡単な例

最初の状態2 + 4
結果6
Program.cs
using System;

int total = 0;
total += 2;
total += 4;
Console.WriteLine(total);
出力
6
広告

身近な例

三つのクラスから、それぞれ 5 冊、2 冊、4 冊の本が寄付されました。図書館の棚には全部で何冊並べられますか。

最初の状態5 + 2 + 4
結果11
Program.cs
using System;

int[] books = new int[] { 5, 2, 4 };
int total = 0;
int i = 0;
while (i < 3) {
    total += books[i];
    i += 1;
}
Console.WriteLine(total);
出力
11
例を実行する
ターミナル
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
公式ドキュメント