for Loop
In this lesson, the concept and implementation of for loops and nested for loops in Java is explained.
We'll cover the following...
for loop: syntax
The for
loop is a loop that lets a programmer control exactly how many times a loop will iterate.
The syntax is as follows:
Press + to interact
for (expression for initialization ; expression for testing ; expression for updating) {//body}
Here is an example of how the for
loop works:
Press + to interact
class Loops {public static void main(String args[]) {for (int i = 0; i < 10; ++i) {// for loop iterates 10 timesSystem.out.println("value of i = " + i);}}}
Take a look at the illustration below to understand the code above more clearly.
The for
loop code above and the while
below are more or less equivalent.
Press + to interact
class Loops {public static void main(String args[]) {int i = 0;while (i < 10) // while loop runs till i is less then 10 just like in for loop{System.out.println("value of i = " + i); //prints value of ii++;}}}
What does the for loop do?
...