Today's tools work together: a loop provides the repetition, conditions make the decisions, and variables declared outside the loop keep the state. Before writing the program below, work out the expected output by hand. A loop that ends one pass too soon or too late looks almost right, so your hand-written answer is the only way to notice.
Warm up: choose the loop condition
These two loops differ by a single character. Predict how many lines each prints, and which one correctly lists the days up to and including day 3.
for (int day = 1; day <= 3; day++)
{
Console.WriteLine(day);
}Check your prediction
1
2
3for (int day = 1; day < 3; day++)
{
Console.WriteLine(day);
}Check your prediction
1
2Build it yourself
A goal planner
A learner wants to study 300 minutes. They study 45 minutes on normal days, and every third day (days 3, 6, 9 and so on) they take a light day of 20 minutes. Starting at day 1, print one line per day until the goal is reached, in this form: Day 1: 45 min, 45 total, normal. Then print Goal reached on day N.
Before you run it, work out on paper which day should reach the goal. Then check that a goal of 0 prints only the last line, using day 0.
int goal = 300;
Console.WriteLine($"Goal: {goal}");Hint 1: the idea
You don't know how many days it will take, so the loop continues while the total is below the goal.
Hint 2: a first step
Write the loop with every day at 45 minutes first. Then use % to spot every third day and choose the amount. If you print a conditional inside an interpolated string, wrap it in its own parentheses: a bare : there would be read as the start of a format.
Show one solution
int goal = 300;
int total = 0;
int day = 0;
while (total < goal)
{
day++;
bool light = day % 3 == 0;
int minutes = light ? 20 : 45;
total += minutes;
Console.WriteLine($"Day {day}: {minutes} min, {total} total, {(light ? "light" : "normal")}");
}
Console.WriteLine($"Goal reached on day {day}");Day 1: 45 min, 45 total, normal
Day 2: 45 min, 90 total, normal
Day 3: 20 min, 110 total, light
Day 4: 45 min, 155 total, normal
Day 5: 45 min, 200 total, normal
Day 6: 20 min, 220 total, light
Day 7: 45 min, 265 total, normal
Day 8: 45 min, 310 total, normal
Goal reached on day 8A while loop fits because the number of days isn't known in advance: the loop runs until the total reaches the goal. day is increased first in the body, so the first day is 1, and the % 3 == 0 test picks out every third day. After the loop ends, day still holds the last day, which is what the final line prints.
Try a goal of 310 and of 311. The first should still finish on day 8 and the second on day 9, because a goal of exactly the running total counts as reached. If your version disagrees, look at your loop condition.
Completion is saved in this browser only. It does not measure mastery.