Java for Loop: Syntax and Usage Explained
Table of Content:
For Loop in Java
Loop statements are an important part of any programming language. Java for loops is very similar to Java while loops and do while loop in that it continues to process a block of code until a statement becomes false. Java supplies a powerful assortment of loop constructs. A for loop has a concise syntax for writing loops.
The traditional for loop in Java is the most common form of iteration, especially when you need to execute a block of code a fixed number of times or when you need control over the index of elements you're iterating over.
Syntax
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; Statement(s); }
for (i = initialValue; i < endValue ; i++) { // Loop body; Statement(s); }
Similar Syntax while loop
i = initialValue; // Initialize loop control variable while (i < endValue) { // Loop body ... i++; // Adjust loop control variable }
Similar Syntax do while loop
i = initialValue; // Initialize loop control variable do{ // Loop body ... i++; // Adjust loop control variable }while (i < endValue) ;
flowchart of the for loop
A for loop performs an initial action once, then repeatedly executes the statements in the loop body, and performs an action after an iteration when the loop-continuation-condition evaluates to true
Example of for Loop
class ForLoopExample { public static void main(String[] args) { int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Ansari Academy!"); } } }
Output:
Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! Welcome to Ansari Academy! . . . . . .
Example of for Loop
/* Demonstrate the for loop. Call this file "ForLoopExample.java". */ class ForLoopExample { public static void main(String[] args) { for(int i=1;i<=10;i++){ System.out.println(i); } } }
Output:
1 2 3 4 5 6 7 8 9 10 Press any key to continue . . .
Example of for Loop
/* Demonstrate the for loop. Call this file "ForLoopExample.java". */ class ForLoopExample { public static void main(String[] args) { for(int x = 15; x < 25; x = x + 1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }
Output:
value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 value of x : 20 value of x : 21 value of x : 22 value of x : 23 value of x : 24 Press any key to continue . . .