Loops

Loops are used when we want to repeat a certain portion of the code multiple times to achieve a purpose. For example, if we want to write a number-guessing game from (1-100) we will want to print out “Guess a number:” multiple times. Assume that the player is really unlucky and could only guess the number at the last try, we would need to do System.out.print 99 times in our program if we don’t use loop. However, with loops, we can reuse the System.out.print as long as the user doesn’t guess the correct number. There are two types of loops, a while loop and a for loop. Let’s talk about while loops first.

While loops

While loops are generally used when we don’t know how many times we want the code to execute, or we want the code to continue executing until a certain condition is met. The syntax for while loops is as follows:

           while(\"a boolean expression\") {
             // the body of the while loop.
           }
       

Similar to if statements, we can write the while loop without the curly braces, but only the statement following the while statement will be considered as the body. Let’s try to program the number guessing game described above. The below is our logic flow for coding this mini-game.

    1. Since we have no idea how many times the program should ask the user for input, that’s a hint that a loop might be in play, and it is a while loop. 2. The condition for the program to terminate should be when the user has the correct number, hence we will need a boolean variable to keep track of it. This variable serves as the condition for the while loop to exit. 3. In the body of while loop, we will need to ask the user for input, check if that inputs is correct. Update the boolean if the numbers match.
        public static void main(String[] args){
        int anwer = 37;                               // this will be our answer that is not visible to user
        boolean correct = false;      // this will keep track of if the user got the answer or not.
        Scanner in = new Scanner(System.in);                         // Scanner to get the user input
        while(!correct) {  //as long as correct is false, this while loop will continue on forever.
        System.out.println(“Guess a number”);
        int userIn = in.nextInt();                // read the user input as an int and store it.
        if (answer == userIn){                                                          //Compare the answers
        correct = true; 	  // update the condition if the answer matches
        }
        }
        System.out.println(“You got it”);
        }
do-while loop:

do-while loops is almost the same as a normal while loop, except that the program will execute the body of the while loop at least once. The syntax is as follows:

 do {
        // The body of the loop
        } while ( <a boolean expression>);
For loops:

For loops, all in all, is just a fancy while loop. It is generally used when you know how many iterations you want the loop to execute. For example, iterating through a String, printing out statements 10 times. The syntax is as follows:

        for ( <initializer> <condition> <update>){
            // body of the for loop.
            }
            

Initializer allows you to initialize a variable that will stay in the scope of the loop. Usually you would initialize an int variable and use it to act as the “counter” of your for loop. Condition specifies the condition for this for loop to run, as long as the condition is satisfied, the for loop will continue running. The logic flow for for-loops is to check the condition before running the loop. Hence if your condition doesn’t pass when you first encounter for loop, it wouldn’t even run once. Be very careful with <, and <= in your for loop, using the incorrect comparison would result in off-by-one error and sad point deduction. Update: This argument allows you to update any variables, typically the “counter” you use in the condition argument. Updating the wrong variable will result in an infinite loop that might take some time for you to debug. Normally we would put i++ to indicate that I increments by one for each iteration, but we can also put i--for decrement or i+=2, i*=2, so on so forth.

It is worth noting that none of these arguments is required for the loop to run, however, it is almost always that you will see all three arguments.
            for(;;){
            //body of loop
            }
            The above code is a perfectly valid infinite loop.

Let’s try to code a program that adds 1 to 100 integers together. Sure, you could do System.out.println(1 + 2 + 3 + 4 +5 …………….+100); If you want to, but I don’t. This is the UGA way, let’s do it the GT way. Since we know that we are iterating from 1 to 100, and we know exactly how many times we want the code to execute, so that’s the hint that for loop is in action. Our logic flow is as follows.

    1. We want a variable named total to hold the answer. 2. We want the use a loop to loop through the numbers 1 to 100. 3. We want to add those numbers to a variable that would be the answer to our problem.
            public static void main(String[] args){
            int total = 0; 		//this will be our total to keep track of the answer.
            for (int i = 0; i <= 100, i++ ){
            // again be careful of the <= comparison, we want to include 100 so       //I used <=, however, notice that this loop runs 101 times.

            total += i; // I am adding i to total, because i increments from 1 to 100 as the        //loop runs, we can use that to add to our variable to add from 1 to 100.
            }
            System.out.println(“Adding 1 – 100 is ” + total);
            }

At the beginning of the for-loop section, it was mentioned that for loop is just a fancy while loop. Java is doing the conversion from for loop to while loop for you. Hence, converting from for loop to while loop is almost always tested as well. You will practice doing so in the practice section.