Lesson contents

Keep a running total

Start at zero and add each value as you reach it.

Simple example

Start2 + 4
Result6
Program.cs
using System;

int total = 0;
total += 2;
total += 4;
Console.WriteLine(total);
Output
6
Advertisements

Everyday examples

Three classes donate 5, 2 and 4 books. How many books can the library put on its shelves?

Start5 + 2 + 4
Result11
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);
Output
11
Run the example
Terminal
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
Official documentation