Desktop Applications in C#
Flow Control: Looping
Chewei Liu
Outline
Looping
While
For
Practice
Lab
Why loops?
The idea behind repetition
4
Why Use A Loop?
Repeat instructions with many data sets
Repetition or iteration structures
Rich set of looping structures in .Net
While
for
foreach statements
4
5
Using the while Statement
Simplest and most frequently used loop
while (conditional expression)
statement(s);
Expression – sometimes called loop condition
Returns a Boolean result of true or false
No semicolon after the conditional expression
Null body→ empty bodied loop→ infinite loop
Enclose multiple statements for body in { }
5
6
While Statement
Pretest
If the conditional expression evaluates to true, statement(s) performed
If the conditional expression evaluates to false, statement(s) skipped
6
7
A common example: Counter-Controlled Loop
Loop control variable
Variable simulating a counter
Initialized
Conditional expression designed so that you can exit the loop after a certain number of iterations
Increment counter with each iteration
Otherwise, infinite loop
7
8
Counter-Controlled Loop Example
Code Sequence
1.
number = 1
number < 4 -> (1 < 4) -> true
Write 1
Number++ -> number = 2
2.
number < 4 -> (2 < 4) -> true
Write 2
Number++ -> number = 3
3.
number < 4 -> (3 < 4) -> true
Write 2
Number++ -> number = 4
4.
number < 4 -> (4 <4) -> false
Leave loop
8
Adding the first 10 numbers
Code Sequence
1.
counter= 1
counter < 11 -> (1 < 11) -> true
sum = 0 + 1 = 1
counter++ -> counter= 2
2.
counter < 11 -> (2 < 11) -> true
sum = 1 + 2 = 3
counter++ -> counter= 3
3.
counter < 11 -> (3 < 11) -> true
sum = 3 + 3 = 6
counter++ -> counter= 4
…
10.
counter < 11 -> (10 < 11) -> true
sum = 45 + 10 = 55
counter++ -> counter= 11
11.
counter < 11 -> (11 < 11) -> false
Leave Loop
Practice: While loop
Use “while loop” to calculate the product of the first 6 numbers
For loops
More control in your loops
12
For Loop
Pretest form of loop (like the while)
Considered specialized form of while statement
Usually associated with counter-controlled types
Packages initialization, test, and update all on one line
General form is:
for (statement; conditional expression; statement)
statement;
Interpreted as:
for (initialize; test; update)
statement;
12
13
For Loop
13
Let’s look at an example:
Practice: While & For loop
Use “for loop” to calculate the product of the first 8 numbers
Lab 11 (Balance Calculator)
Get current balance, interest rate, and future balance from users (I wrote the code for you).
Use “While-Loop” to calculate number of years to achieve the future balance.
Use “For-Loop” to show the balance for each year.
Do While (Advanced Content)
Learn this concept yourself
Very similar to While loops
18
Do…While Statements
Posttest
General form
do
{
statement;
}
while ( conditional expression);
18
Do while example
Difference between While and Do-While
While
Do While
sum: 0 (while example)
sum: 11 (do while example)
/docProps/thumbnail.jpeg