...

/

`for` or `while`, It Depends

`for` or `while`, It Depends

Learn which loop(`for` or `while`) to choose according to given situations in this lesson.

According to the situation, it depends whether we should use for loop or while loop statement.

while loop

Example: 1

In many cases, the while loop is the best remedy. Suppose, we want to take integer inputs from the user and give the output of the average value. While writing the code, we will decide how many times the user will type the value. In the following code, the user is restricted to giving five values.

Once the user reaches the range, the average will come out automatically. If you want to rerun the code, write java main in the terminal:

//code snippet to find the average of five numbers

import java.util.Scanner;

public class main {

    public static void main(String[] args) {

        final int listSize = 5;
        double valueOfSum = 0;
        int valueProcessed = 0;

        System.out.println("Please enter " + listSize + " numbers.");
        Scanner sc = new Scanner(System.in);
        while (valueProcessed < listSize){
            double yourNumber;
            yourNumber = sc.nextDouble();
            valueOfSum += yourNumber;
            valueProcessed++;
        }
        double averageOfYourNumbers = valueOfSum / valueProcessed;
        System.out.println("The average of given numbers " + averageOfYourNumbers);


    }
}

Code explanation

If we run the code, the user is ...