5. Loops
Chapter 0101 2
What’s the Point?
- 
Understand the purpose of loops 
- 
Understand the difference between definite and indefinite loops 
- 
Use whileloops
- 
Use do-whileloops
- 
Use forloops
- 
Understand why breakandcontinueare crimes against nature
Source code examples from this chapter and associated videos are available on GitHub.
A computer is designed to execute a series of instructions, in order, very quickly. Now that we understand how to use Boolean expressions to control the flow of our programs, we can use that concept for a programming structure that really unlocks the power of the computer: repetition. Many of the tasks we think of as "computer tasks" are repetitive in nature. Processing data often involves performing the same operation on each piece of information, one after the other, until everything is processed. A computer game has to draw the screen, check for collisions, check what the user is doing with the gamepad, and update the positions of all the objects on the screen, over and over again, until the game ends. When we use a search engine on the web, that search engine has scanned the web one page at a time, indexing what it finds and then moving on to the next page, until it’s scanned all of the pages in its database. These kinds of repetitive tasks everywhere in computer use—and in computer programming.
Computers are great for these kinds of tasks: they don’t get bored, they don’t get tired, and they don’t make mistakes—other than the mistakes we make when programming them!
To create the kind of repetition that leverages this processing power, programmers use loops. A loop is a structure that repeats a block of code as long as a certain condition is true. Each time the loop repeats is called an iteration.
Time To Watch!
Introduction to Loops
5.1. while Loops
The first structure we’ll look at for creating loops in C# is the while loop.
A while loop repeats a block of code as long as a specified condition is true.
The condition is checked before the block of code is executed, so the block of code might not execute at all if the condition is false the first time it’s checked.
We can call this a check first, then run loop.
A while loop is exactly like an if statement: a Boolean expression is checked, and if it’s true, the block of code is executed.
The only difference is that, after the block of code is executed, program execution jumps back to the beginning of the loop and checks the condition again, instead of just moving forward as an if statement would.
If the condition is still true, the block of code is executed again.
while loop1
2
3
4
5
6
int count = 0;
while (count < 10)
{
    Console.WriteLine("Count is: " + count);
    count++;
}
In this example, the Boolean expression count < 10 is checked; if it’s true, the block of code is executed.
The block of code prints out the value of count, then increments count by 1.
The program then jumps back to the beginning of the loop and checks the condition again.
This process repeats until the expression count < 10 is false.
The result of this loop is that the program prints out the value of count 10 times, starting with 0 and ending with 9.
It is a definite loop (see the video Introduction to Loops, above) because, before the loop starts, it’s already been determined that the loop will repeat 10 times.
5.2. Infinite Loops
One thing to be careful of when using a while loop is the possibility of creating an infinite loop; they’re possible in any loop structure, but especially easy with a while loop.
An infinite loop is a loop that repeats forever, because the condition that determines whether the loop should repeat is never false.
Infinite loops are a common mistake for new programmers, and they cause our program to crash or appear to freeze.
while1
2
3
4
5
int count = 0;
while (count < 10)
{
    Console.WriteLine("Count is: " + count);
}
In this example, we’ve forgotten to increment count by 1 after printing it out.
count will always be 0, so the condition count < 10 will always be true.
The program will print out "Count is: 0" over and over again, forever.
| Your IDE has a way to stop the program if it’s stuck in an infinite loop. Often, this is a square button—like the symbol for "stop" in a media player app. Every IDE should also allow you to press Ctrl+C to stop a program. | 
A simple infinite loop in C# is:
while statement.1
2
3
4
while (true)
{
    // hey, there's nothing to stop this loop!
}
This loop will repeat forever, because the condition true is always true.
Some programmers use while (true) to start a loop and then use an if statement to break out of the loop when a certain condition is met, but that’s not really an infinite loop—it just puts the boolean expression that controls the loop in an if statement within the loop’s body instead of in the while statement.
I personally consider that less readable than using a clear condition in the while statement, so I don’t write loops like that.
I’ll rant and rave about that a little later in the chapter.
| There’s a common beginner mistake that also creates an infinite loop: adding a semicolon immediately after the  
 A semicolon by itself in C# essentially means "do nothing." So this really says, "While the count is less than 10, do nothing" and it never even gets to the code block. | 
5.3. do-while Loops
As we’ve seen, a while loop checks the condition before executing the block of code.
A do-while loop is similar, but it checks the condition after executing the block of code: run first, then check.
This means that the block of code will always execute at least once.
Other than that, a do-while loop is exactly the same as a while loop.
do-while loop in C#.1
2
3
4
5
6
int count = 0;
do
{
    Console.WriteLine("Count is: " + count);
    count++;
} while (count < 10);
This is the same loop as the while loop we looked at earlier, but the condition is checked after the block of code is executed.
The while statement is at the end of the loop; the do statement at the beginning indicates the block of code that should iterate.
Time To Watch!
while and do-while Loops in C#
Files from video:
- 
Starter code: PearlJamDebut.cs
- 
Completed code: PearlJamDebutFinished.cs
- 
Starter code: LoopCounting.cs
- 
Completed code: LoopCountingFinished.cs
5.3.1. Choosing Between a while and a do-while Loop
Both while and do-while loops work well for indefinite loops (though they can be used for definite loops as well).
There’s nothing in the structure of these loops that requires a counter or other control variable, so they can be used for loops that repeat until a certain condition is met, however many iterations that requires.
In many cases, it doesn’t matter whether we use a while or a do-while loop.
We really can use either one to create the same loop.
However, in some cases, one might be a better choice than the other.
The simple rule of thumb for now is: if we need to guarantee that the block of code will execute at least once, we should use a do-while loop; if we need to check the condition before executing the block of code, we should use a while loop.
 
5.4. Input Validation with Loops
A common use for indefinite loops is input validation. Input validation is the process of checking the data a user inputs into a program to make sure it’s valid. For example, if a program displays a menu with three options, a loop could keep asking for a selection until the user enters one of the three choices.
There are more advanced techniques we’ll eventually use for input validation, but indefinite loops are a simple way to make sure the user’s input is what we expect.
do-while loop 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
int choice;
string choiceString;
do
{
    Console.WriteLine("Choose an option:");
    Console.WriteLine("1. Check balance");
    Console.WriteLine("2. Deposit");
    Console.WriteLine("3. Withdraw");
    Console.WriteLine("4. Exit");
    Console.Write("Your choice: ");
    choiceString = Console.ReadLine();
    choice = Convert.ToInt32(choiceString);
} while (choice < 1 || choice > 4);
// Rest of the code...
This code will keep displaying the menu and asking for the user’s choice until the user enters a number between 1 and 4.
Take It for a Spin
This is a good time to stop and try out what you’ve learned so far. The Coding Practice assignment for this chapter can be completed with the concepts covered to this point.
5.5. for Loops
Definite loops are really common, especially when we learn about things like arrays later on, so C# provides a shorthand format to create that kind of loop: the for keyword.
The syntax of a for loop can be a little intimidating for new coders, but it really just takes  all three of the pieces we need for a loop and combines them into one line of code: initializing a counter, checking the counter, and changing the counter.
for loop.1
2
3
4
for (int count = 0; count < 10; count++)
{
    Console.WriteLine("Count is: " + count);
}
The for loop has three parts, separated by semicolons:
- 1. Initialization
- 
Runs at the start of the loop; used to set a counter. Example: int count = 0
- 2. Condition
- 
Checked before each iteration; the loop stops when this returns false.Example: count < 10
- 3. Update
- 
Runs after each iteration; used to update the counter. Example: count++
Once you get the hang of the syntax, the for loop is a really convenient way to create a definite loop.
Time To Watch!
for Loops in C#
File from video:
- 
Starter code: ForLoopDemo.cs
- 
Completed code: ForLoopDemoFinished.cs
5.6. break and continue Statements
I believe that while, do-while, and for loops, when written with clear Boolean expressions, are the most readable loops, and any loop a coder will need in their career can be written with one of those structures.
A well-written loop will execute the block of code as many times as necessary, and then stop when the condition is false, without any additional help from the programmer.
However, C# provides two statements that can be used to alter the flow of a loop: the break statement and the continue statement.
Since they aren’t necessary for writing loops, I consider them somewhat optional: none of my assignments questions will require you to use them. However, it is important for beginners to know how they work.
The break statement is used to exit a loop early.
When a break statement is executed, the loop stops, and the program continues with the next statement after the loop; think of it as a return statement for a loop (except that it can’t pass a value anywhere).
Some programmers use break when they need to get out of a loop before the controlling condition is false.
My own opinion is that this is a sign the controlling condition should be rewritten to account for all contingencies, but because you’re likely to see break in other people’s code, I think it’s important to know about it.
The continue statement is used to skip the rest of the block of code in a loop and jump back to the beginning of the loop.
When the continue statement is executed, the program stops executing the loop’s block of code, and jumps to the Boolean expression that controls the loop to see if it should run again.
Time To Watch!
break and continue in Java
Note: you read that right—this video is in Java, and I haven’t had time to re-record it yet. Java and C# are nearly identical, so you’ll be able to follow this. I’ve linked C# versions of the demo code below.
Files from video (C# translations):
- 
Completed code: BreakDemo1.cs
- 
Completed code: BreakDemo2.cs
- 
Completed code: EvilDemo.cs
5.7. Counters and Accumulators
Loops are often used to calculate a total or to count how many times something happens. When we use a loop to calculate a total, we call the variable that holds the total an accumulator. When we use a loop to count how many times something happens, we call the variable that holds the count a counter.
We’ve seen counters in the examples of definite loops, where we used a counter variable to control how many times the loop repeated.
In fact, for loops essentially require a counter variable to work.
But in addition to controlling the loop, we can also use a counter variable to count how many times something happens within the loop.
As a trivial example, we could count how many numbers are divisible by 4 in a given range.
(We’ll pretend that we don’t know a mathematical solution to that problem—we’re trying to learn loops here!)
1
2
3
4
5
6
7
8
9
int divisible = 0; // This is our counter variable
for (int i = 33; i <= 75; i++)
{
    if (i % 4 == 0)
    {
        divisible++; // Increment the counter when we find a number divisible by 4
    }
}
Console.WriteLine("There are " + divisible + " numbers between 33 and 75 that are divisible by 4.");
Before starting the loop, we declare and initialize a variable that will hold our count; in this case, we call it divisible.
The for loop uses a control variable called i to iterate through the numbers from 33 to 75.
Then, inside the loop, we check each number to see if it’s divisible by 4.
To check that, we use the modulus operator (%), which gives us the remainder when one number is divided by another; if there is no remainder when i is divided by 4, then i is divisible by 4.
When we find a number that meets that condition, we increment our counter variable divisible by 1.
Once the loop is finished, the variable divisible holds the total count of numbers between 33 and 75 that are divisible by 4, and we can output that value.
An accumulator is similar, but instead of counting how many times something happens, it adds up a total.
Again, we’ll initialize a variable before the loop starts. Within the loop, we’ll add to that variable as necessary, and when the loop is finished, the variable will hold the total.
In this example, we’ll ask the user to input numbers until they enter a zero, and then we’ll output the total of all the numbers they entered.
1
2
3
4
5
6
7
8
9
int total = 0; // This is our accumulator variable
int number;
do
{
    Console.Write("Enter a number (0 to stop): ");
    number = Convert.ToInt32(Console.ReadLine());
    total += number; // Add the entered number to the total
} while (number != 0);
Console.WriteLine("The total is: " + total);
Note that counters and accumulators may not seem that important in these simple examples, but as we learn more about programming, we’ll see that they are essential tools for working with data. They’ll be especially important when we learn about arrays.
5.8. A Word About Nested Loops
We can put a loop inside another loop, and that’s called a nested loop. They are useful in some situations, and studying them can improve your ability to think through loop-based algorithms.
However, they are beyond the scope of this course, which focuses on the fundamentals of C# programming.
Check Yourself Before You Wreck Yourself (on the assignments)
Chapter Review Questions
Sample answers provided in the Liner Notes.