· Define new terms
· Describe the reasons for repetition in a program
· Explain the different parts of a loop
· Identify the different ways to program loops
· Describe how to select the best loop for a task
Computers are good at repetitious tasks. A computer will count, repeat a series of steps many times, or do the same thing to a number of different objects without losing track of the process.
The function of making a computer repeat things, with or without minor changes, is through a loop. All loops have three primary stages.
· Initialization
· Comparison
· Change
Some loops must be clearly and deliberately setup by the programmer. Other loops use syntax that uses features that are included in the language to handle some of these stages.
Initialization involves setting up the loop. One or more variables will be used to control the loop. This kind of variable is called a loop control variable. The starting values of these loop control variables are set as part of initialization. Variables or constants that determine when the loop ends are set during initialization. Some loops must also be initialized with information about how the loop control variables will be changed.
Comparison is the part of the loop that determines if the loop should stop. The computer needs to check the loop’s progress, what the values of the loop control variable or variables are, and compare that with the ending values defined during initialization.
Change involves changing the value of the loop control inside the loop. If the loop control variable is never changed then the comparison always determines that the loop should continue. A loop that never ends is called an infinite loop. Infinite loops can happen when a programmer makes a simple mistake like forgetting to change a loop control variable.
A careful programmer checks their loop before running the program. Infinite loops can be very difficult to stop. Occasionally, drastic measures, such as restarting the computer, must be taken to escape from infinite loops. It is a good idea to save your program before running it if there is a new or changed loop involved.
The for loop holds all three stages of a loop in a single statement. The key word for starts the statement and is followed by a set of parentheses. Separated by semi-colons are the initialization, comparison and change statements for the loop.
The first section sets the initial value of the control variable. This variable may be declared in the statement itself, as in the example below, or it may be a variable that was previously declared. This section may even be empty is the loop control variable has been declared and set in earlier code. This is not a good practice because it can be confusing and may make it hard to follow the flow of the code.
The second section holds the comparison. The comparison is a Boolean expression like the ones used in an if statement. This expression usually involves the loop control variable but may involve other objects. as long as this expression evaluates to true the loop will continue executing.
The third section holds the formula for changing the loop control variable. For a counting loop, this statement is often a simple increment such as the one in the example below.
for(int k = 0; k < 10; k++)
{
Console.WriteLine("Counting {0}",k);
}
Any statement that changes one of the values in the comparison expression can be used in the last section.
A for loop can be specified without any statements in the parentheses, as in the example below.
for(;;)
This loop will run without stopping. This is called an infinite loop. There are some cases where an infinite loop is desired but generally, a program should have a way to exit any loop. C# does have a statement that can be used to exit a loop without the expression in the for statement evaluating false. This statement is called the break statement.
The break statement consists of the single word break. When the break statement executes the loop is exited immediately and the program continues with the first statement after the loop. The break statement is often paired with an if statement as in this example.
for(int k = 0;k < 10;k++)
{
Console.WriteLine("Counting {0}",k);
if (k > 5) break;
}
Console.WriteLine("The loop is ended.");
The continue statement can also be used to change the flow inside a loop. When a continue statement is executed the program moves to the bottom of the loop. This means that any statements after the continue statement will not be executed. The following code shows how this might work. The if statement checks for even values of k. If an even value is found then the program will skip to the bottom of the loop.
for(int k = 0;k < 10;k++)
{
if( k % 2 == 0) continue;
Console.WriteLine("Counting {0}",k);
}
This sample is not the most efficient way to print the odd numbers from 1 to 9 but serves as an example. The code below does the same thing more efficiently.
for(int k = 1;k < 10;k+=2)
{
Console.WriteLine("Counting {0}",k);
}
The continue statement is useful for handling infrequent interruptions to the flow of the program.
For loops are known as definite loops because the number of iterations or times the loop will be executed has a specific value. A loop that increments the loop control variable from 0 to 9 will execute 10 times. The number of times a loop that start the loop control variable at the value in iMin and ends when it gets to iMax executes can easily be determined from the values in those variables.
Loops that are based on a number of variables may not run at all if the values of the loop are set before reaching the loop. In all cases though, the number of iterations is definite. There are other cases where a program may execute until a specific condition is reached. These loops are indefinite loops. C# has several ways of programming these loops.
The while loop may be used as a definite or indefinite loop. The three stages of a while loop take place in separate statements. The variables are initialized before the while statement. The comparison operation is specified as a Boolean expression as part of the while statement. At some point inside the loop's block of statement the value in one or more of the variables in the while statement's expression must be changed. If the change does not take place in a sequence known at compile time then the loop is indefinite.
The following code shows a simple while loop.
Dice gameDie = new Dice (6);
int x = 0;
while (gameDie.Face != 3)
{
x++;
gameDie.Roll();
}
Console.WriteLine ("{0} rolls before a three",x);
This loop rolls a virtual die until it comes up a three. A counter, x, counts the number of rolls until the loop exits. The number of times the loop executes will change every time the program is run.
While loops can also be run a definite number of times. The while loop and the for loop in table 6-x below both do the same thing.
|
int k = 10; while (k >= 0) { Console.WriteLine("{0}",k); k--; } |
for(int k = 10;k >= 0; k--) { Console.WriteLine("{0}",k); } |
Table 6-x Sample Loops
The while loop requires more statements then a for loop but is also more flexible. A programmer must be careful to make sure that the loop control variable is changed, and changed correctly, in the body of the loop. Forgetting to change the loop control variable often results in an infinite loop.
While loops test at the top of the loop. This means that under some circumstances the loop will never execute. There are times when a programmer wants to make sure the loop executes at least once. Many menu driven programs have this requirement. A programmer can set initial values to guarantee that the loop executes but this requires more planning and, often, extra statements. A do/while loop checks at the bottom of the loop.
The loop block starts with the keyword do. The block ends with a while statement after the closing curly bracket. The while statement ends with a semi-colon after the Boolean expression. The while loop above will never execute if the face value of the die is three before the loop is reached. If you wanted to make sure the loop executed at least once you could use a do/while loop such as the one below.
x = 0;
do
{
x++;
gameDie.Roll();
} while (gameDie.Face != 3);
Console.WriteLine("{0} rolls before a three",x);
Loops are statements that are used to repeat a set of instructions. Loops always consist of an initialization step, a comparison step and a change step. The initialization step sets up the loop by setting initial values. The comparison step compares the current values used by the loop with the ending values for the loop to determine if the loop should continue. The values used by the loop must be changed somewhere in the loop or an infinite loop results. For loops change the loop control variable at the bottom of the loop as specified in the for statement. A programmer using a while loop or a Do/While loop must be careful to include program code that changes the loop control value inside the loop block.
For loops have a definite number of runs. The starting and ending values are known and C# counts a specific number of iterations. While loops may not always have a definite number of runs. Events outside the loop or random events may determine how many times the loop runs.
Some loops check values at the top of the loop. A top-checking loop may not execute at all if the ending condition is met before it runs. Loops that check at the bottom always execute at least one time.
1. Why would a programmer want a loop to check at the bottom of the loop?
2. How is a for loop setup to count down?
3. Why is a for loop called a definite loop?
4. Why is a while loop called an indefinite loop?
5. How does a program break out of a loop before it is finished?
6. What are the three main activities involved in running a loop?
7. What kind of loop is used to count an unknown number of activities?
8. What kind of loop is often used for menus?
9. What kind of a loop is needed when more then one variable must be checked to end or continue the loop?
10. What are the advantages of using a loop over cutting and pasting statements?
Definite loop Definite loops are defined to run a specific and finite number of times when their initial values are set.
Indefinite loop A loop whose ending is not known before it begins but will be determined by activity inside the loop.
Infinite loop A loop that never ends because the conditions that would end it never happen.
Loop control variable A loop control variable is a variable that is modified and checked by a loop to determine when the loop is done.
*
**
***
****
*****
******
*
**
***
****
*****
******
*
* *
* * *
* * * *
* * * * *
* * * * * *
******
******
******
******
******
* *
* *
******