Counted Loops

advertisement
Control Statements – Counted Loops
Until now each C# statement was executed from top to bottom within the source code. Now we
want to tackle problems where we wish to repeat statement or take control of the order of
execution.
There are many different control statements. The first we will use is a counted loop.
A loop is a programming construct that lets you repeat a block of code many times.
A counted loop is a loop that has a specific number of iterations (repetitions).
Counting to 10 With a For Loop
But when C# programmers make loops, they often prefer to use a special kind of loop called a
for loop. The for loop syntax puts all the loop variable stuff (select, initialize, test, and change)
on one line, and then the loop body comes afterwards. This may seem strange at first, but many
people prefer to see exactly how the loop works up front. Here is the same code as a for loop
Select, Initialize
Test
Change
for (int counter=1; counter<=10; counter=counter+1)
{
MessageBox.Show(counter);
START
}
MessageBox.Show("done")
counter  1
How to Read a For Loop
1. The select and initialize statement happens once at the
beginning of the loop, and then never again.
2. The test statement happens before each pass through the NO
loop body.
3. The change statement happens at the end of the loop body
(even though it’s at the top of the loop).
Flow Charts for a For Loop
The flow chart for both of the loops on this sheet is exactly the
same. They both do the initialization, then the test, and then do
the change at the end of the loop before looping back to the test.
counter <= 10?
YES
Print counter to
screen
counter  counter + 1
Print “done”
END
Exercises
1. Write a console application that will ask a user for the number of positive integers to
sum. Assume the first integer value is 1 and the user-supplied final integer is provided by
the user. Display the sum of these integers to the user using a counted loop to perform the
calculation.
Example: User enters the value 4.
The program provides the value of 4+3+2+1 = 10 to the user.
2. Write a different version of the first exercise using the following formula:
𝐍(𝐍 + 𝟏)
𝟐
N represents the maximum integer to sum in the series.
a) Which of the 2 techniques is faster?
BONUS: Create a combined program that records timings for very large sums to
prove your point.
3. Create a console program that will ask the user for the side length of a right angle triangle
and then display a triangle using the asterisk (*) character.
Example: User enters 5
The program displays the following triangle.
*
**
***
****
*****
Download