Understanding Loops in Java: Java for Loop
Tags: java, forloop, loops, learning
Published: 2022-04-05 17:47:37


Years back, while I was learning Java Programming, I was stucked at learning Loops in Java. Loops sometimes, can be frustrating and difficult to learn, most especially when you don't get the right resources for your learning.
 
In this article, I will explain Loops in Java, in the most simplified and comprehensive way, with easy to understand terms, and at the end we will build a simple project using a for Loop. 

Requirements:

- Understandings of Java Variable declaration.
- Understandings of Java expression.

> Because of the need to explain java loops comprehensively, this article will be divided into three.
1. For loop
2. While loop
3. Do while loop.
each will have a different article.

**Concept of Loops**

Loops is a broad phenomenon in the field of Computer science. Basically, every functioning Programming language has a support for Loops. Loops simply means doing something repeatedly. From the programming perspective, Loops means, repeatedly carrying out an instruction on the basis of some conditions. These conditions are what prevents a loop from been infinite. The usefulness of every loops makes us to write redundant-free codes and easy to understand codes.

Think for a moment, if you were ask to print "Hello, John" in the console 10 times, how will you get that done?
There are basically one option you will use, You are definitely going to keep rewriting "Hello, John" Untill it count up to 10

_for example:_

```
public class Main {
	public static void main(String[] args) {
    System.out.println("Hello, John");
    System.out.println("Hello, John");
    System.out.println("Hello, John");
    System.out.println("Hello, John");
    System.out.println("Hello, John");        System.out.println("Hello, John");
    System.out.println("Hello, John");     System.out.println("Hello, John");     System.out.println("Hello, John");
    System.out.println("Hello, John");
    }
}
```
While this method may result to the expected output, thus, it's been regarded inefficient! in Programming you must not repeat yourself, the above lines of codes looks unprofessional. However, we can print same result in an entirely different way, more efficient and less lines of code:

_For example:_
```
import java.util.*;
public class Main{
	public static void main(String[] args) {
		for(int i = 0; i<=10; i++){
            System.out.println("Hello, John");
        }  
    }
}
```
You could see the difference, With loops you can write less lines of code with better result, and it can be helpful in times of debugging.

**Java Loops**

Loops in java is further divided into three,
1. For Loop
2. While Loop
3. Do...While Loop.

**For Loop**
The for Loop is used to repeat a statement until a condition is met. It makes use of a counter/index, which is always incremented or decremented at the end of a statement each time the loop run. The essentiality of this index or counter is to meet a condition.

_The basic syntax of Java for Loop is:_

```
for(initialization; test; increment){
//Some statements
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jkm4f14szthyf98ft4k.jpg)
_lets understand each parameter in the for loop__

**Initialization:**The initialization is the first stage of every for loop and its indicates the starting point of any for loop. it's usually called a counter or an iterator or index. The initialization is usually a variable, once the statement in the loop is executed, the counter is incremented.

If you're iterating through each element in an array, then the counter will be equals to 0, this is because, arrays starts from 0 index, Sometimes, you might want to initialize the counter starting from 1, it all depends on what you're iterating.

**Test:** This is a boolean expression, that it's returned value is a determinant to terminate the loop or continue executing the statement, the test return value must either be true or false. If false: the loop terminate,  if true, the loop continue executing, until it returns false.

_for example_
In ensuring that a loop execute a statement 5 times, the counter must be checked to ensure that when it is equals to 5 it should be terminated.

```
i < = 5
```
Once the counter becomes equals to 5 the loops terminate.

**Increment:**This is the basis of the test return value, it is an expression that is meant to call the loop to an end, once the statement in the for loop runs, the increment takes into action by either increasing the counter or decreasing the counter.
```
i++ or i--
```

The counter is being incremented.

Here is an explanation of the flow of the for loop. the first stage is the initialization, where by a counter variable is declared and initialize. At the second stage, the loop is checked, if it returns true, it run the statement within the for loop, and i is incremented, the loop run again as long as the test keep returning true.

_Let's take an example_
You remember our "Hello, John" program?

Let's try to print "Hello, John" with the for loop with explanation. Hello John is to be printed 10 times.

```
import java.util.*;
public class Main {
	public static void main(String[] args) {
		for(int i = 1; i<=10; i++){
            System.out.println("Hello, John");
        }  
    }   
}
```

First i is initialize to 1;
Second i is checked if it less than or equals to 10, currently `i is 1` , so the condition returns true;
Third,  "Hello, John" is printed once in the console
Fourth, i is incremented, i now is 2;

The loops runs again, now i is 2,
Second i is checked if it less than or equals to 10, currently `i is 2` , so the condition returns true;
Third,  "Hello, John" is printed twice in the console
Fourth, i is incremented, i now is 3;

It keeps going untill when i becomes 10, the condition is checked if i is equals to 10,and currently i is equals to 10, which makes the test to return value of false, at this stage the for loop is terminated.

**Break statement with for loop**

Once a break statement is called within a loop it forcefully terminate the loop, normally a loop is meant to stop once the condition no longer return true. But sometimes we would want to break from the for loop when certain condition has been met.

```
for(int i = 1; i<=20; i+=2){
System.out.println(i);
If(i == 20){
break;
}
}
```

In the above program, we are trying to print out the even numbers between 2 and 20, but we would like to stop at 12. The if statement checks if the i is equals to 12, if true the program terminate leaving the other iterations.

**Continue statement with java for loop**

Sometimes you might want to forcefully break out from a for loop, at another time you need something entirely different, you probably need to skip an iterator, then continue with the rest, this can be done using the `continue` statement.

Let come back to our even program, but this time, we will like to skip the even number 12.
```
for (int i = 2 ; i<=20 ; i+=2)
        {
            if(i == 12){
                continue;
            }
       System.out.println(i);
    }
```

Once the loop get to 12, it skip that particular iterate and continue with the remain interations.

**For Loops can be decremented**

Since the beginning of this article, we have been incrementing the counter, the counter can also be decremented using the decrement operator. Using the decrement operator requires some changes in both the counter initialization and the condition.
```
for ( int i = 20 ; i >=1  ; i--)
        {        
            System.out.println(i);
        }
```

In the program above, we are trying to count down from 20 to 1, so we used the `i-- `operator

**For Loops can be nested**

A for loop can iterates inside another for loop, when you place a for loop inside another for loop, you are directly creating a nested loop. In nested for loop the inner loop must complete it iteration cycle before moving to the next outer loop.

_Format of a nested for loop_
```
//Outer Loop
for ( initialization; test ; increment)
        {
 //Inner Loop
for(initialization; test; increment){
                //Some statements
           }
       } 
```
_take for example_

```
for(int i = 1; i<= 5; i++)
    {
      //inner loop
      for(int j = 1; j <= i; j++)
      {
        System.out.print( "* " );
      }
      System.out.println(); 
```
**Output**

```
*
* *
* * *
* * * *
* * * * *
```
**Scoping in Java for loop**

Throughout this article we have been declaring and initializing the counter variables between the for loop brackets, making it a local variable, which implies non-accessibility outside the for loop block. Sometimes we might be writing a program where we need to access the value of the counter value, this method may not work.
_for example_
If we try to run the following code we will get an error

```
for ( int i = 1 ; i <=20  ; i++)
        {
                 
        }
     System.out.println(i);
```
The error:

```
Error: i cannot be resolved to a variable
```
What this error means is, the variable `int i = 1  ` cannot be visible out the scope of the for loop. However to make this code run, you are certainly going to declare the `int i  ` outside the scope of the for loop.

```
  int i;
  for ( i = 1 ; i <20  ; i++)
        {
                 
        }
     System.out.println(i);
```
Now the value of i can be visible from outside the scope of the for loop.
Output:

```
20
```
**Infinite for loop**
Infinite for loop is type of loop were it condition always return true, and can never be terminated.
_for example_

```
for ( int i = 1 ;  ; i++ )
        {
     System.out.println( i );
        }
```
In the above code the condition statement never return false, and therefore `int i = 1` will keep incrementing, until you force the loop to stop, by either exiting the compiler, or rebooting your computer😁.

But sometimes we can set a condition for infinite loop, so that when that condition is met, out loop will terminate.
```
for ( int i = 1 ;  ; i++ )
        {
     System.out.println( i );
     if(i == 12){
     break;
     }
  }
```
In the above program, we are trying to check the condition at runtime, so once the loop get to `i = 12` the loop terminate.

**Ganging up the for loop**
Sometimes we may be working on more complex program, and there is need to make multiple initializations and increment.
```
int i, j;
		for ( i = 0, j=10; i<=j; i++, j--)
        {
            System.out.println("i "+i+":"+"j "+j);
        }
```
When you need to run this kind of program, multiple initialization and increment must be separated by a comma.

**Project time**
At the beginning of this article I said we are going to build a project using java for loops:

> The project we are going to build using the Java for loop is a guessing game, in this guessing the user will be given 10 trial the to guess the right number between 1 and 10, if the user guess it correct `A congratulations message will be printed on the console`. We will be using the Java for loop to iterate the 10 time the user is meant to Guess.
.

**Code snippet.**

```
import java.util.*;

public class Main
{
    //scanner class for accepting inputs
	static Scanner input;
    /*variable declaration for the number of times
    the user has guess, the second variable is the 
    variable declaration that will hold the random number
    value
    */
    static int count, randomNumber;
    //a boolean to check if the user has won
    static boolean hasWon;
	public static void main ( String[] args )
    {
        input = new Scanner( System.in );
        //Asking the user if he is ready to play the game
        System.out.println( "Do you want to begin the game?\n" +
                           "1. Yes\n" +
                           "2. No" );
        //variable for collecting the user response
        int option = input.nextInt( );
        //validatinf if the use choosed 1
        if ( option == 1 )
        {
            //if the use choosed one, then we begin the game
            System.out.println( "Welcome to guess world\n" +
                               "You have only 10 trials go guess the right number" );
            //processing the random number value
            randomNumber = (int)Math.floor(Math.random()*10+1);
            //Asking the user to Guess a number between 1 and 10
            System.out.println("Guess a number from 1 - 10");
            
            //Looping through from 1 - 10
            for(int i = 1; i<=10; i++){
                //At each iteration the user is asked to input a guess
                int userGuesses = input.nextInt();
                //If the guess is correct
                if(userGuesses == randomNumber){
                    //haswon is set to true
                    hasWon=true;
                    System.out.println("Congratulation, you guessed the right number at count: "+count);
                //If guess is greater than the random number
                }else if(userGuesses>randomNumber){
                    System.out.println("Oops! Try a lesser number");
                    //haswon is set to false
                    hasWon = false;
                //If guess is lesser than the random number
                }else if(userGuesses<randomNumber){
                    System.out.println("Oops! Try a greater number");
                    //has won is set to false
                    hasWon = false;
                }
                //At the end of each count, the count variable is incremented
                count++;
                
            }
            //check if haswon is false
            if(hasWon == false){
                System.out.println("Trial exceed 10, the guess is "+randomNumber);
            }
            
       //if the user chooses 2, then the game is going to be exited
        }else{
            System.out.println("Guess game exiting...");
        }
       
    }

}

```
**Conclusion**
For loop is an important feature in every Programming language, the importance of for loop make it necessary to always use it while building advance programs. By now you should have a brief concrete understanding of what java for loop is, how to use it, manipulatingg it etc.