Learn C# · lesson 29 of 61 · about 10 minutes
Project: Battle Statistics
Fight the boss: keep every hit in a List<int>, then find the total, the best hit and the average.
What you'll learn
- Read values into a list until a stop value
- Total and search a list in one loop
- Print an average to one decimal place
The boss fight
Past the last gate waits the boss. Each hit's damage is typed in, and 0 means the fight is over. The hits go into a List<int>, because nobody knows how many there will be. Then one foreach loop finds the total and the best hit, the average is the total divided by the number of hits, and the boss is defeated by 50 damage or more.
Totals, best and average
- Read until a stop value:
while (x != 0) { list.Add(x); read the next x } - A total starts at 0; a best starts at the first item
(double)total / list.Countdivides as doubles, so the .5 isn't lost{average:F1}prints one digit after the point- Check
Count == 0first: an empty list has no first item and no average
Totals and averages
List<int> laps = new() { 62, 58, 65 };
int total = 0;
int best = laps[0];
foreach (int lap in laps)
{
total += lap;
if (lap < best) best = lap;
}
double average = (double)total / laps.Count;
Console.WriteLine($"Total {total}, best {best}, average {average:F1}");
Console.WriteLine(total / laps.Count);Output
Total 185, best 58, average 61.7
61Tip
int.TryParse gives 0 when a line isn't a number or there are no lines left, so reading until 0 also stops cleanly at the end of the input.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.