Chapter 02 Loop Summary
Loops
For loop - repeats when you know the number of times to repeat
for (statement to start the loop; condition that evaluates to true or false; statement to run when the loop repeats)
{
// do something
}What you need to know:
- loop control - know how to set up a loop to run a certain number of times
- scope - variables created in a loop are destroyed at the end of the loop
- only what is in the {} will repeat.
- to accumulate - initialize a variable before the loop, add to itself during the loop, and then print the total at the end of the loop
- tracing - be able to trace all variables in the program including the counter. Know that the first time through the loop it executes the starter statement, and every time following it executes the incrementing.) From this you can tell how many times a loop will run.
- inner loop - should not use same counter as outer loop; know what it is and how to trace it, but you will not have to construct one on the quiz.
FOR coding helps: (but not needed explicitly for the test)
- Don't put a semi-colon at the end of the for condition
- Remember to create the variable used to count the loop with an int statement somewhere in your program. (either in the for statement or before it)
- You can add to the counter between the brackets as well.
- After the first time through, the for loop does the "statement to run when the loop repeats" first, and then checks whether the condition fails.
- When the condition fails, it goes to the bottom bracket of the loop and continues on
- You can have loops inside loops
- Stopping when equal to a single number is dangerous - go with < or > instead when you can.
Loop Flow Charting:
Loop approach: (No need to memorize. Just figure out which approach works best for you)
Structure Summary: (You should know how to create each of these structures)
Theory Summary:
a