Java For Loop

for loop is used to run a block of code repeatedly for a specified number of times, based on a condition. It is one of the most common control structures in JavaScript.


Syntax:

for (initialization; condition; increment/decrement) { 
  // Code to execute 
}


  • Initialization: Sets the starting value for the loop variable.
  • Condition: Specifies when the loop should stop (must evaluate to false to terminate the loop).
  • Increment/Decrement: Updates the loop variable after each iteration.


Basic For Loop
for (int i = 0; i < 5; i++) {
System.out.println("Iteration number:"+ i);
}

Try it yourself


Nested For Loop
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.print(" "+i*j);
}
System.out.println();
}

Try it yourself


Enhanced For Loop (For-Each Loop):

The for-each loop is used to iterate over arrays or collections without using an index. It's simpler and avoids potential errors with index handling.


Syntax:

for (dataType variable : arrayOrCollection) {
    // Code to execute
}
Example
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.