For Loops - Brief Review
Created 2 years ago
This is intended as a brief review of how a for loop works in C#. There are a few easy review questions at the end.
Email this Mix
Slide 1 - For Loops - C#
Slide 2 - Three Essential Parts
- Set up control conditions
- Check control conditions for completion
- Change control values
- All loops requires these steps!
Slide 3 - Set Control Conditions
- What are the initial conditions?
- Set initial value(s) for loop control variables
- Make sure everything is at a known state
Slide 4 - Check Control Conditions
- Are we done yet?
- Is the counter at maximum value?
- Is the “completed flag” set?
Slide 5 - Change control values
- Avoiding the dreaded infinite loop!
- Get new input from user or other source
- Other changes depending on type of loop
- Increment (decrement) counter
Slide 6 - For Loop
- A counter controlled loop
- Used when we know how many times we want the loop to execute
- An alternative to the while Loop
Slide 7 - For Loop Example
- for (int i = m; i < n; i++)
- All three steps in a single line
Slide 8 - Details
- for (int i = 1; I < 5; i++)
- “i” is initialized to 1
- “i” is tested against the
- stop value 5
- Increment i
Slide 9 - Altering the Counter Variable
- The value of the counter variable should not be altered within the body of a for loop.
- Doing so might cause the loop to repeat indefinitely or have an unpredictable number of repetitions.
- So Don’t do it!
Slide 10 - Let’s See What You’ve Learned