Transcript CHAPTER 8

Lecture Set 5
Control Structures
Part D - Repetition with Loops
Objectives




Learn to write while, do-while, and
for loops to repeatedly execute statements
Learn the differences between these
three types of loops
Learn how to use loop break and
continue statements
This material is mostly review so it should
go quickly – you have seen most of it
already …
8/6/2013 9:01 PM
Introduction to Loops



These structures are part of nearly every
program written
Repetition is the most powerful feature of any
language – it is what computers do best (and
FAST!)
Learning how to construct loops with
appropriate loop parameters can make
difficult tasks seem easy (and code-able with
a short instruction sequence)
8/6/2013 9:01 PM
Executing Statements Repeatedly

Situations where repetition is used




Calculating payroll – a loop is used to calculate
the payroll for each employee
Reading multiple records in a file – a loop is
used to process each record in a file
Graphical animations – a loop is used to move
graphical objects about the screen
Accounting problems – depreciation and loan
balances are calculated repeatedly for multiple
periods
8/6/2013 9:01 PM
Types of Loops


Pre-test loops -- test a condition before
executing the statements in a loop
Post-test loops -- execute the loop's
statements first, and then test the loop's
condition
8/6/2013 9:01 PM
while and do-while Loops (Syntax) - 1

Do-While loop
do
{
[statements]
[break;]
[continue;]
[statements]
}
while (condition);
8/6/2013 9:01 PM
while and do-while Loops (Syntax) - 2

while loop
while (condition)
{
[statements]
[break;]
[continue;]
[statements]
}
Do While and Do Until Loops

The while loop tests the condition before
executing the statements in the body of a loop




The condition evaluates to a Boolean value and the loop
will continue repeating as long as the condition is true
The while loop will execute 0 or more times
The do-while loop tests the condition after the first
execution of the loop and will continue repeating as
long as the condition is true


(Syntax, continued)
The do-while loop will execute 1 or more times
When the condition becomes false, execution
continues with the statements following the loop
The break and continue statements will be
discussed at the end of this Lecture Set
7/17/2015 5:55 PM
Loops and Counters

A counter is a variable whose value increases
by a constant value each time through a loop


The constant value used to increment the
counter is typically 1 but does not have to be
A counter update takes the following general
form:




counter = counter + 1;
counter += 1;
counter++;
i -= 5;
// decreases the counter i by 5
7/17/2015 5:55 PM
Loops and Counters


(example)
Print the counting numbers 1 through 10 using
a while loop
Almost every loop has a loop control variable
(lcv) that is used to control the execution of the
loop
int counter = 1;
// lcv initialization
while (counter <= 10) // lcv test
{
Debug.WriteLine(counter);
counter += 1;
// lcv update
} // end while loop
7/17/2015 5:55 PM
Loops and Counters

(Example, continued)
Print the counting numbers 1 through 10
using a do-while loop
int counter = 1;
do
{
Debug.WriteLine(counter);
counter += 1;
}
while (counter <= 10);
7/17/2015 5:55 PM
The Role of an Accumulator

An accumulator is similar to a counter



An accumulator usually takes the following
general form:



An accumulator is updated each time the
statements in a loop execute
It can be used to calculate (accumulate) a total
accumulator = accumulator + value;
accumulator += value;
But we will see other forms of “accumulators”
as well – they are a powerful programming tool
7/17/2015 5:55 PM
Accumulator

(Example)
Store the sum of the counting numbers 1
through 10
int counter = 1;
int accumulator = 0;
while (counter <= 10)
{
Debug.WriteLine(counter);
accumulator += counter;
counter += 1;
}
7/17/2015 5:55 PM
Infinite Loops


A condition must ultimately occur causing a loop to
exit
Loops can be mistakenly written so that statements
execute indefinitely


These loops are called infinite loops
Infinite loop example (counter is always equal to 1):
int counter = 1;
while (counter <= 10)
{
Debug.WriteLine(Counter);
}
7/17/2015 5:55 PM
Nested Loops and Decision Structures





Loops can be nested, just as decision
statements can be nested
Loops can contain decision statements
Decision statements can contain loops
Both can contain nested structures
HOWEVER – it is generally a good idea to
avoid any heavy nesting of control structures,
especially when loops are involved


Complicates logic
Helpful to put nested loops in separate functions
7/17/2015 5:55 PM
Combining Loops and Decision Statements
(Example)

Determine whether a number is prime
// Simple-minded function to determine if a number is prime
private Boolean isPrime (int arg)
{
if (arg % 2 == 0) return false;
int count = 3;
while (count < arg)
{
if (arg % count) == 0)
return false;
count += 2;
} // end while loop
return true;
} // end isPrime
7/17/2015 5:55 PM
for Loops




(Introduction)
for loops execute statements repeatedly
We usually use a for loop in place of a
while loop when the iteration count (the
number of times the loop will execute) is
known in advance
for loops usually run more quickly than
comparable Do loops because they are
optimized
for loops are usually more readable than
equivalent Do loops (Why?)
7/17/2015 5:55 PM
For Loops (Syntax)
for (initialization; condition; update)
{
[statements]
[break;]
[continue;]
[statements]
} // end for loop
// next sequential statement
(See explanation on next page)
7/17/2015 5:55 PM
For Loop Sequence of Steps
(continued)
1.
The initialization expression assigns a value to a loop control
variable (lcv)
2. The condition normally compares the lcv to a loop termination
value
3. If the condition is true, the loop body is executed once
4. When loop body execution reaches the end (right) brace, the lcv
is updated and steps 2-4 are repeated
5. If the condition is false the loop terminates and execution
continues with the next sequential statement
Break and continue statements are discussed later in the Lecture Set
7/17/2015 5:55 PM
for Loops

(Example)
Print the counting numbers 1 to 10
for (int counter = 1; counter <= 10, counter++)
{
Debug.WriteLine(counter);
} // end for loop

OR, since the loop has a one-statement body
…
for (int counter = 1; counter <= 10, counter++)
Debug.WriteLine(counter);
7/17/2015 5:55 PM
Execution of a for Loop
7/17/2015 5:55 PM
Nested for Loops (Example)

Print a multiplication table
int factor1, factor2, result;
for (factor1 = 1; factor1 <= 10; factor1++)
{
for (factor2 = 1; factor2 <= 10; factor2++)
{
result = factor1 * factor2;
Debug.WriteLine(result.ToString() + “inner loop");
} // end inner loop
Debug.WriteLine(factor1.ToString() + “outer loop“);
} // end outer loop
7/17/2015 5:55 PM
Using the Step Keyword


Use the Step keyword to modify a counter's
value by a value other than 1
Example to decrement a counter by 5
int currentYear As Integer
for (currentYear = 2000; currentYear >= 1900; Step –5)
{
Debug.WriteLine(CurrentYear.ToString)
} // end for loop
OR use the following for loop header:
for (currentYear = 2000; currentYear >= 1900;
currentYear -= 5)
7/17/2015 5:55 PM
break and continue Statements



Can be used with any loop form
break causes the innermost loop that contains
it to exit immediately, sending control to the
first instruction that follows the loop (next
sequential instruction or nsi)
continue causes the innermost loop that
contains it to repeat immediately (effectively
sending control to the loop header so that the
expressions that control loop repetition can be
executed again)
7/17/2015 5:55 PM
The break Statement
(Example)
decimal monthlyInvestment;
decimal monthlyInterestRate;
int months;
decimal futureValue;
for (int i = 1; i<= months; i++)
{
futureValue = (futureValue + monthlyInvestment)
* (1 + monthlyInterestRate);
if (futureValue > 1000000.0)
{
MessageBox.Show("Future value is too large.",
"Future Value Overflow!");
break;
// break from or exit the for loop to nsi
} // end if
} // end for loop
// next sequential instruction (nsi)
7/17/2015 5:55 PM
The continue Statement
int sumNumbers = 0;
int sumBigNumbers = 0;
for (int i = 1; i <=6; i++)
{
sumNumbers += i;
if (i < 4)
{
continue; // to top of loop; increment and test i
} // end if
sumBigNumbers += i;
} // end for loop
7/17/2015 5:55 PM
The Implications of Long-running Loops

Some loops can run for hours



Display messages periodically in long-running
loops, or
Show a progress bar as the loop is running so
the user knows that progress is being made
Improve the performance of long-running
loops where possible

Move unnecessary statements to the outside of
a loop
7/17/2015 5:55 PM
Setting and Clearing Breakpoints
How to set and clear breakpoints
 To set a breakpoint, click in the margin indicator bar to the left of
a statement. Or, press the F9 key to set a breakpoint at the cursor
insertion point. Then, a red dot will mark the breakpoint.
 To remove a breakpoint, use either technique for setting a
breakpoint. To remove all breakpoints at once, use the Clear All
Breakpoints command in the Debug menu.
How to work in break mode
 In break mode, a yellow arrowhead marks the current execution
point, which points to the next statement that will be executed.
 To step through your code one statement at a time, press the F11
key or click the Step Into button on the Debug toolbar.
 To continue normal processing until the next breakpoint is
reached, press the F5 key.
7/17/2015 5:55 PM