Java for loop
A for loop is a control flow statement in programming that allows you to repeatedly execute a block of code a specified number of times or until a certain condition is met. The basic structure of a for loop includes:
- an initialization statement (e.g. setting a loop counter variable)
- a termination condition (e.g. when the counter reaches a specific value)
- an increment/decrement statement (e.g. increasing or decreasing the counter each iteration)
Syntax for a for loop can vary across programming languages, but a common form looks like this:
for (initialization; termination; increment/decrement) { // code block to be executed }
for (int i = 1; i <= 10; i++) { System.out.println(i); }
- int i = 1: the loop counter i is initialized to 1
- i <= 10: the termination condition checks if i is less than or equal to 10
- i++: the increment statement increases the value of i by 1 after each iteration
- System.out.println(i): the code inside the loop body that prints the value of i to the console each iteration.
Here's an example of a for loop in Java that prints the even numbers from 2 to 20:
for (int i = 2; i <= 20; i+=2) { System.out.println(i); }
Explanation:
- int i = 2: the loop counter i is initialized to 2
- i <= 20: the termination condition checks if i is less than or equal to 20
- i+=2: the increment statement increases the value of i by 2 after each iteration
- System.out.println(i): the code inside the loop body that prints the value of i to the console each iteration.
for (int i = 10; i >= 1; i--) { System.out.println(i); }
- int i = 10: the loop counter i is initialized to 10
- i >= 1: the termination condition checks if i is greater than or equal to 1
- i--: the decrement statement decreases the value of i by 1 after each iteration
- System.out.println(i): the code inside the loop body that prints the value of i to the console each iteration.