Lektionens innehåll

Summera efter hand

Börja på noll och lägg till varje värde när du når det.

Ett enkelt exempel

Från början2 + 4
Resultat6
Program.cs
using System;

int total = 0;
total += 2;
total += 4;
Console.WriteLine(total);
Utdata
6
Annonser

Exempel från vardagen

Tre klasser donerar 5, 2 och 4 böcker. Hur många böcker kan biblioteket sätta på sina hyllor?

Från början5 + 2 + 4
Resultat11
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);
Utdata
11
Kör exemplet
Terminal
dotnet new console --output Lesson
cp Program.cs Lesson/Program.cs
dotnet run --project Lesson
Officiell dokumentation