Lesson 4 of 10
Loops
- 15 min
- 6 checks
- 3 hints
- Go to task
Goal
Repeating with for, while and foreach
Explanation
Use for when you know how many times to repeat. Its first line has three parts: the start int i = 1, the condition i <= 5 that's checked before every pass, and the step i++ that runs after every pass. The difference between < and <= is one whole pass, and it's one of the most common loop bugs.
while (hp > 0) repeats as long as its condition is true, and it suits cases where you don't know the number of passes in advance, like "keep hitting until the enemy falls". Make sure something inside the loop moves it toward its end, or it will keep going until the server stops it. foreach (char c in row) goes through every item in a collection without a counter, and a string is itself a collection of characters of type char.
Every number type has a maximum. The largest value an int can hold is about 2.1 billion (int.MaxValue), and if you go past it, the value wraps around to a negative number without any warning. Factorials grow fast: 13 factorial is already too big for an int, so use long, whose limit is around 9.2 quintillion.
Your task
Complete SumTo(n) to add up the numbers from 1 to n with for, Factorial(n) to return n factorial as a long (0 factorial is 1), HitsToKill(hp, damage) to count, with while, how many hits it takes for health to reach zero or less, and CountWalls(row) to count, with foreach, the '#' walls in one row of the game map. Then, from Main, print the 7 times table from 1 to 5, one multiplication per line in the form 7 x 3 = 21, and print nothing else.
Checks
6 checks- SumTo(5) is 15 and SumTo(100) is 5050
- Factorial(5) is 120, and 0 factorial is 1
- Factorial(20) is correct because it's a long
- HitsToKill counts four hits of 30 damage for 100 health
- CountWalls counts the # walls
- Only the 7 times table from 1 to 5 was printed