You are entering the most difficult chapters of this book. Loops are a mighty tool that all programmers need as much as the air they breathe. Understanding loops is not simple, which is why you will go through many exercises with loops.
Repeating the Same Text
A loop is a tool to efficiently write repetitions of the same or more often a similar activity. So that you can properly appreciate loops, you will solve some of the tasks twice, first without a loop and then with it. You will start with some repetition of the same activity, and after that you will move on to using loops to repeat similar activities.
Task
You will write a program that displays “I will start learning tomorrow.” ten times in a row (see Figure 20-1).
Figure 20-1 Ten repetitions
Solution
Here is the code:
static void Main(string[] args)
{
// Output
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
Console.WriteLine("I will start learning tomorrow.");
// Waiting for Enter
Console.ReadLine();
}
Solution Using a Loop
Think a bit about the previous exercise. Can you imagine that someone might want you to change the displayed sentence? Can you imagine repeating it a hundred times rather than ten times? Can you imagine the number of repetitions being entered by the user?
To solve these problems, you need a new tool: a loop.
Solution
Here is the code:
static void Main(string[] args)
{
// Output
for (int count = 0; count < 10; count++)
{
Console.WriteLine("I will start learning tomorrow.");
}
// Waiting for Enter
Console.ReadLine();
}
How the for Loop Works
You use the for construction to indicate repetition. Its general syntax looks like this:
for (initializer; loopCondition; iterator)
{
statement;
statement;
statement;
...
}
The for loop works like this:
initializer is performed once before entering the loop.
loopCondition is being evaluated before every turn of the loop. If it holds, the computer enters the loop and executes the statements inside its body.
The iterator statement is executed after every turn of the loop is completed. After that, loopCondition is evaluated again.
Figure 20-2 shows the program flow.
Figure 20-2 The program flow
The Loop
In this case, the required number of repetitions is achieved by counting the loop turns performed so far. For that purpose, you use the count variable.
At the beginning ( initializer), the variable is set to zero.
After completing every loop turn ( iterator), the variable is incremented by one.
The loop body (the display of a line of text) is repeated as long as (loopCondition) the number of lines in the output has not reached ten. As soon as the count variable becomes 10, the condition (count < 10 or 10 < 10) will no longer be fulfilled, the loop will terminate, and the computer will continue executing the statements following the loop.
Explore It Yourself
You should take the time to explore the inner workings of loops to grasp them thoroughly. Use debugging tools you already know: stepping and inspecting the count variable.
Tip
Visual Studio can help you write a for loop without mistakes. Just enter for, press the Tab key twice, and edit the generated loop header.
Choosing the Number of Repetitions
The for loop allows you to solve cases when you do not know the number of repetitions in advance (at the time of code writing).
Task
You will modify the previous exercise to let the user specify the number of the sentence repetitions (see Figure 20-3).
Figure 20-3 Letting the user specify the number of sentence repetitions
Solution
Here’s the code:
static void Main(string[] args)
{
// Input
Console.Write("Enter number of repetitions: ");
string input = Console.ReadLine();
int howManyTimes = Convert.ToInt32(input);
// Output
for (int count = 0; count < howManyTimes; count++)
{
Console.WriteLine("I will start learning tomorrow.");
}
// Waiting for Enter
Console.ReadLine();
}
Discussion
Note the following:
Compared to the previous task, you replaced the fixed number of repetitions with a variable value entered by the user.
Carefully choose the name of the variable to store the required total number of repetitions; here it’s howManyTimes. Specifically, you should distinguish it from the count variable storing the current number of repetitions.
Throwing a Die Repeatedly
You will see one more example of repeating the same activity.
Task
You will write a program that throws a die 20 times (see Figure 20-4).
Figure 20-4 Throwing a die 20 times
Solution
Here’s the code:
static void Main(string[] args)
{
// Random number generator
Random randomNumbers = new Random();
// Output
for (int count = 0; count < 20; count++)
{
int thrown = randomNumbers.Next(1, 6 + 1);
Console.Write(thrown.ToString() + " ");
}
// Waiting for Enter
Console.ReadLine();
}
Repeating Similar Lines
What if the repeated activity was not the same but just similar?
Task
You will output ten similar lines , differing only in the printed line number (see Figure 20-5).
Figure 20-5 Outputting something similar ten times
Solution Without a Loop
Again, you can start with a solution without a loop to appreciate the importance of loops.
Here’s the code:
static void Main(string[] args)
{
// Output
Console.WriteLine("My main to-do list:");
Console.WriteLine("1. To learn");
Console.WriteLine("2. To learn");
Console.WriteLine("3. To learn");
Console.WriteLine("4. To learn");
Console.WriteLine("5. To learn");
Console.WriteLine("6. To learn");
Console.WriteLine("7. To learn");
Console.WriteLine("8. To learn");
Console.WriteLine("9. To learn");
Console.WriteLine("10. To learn");
// Waiting for Enter
Console.ReadLine();
}
Solution Using a Loop
Loops can efficiently solve this type of problem. Actually, you will find yourself incorporating loops to repeat similar activities more often than to repeat precisely the same ones.
static void Main(string[] args)
{
// Output
Console.WriteLine("My main to-do list:");
for (int taskNumber = 1; taskNumber <= 10; taskNumber++)
{
Console.WriteLine(taskNumber.ToString() + ". To learn");
}
// Waiting for Enter
Console.ReadLine();
}
Discussion
The following sections discuss the program.
Control Variable
The core of the solution is to use the value of the loop’s control variable inside its body. In this program, you name the variable taskNumber, and you use its value for output.
This is how you achieve displaying 1 in the first passage of the loop, 2 in the second passage, and so on.
Check the situation yourself using your debugging tools.
The Loop Starts at 1
The previous exercise (repeatedly throwing a die) used the loop with its control variable running from 0 to 19. Contrary to that, this time it was more convenient to start at 1 rather than at 0. This change also caused the loop condition to change. You used a “less than or equal” test rather than a “less than” one.
Summary
The chapter introduced you to the topic of loops, which are a mighty programming tool allowing you to specify repetitions of the same or, more often, a similar activity.
For loops, C# offers several programming constructs; you learned about the most fundamental for loop in this chapter. In the code, the for loop consists of a header controlling the loop and a body consisting of the statements to be repeated surrounded with braces. The header itself consists of three parts separated by semicolons,
The initializer is the statement to be executed once before the loop starts “revolving.”
The loop condition is the condition evaluated before each turn of the loop. If it is fulfilled (i.e., evaluated to true), another round of statements of the loop’s body is executed. If it is not fulfilled (i.e., evaluated to false), the loop is terminated, and the program’s execution continues to the statements after the loop.
The iterator is the statement to be executed after each turn of the loop.
To get a deeper understanding of how for loops work, definitely use debugging tools like stepping and memory inspection.
The for loop is most often controlled by a variable working more or less like a counter of loop turns. This variable is called the control variable. In the last task, you learned how to use the value of the control variable also inside the loop’s body.