Java: How to use the For Loop

What is the For Loop?

The for loop prints out a piece of code in the brackets if the code in the parenthesis is true.

The code below shows how to make a for loop.

package com.lessons;

public class ForLoop {
     public static void main(String[] args) {
          //  The variable test = 0;

          //code in brackets gets executed only if test is less than 91;

          //test + 1 every loop
          for(int test = 78; test < 91; test++) {
System.out.println(“It is ” + test + ” degrees fairenheit today”);
}
}
}

How the Code Works

The loop says for (int test = 78; test < 91; test ++)  {

System.out.println (“It is” + test + ” degrees fairenheit today”);

}

int test is defined in the parenthesis as 78. Then it says test < 91. This means that if test is less than 91, the code in the brackets will get executed. The last part says test++. This means that whenever the code gets executed, add 1 to test.

This is how it works:

 

int test = 78.

Is 78 < 91? Yes it is. The code will get executed and ” It is 78 degrees fairenheit today” will get printed.

Add one to test.

 

int test now = 79.

Is 79 < 91? Yes it is. The code will get executed and ” It is 79 degrees fairenheit today” will get printed.

Add one to test.

 

int test now = 80.

Is 80 < 91? Yes it is. “It is 80 degrees fairenheit today” will get printed.

Add one to test.

 

int test now = 81.

Is 81 < 91? Yes it is. The code will get executed and ” It is 81 degrees fairenheit today” will get printed.

Add one to test.

 

int test now = 82

Is 82 < 101? Yes it is. “It is 82 degrees fairenheit today” will get printed.

Add two to test.

 

It will keep going until test is equal to 91, Then the for loop will stop because 101 is not < 101.

 

At the end, the following will get printed on the screen:

It is 79 degrees fairenheit today

It is 80 degrees fairenheit today

It is 81 degrees fairenheit today

It is 82 degrees fairenheit today

It is 83 degrees fairenheit today

It is 84 degrees fairenheit today

It is 85 degrees fairenheit today

It is 86 degrees fairenheit today

It is 87 degrees fairenheit today

It is 88 degrees fairenheit today

It is 89 degrees fairenheit today

It is 90 degrees fairenheit today

Leave a comment