For Loops
For Loops
- The for loop, like the other looping statements, repeats while a condition is true.
- The for loop is a pre-test loop like the while loop.
- The for loop is unique, in that it contains a built-in mechanism for counting.
- A for loop is used when you know in advance how many times you want your loop to execute.
Basic Syntax
The For Loop header has three components:
1. The Initialization Statement:
The initialization statement(s) declares and assigns the initial value of the variable used in the Boolean expression.
2. The Boolean Expression:
A Boolean expression related to the initialize statement(s). Evaluates to true or false. A value of false will terminate the loop.
3. The Update Statement:
Example:
1. The Initialization Statement:
The initialization statement(s) declares and assigns the initial value of the variable used in the Boolean expression.
2. The Boolean Expression:
A Boolean expression related to the initialize statement(s). Evaluates to true or false. A value of false will terminate the loop.
3. The Update Statement:
- The update statement is used to modify the variable after each iteration through the block.
- This can be any assignment operator.
Example:
What is the output?
There can be some variation of the FOR loop
Practice:
What is the output to the following:
There can be some variation of the FOR loop
- The update statement can be any assignment operator
- The update statement can increase/decrease by any amount
Practice:
What is the output to the following: