for loop java
- In computer science, for loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly.
- In Java, the for-each loop is used to iterate through elements of arrays and collections.
Syntax
for(initialization; condition; iteration) { statement sequence }
java for loop
- The initialization is usually initializes and/or declares variables and executes only once.
- The condition is a Boolean expression that determines whether or not the loop will repeat.
- The iteration expression defines the amount by which the loop control variable will change each time the loop is repeated.
- The for loop will continue to execute as long as the condition tests true.
- Once the condition becomes false, the loop will exit.
java for loop example
You Can Display a text number of times.
class Main { public static void main(String[] args) { int n = 3; // for loop for (int i = 1; i <= n; ++i) { System.out.println("Hello I'm text" + i); } } }
Hello I'm text1 Hello I'm text2 Hello I'm text3
Once the condition becomes false, the loop will exit, and program execution will resume on the statement following the for.
for loop in java
Print a number
class Main { public static void main(String[] args) { int n = 3; // for loop for (int i = 1; i <= n; ++i) { System.out.println(i); } } }
1 2 3
for loops java
The for loop can proceed in a positive or negative fashion, and it can change the loop control variable,. For example, the following program prints the numbers 10 to -10, in decrements of 5.
java for loops examples
class DecMe { public static void main(String[] args) { int x; for (x = 10; x > -10; x -= 5) System.out.println(x); } }
10 5 0 -5