The for loop
For loop is an entry controlled loop, where the condition is checked first before entering into the loop body, it is the simplest way to write a loop structure.
Syntax
for (<Initialize>; <Condition>; <Increment/Decrement>) { // body of the loop }
Simple example
In this example, we are printing a number from 0 to 9 with prefix “Item”. So it will print something like – Item 0, Item 1, Item 2… Item 9
public class SimpleExample { public static void main(String[] args) { for(int i = 0; i < 10; i++) { System.out.println("Item " + i); } } }
Points to note
- As the loop begins initialization happens.
- Initialization usually consists of a single variable declaration, but it can have one or more statements separated by commas.
- The scope of the declared variable in for statement is limited to the loop body.
- Condition is evaluated every time and if it evaluated as true then control enters into loop body.
- The loop terminates when the condition is evaluated as false.
- The Increment/Decrement happens after each iteration of the loop.
- Increment/Decrement expression can have multiple statements separated by commas.
Flow diagram
Odd numbers example
This is an example program that demonstrates how to use for loop. In this program, we are printing all the odd numbers up to N.
The logic for printing odd numbers are pretty simple and straight forward, we only need to check if the number is not divisible by 2. If the number is not divisible by 2, then we have to print it.
import java.util.Scanner; public class OddNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Take input from user. System.out.print("Print all odd numbers till : "); int n = scanner.nextInt(); System.out.println("\nOdd numbers from 1 to " + n + " are : "); // For loop example for(int i = 1; i <= n; i++) { // Check for odd or not. if((i % 2) != 0) { System.out.print(i + " "); } } } }