Back

Activity 1.19: Counting With for

divider

Activity 1.19

Counting With for

Key Concepts

Three Parts, One Line

Counting Up and Counting Down

Starting at Zero

You Knew the Number All Along

Activity 1.17 said a loop needs three things: a start, a condition, and a change.

while is what you reach for when you do not know how many passes — keep asking until the answer is valid, keep drawing until the window closes.

But the very first loop you wrote counted from 10 to 0. You knew the number before you started.

Three Parts, Three Places

int i = 1;
while (i <= 5)
{
Console.WriteLine($"Pass {i}");
i = i + 1;
}

The start is on line 1, the condition is on line 3, and the change is buried at the bottom of the block.

The change is the one everybody forgot last session, and it is the one furthest from the others.

Three Parts, Three Places

Terminal window
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5

Hold that output in your head. The next slide produces it again.

The Same Loop, Gathered Up

for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Pass {i}");
}

Predict it before you look.

The Same Loop, Gathered Up

Terminal window
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5

Identical. Character for character. Seven lines became four, and all three parts now sit on one line, in order, separated by semicolons.

Reading the Header

int i = 1
runs once, before anything else
i <= 5
checked before every pass, including the first; false ends the loop
i++
runs after every pass, at the bottom of the block

Nothing new is happening here. It is a while loop with its three parts tidied into one place — which makes leaving one out much harder to do by accident.

A Shorthand You Will See Everywhere

for (int i = 3; i >= 1; i--)
{
Console.WriteLine(i);
}

i++ means exactly i = i + 1, and i-- means i = i - 1.

A Shorthand You Will See Everywhere

Terminal window
3
2
1

Going down flips two things, not one. The change becomes i-- and the condition becomes >=. Flip only one and you get nothing or you get forever.

A Loop Can Run Zero Times

for (int i = 1; i <= 0; i++)
{
Console.WriteLine("Loading...");
}
Console.WriteLine("Done.");

i starts at 1 and the condition asks whether it is at most 0. Predict what prints.

A Loop Can Run Zero Times

Terminal window
Done.

One line, and no error of any kind. The condition is checked before the first pass, so a loop whose condition starts out false simply never runs.

That is not a bug to guard against. It is the behavior you want when somebody asks for zero of something.

Why Programmers Start at Zero

for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}

Count the passes this makes before you look.

Why Programmers Start at Zero

Terminal window
0
1
2
3
4

Five passes, and the number 5 never appears. 0 paired with < 5 runs five times, exactly like 1 paired with <= 5.

Learn to read i = 0; i < n as the words "n times." You will see it far more often than the other one.

i Belongs to the Loop

int i is declared inside the header, so it exists only while the loop is running.

Ask for i on the line after the closing brace and the program will not compile at all. The counter is born with the loop and dies with it.

You will make the compiler say so yourself in Task 4.

So Which One Do I Use?

  • for — when you know the number of passes before the loop starts
  • while — when you are waiting for something to become true

Loading five crates is a for. Asking until somebody types a valid crew size is a while.

Either one can do either job. The right one is the one that tells the next reader which situation you were in.

Today's Objectives

  • Writing a counted loop with for
  • Reading the three parts of a header
  • Counting up and counting down
  • Looping a number of times that is not known until run time
  • Choosing between for and while

Key Terms

Counted loop
A loop that runs a known number of times.
Loop counter
The variable tracking which pass the loop is on, almost always named i.
Increment
Adding one to a variable. i++.
Decrement
Subtracting one from a variable. i--.
Scope
The region of a program where a variable exists. A loop counter's scope is the loop.

'F' → Fullscreen

divider

Build

Everything today goes in a new program named 1-19-for.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.

Where a block shows only comments, you write that code yourself. The comments stay in your file.


Task 1: Five Passes

  • Write the code below and run it.
  • Now change i <= 5 to i < 5 and run it again. Count the lines. One character, one fewer pass.
  • Write down which system number disappeared — the first or the last. It matters, and it is not a guess.
  • Put it back to <= before you continue.
1-19-for
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Checking system {i}");
}
Console.WriteLine("All systems checked.");

Task 2: Add Up, and Count Down

  • Add two more loops. The first adds up 1 through 10; the second counts backwards from 10.
  • Check the sum by hand. 1 through 10 comes to 55, so if your program disagrees the loop is wrong and not the arithmetic.
  • The countdown flips two things at once — i-- for the change and >= for the condition. Predict what happens if you write i-- and leave the condition as <=, write the prediction down, and only then run it. The deck already gave you everything you need to get this right.
  • total is declared before its loop, on purpose. Be ready to say what would go wrong inside.
1-19-for
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Checking system {i}");
}
Console.WriteLine("All systems checked.");
Console.WriteLine();
int total = 0;
for (int i = 1; i <= 10; i++)
{
total = total + i;
}
Console.WriteLine($"Sum of 1 to 10: {total}");
Console.WriteLine();
for (int i = 10; i >= 1; i--)
{
Console.WriteLine($"T-minus {i}");
}

Task 3: A Number You Do Not Know Yet

  • The comments describe a crate loader. Write the code under them, leaving the comments where they are.
  • The number of passes comes from a variable, not from a number you typed. That is the whole point of this task — the program does not know how many passes it will make until somebody answers.
  • Convert the answer, or the comparison in your loop header will not compile.
  • The running total has to be declared before the loop, for the same reason total was in Task 2.
  • Test it with 0. It should load nothing, report 0, and not crash.
1-19-for
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Checking system {i}");
}
Console.WriteLine("All systems checked.");
Console.WriteLine();
int total = 0;
for (int i = 1; i <= 10; i++)
{
total = total + i;
}
Console.WriteLine($"Sum of 1 to 10: {total}");
Console.WriteLine();
for (int i = 10; i >= 1; i--)
{
Console.WriteLine($"T-minus {i}");
}
Console.WriteLine();
// Ask how many crates to load and convert the answer
// Loop that many times, showing the crate number each pass
// Keep a running total of mass, adding 40 for every crate
// After the loop, display the total mass

Task 4: Break It on Purpose

Two changes, one at a time. Write down exactly what happens, and put each one back before you try the next.

  1. In the T-minus loop, change i-- to i++ and leave everything else alone. Run it, watch for a moment, then press Ctrl + C.
  2. Put it back. Now add Console.WriteLine(i); as the very last line of your program and try to run it.

For number 1, record what it printed and how you stopped it. For number 2, record the error code, the message, and the line number — copy them exactly.

Number 2 never ran at all, and that is the difference worth noticing. Number 1 was a program that worked exactly as written and was still wrong. Number 2 was refused before it started. Say which kind of mistake is easier to find.


Challenge (Optional): Only the Even Ones

  • Add a loop that displays only the even numbers from 1 to 20. There are two good ways to do it, and you should write both.
  • One puts a decision inside the loop and uses the remainder operator from Activity 1.6.
  • The other changes the loop header so the loop never visits an odd number in the first place.
  • Both print the same ten numbers. Add a comment saying which you prefer and why, and say how many passes each one actually makes.
divider

Same Idea, Exam Notation

The reference sheet has no for loop at all. It offers REPEAT n TIMES, REPEAT UNTIL from Activity 1.17, and one more you meet at Activity 1.25. That is the complete set.

C#
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Exam Notation
i ← 1
REPEAT 5 TIMES
{
DISPLAY(i)
i ← i + 1
}

Count the Lines That Had to Be Added

REPEAT n TIMES gives you no counter. It repeats a block a fixed number of times and tells the block nothing at all about which pass it is on.

So when the block needs the pass number, you build the counter by hand — declared before the loop, and moved along as the last line inside it. Two extra lines of housekeeping that C# packs into one header.

C#Exam notation
for (int i = 1; i <= 5; i++)REPEAT 5 TIMES, plus a counter by hand
for (int i = 1; i <= n; i++)REPEAT n TIMES, plus a counter by hand
while (fuel < 500)REPEAT UNTIL(fuel ≥ 500)

Why This Matters on Exam Day

  • This exact shape turns up constantly. An initialization, a REPEAT, and an i ← i + 1 at the bottom of the block is one of the most common patterns on the whole exam.
  • Where the increment sits changes every answer. Put it above the work instead of below and every pass uses a number one too big.
  • Do not assume an i is available. If a question uses REPEAT n TIMES and declares no counter, the block genuinely cannot tell which pass it is on, and a question may be testing exactly that.
  • There is no counting-down form on the sheet. A countdown in exam notation is a counter you subtract from yourself, inside a REPEAT n TIMES.
divider

Checkpoint

Your finished program should run like this.

Example Output
Checking system 1
Checking system 2
Checking system 3
Checking system 4
Checking system 5
All systems checked.
Sum of 1 to 10: 55
T-minus 10
T-minus 9
T-minus 8
T-minus 7
T-minus 6
T-minus 5
T-minus 4
T-minus 3
T-minus 2
T-minus 1
How many crates? 3 [Enter]
Crate 1 loaded
Crate 2 loaded
Crate 3 loaded
Total mass: 120
  • Five systems are checked, and you wrote down which one disappeared when you changed <= to <
  • The sum is 55, and the T-minus loop ends at 1
  • The crate loader works for 3, and works for 0 without crashing
  • Both Task 4 results are recorded — how you stopped the runaway loop, and the exact error code, message, and line number
divider

Reflection

Answer the following questions before submitting your work.

  1. A for loop and a while loop can do the same job, and today's first slide proved it. Explain when each one is the clearer choice, and why gathering the three parts into one line makes a certain mistake harder to make.
  2. i <= 5 and i < 5 differ by one character and by one pass. Explain why that is such an easy mistake to make and how you would catch it in your own code.
  3. Exam notation has no for loop, so the counter has to be maintained by hand. Describe what would go wrong if the i ← i + 1 were placed at the top of the block instead of the bottom.
divider

Submit

Submit four things to the dropbox:

  1. Your 1-19-for program file.
  2. Which system number disappeared in Task 1, and what happens if you flip only one of the two things in the countdown.
  3. Both Task 4 results — how you stopped the runaway loop, and the error code, message, and line number from the last one.
  4. Your three reflection answers.

Activity Complete