Control Statements
Loops
for
The syntax of the for loop
for(initializationExpression; booleanExpression; incrementExpression) { statements }
How to code for loops
- A for loop is useful when you need to increment or decrement a counter that determines how many times the loop is executed.
- Within the parentheses of a for loop, you code:
- an initialization expression that gives the starting value for the counter
- a Boolean expression that determines when the loop ends
- an increment expression that increments or decrements the counter
- The loop ends when the Boolean expression is false.
- You can declare the counter variable before the for loop. Then, this variable will be in scope after the loop finishes executing.
A for loop that stores the numbers 0 through 4 in a string
With a single statementWith a block of statementsString numbers = ""; for (int i = 0; i < 5; i++) numbers += i + " ";String numbers = ""; for (int i = 0; i < 5; i++) { numbers += i; numbers += " "; }
A for loop that adds the numbers 8, 6, 4, and 2
int sum = 0; for (int j = 8; j > 0; j -= 2) { sum += j; } A for loop that calculates a future value for (int i = 1; i <= months; i++) { futureValue = (futureValue + monthlyPayment) * (1 + monthlyInterestRate); }