Skip to content

Week 8 - Loops

Repeating Functionality (LOOPS)

Learning Objectives

  1. Loop Familiarity and Creation: You possess a solid understanding of loops and can proficiently construct programs that incorporate them.
  2. Effective Loop Termination: You can skillfully employ the “break” command to gracefully halt the execution of a loop when a certain condition is met.
  3. Loop Control with “continue”: You have the ability to employ the “continue” command to efficiently return to the beginning of a loop and manage the flow of program execution.
  4. User Input Handling: You are proficient in developing programs that solicit and process user inputs until a specific predefined input (e.g., “0” or “end”) is provided, after which the program responds appropriately with information about the collected inputs.
  5. While Loop Proficiency: You have a strong grasp of the condition used in a while loop and can effectively work with it in your programs.
  6. Competence in For Loops: You are proficient in utilizing for loops to control program flow and iteration.
  7. Loop Selection Aptitude: You can discern between situations that warrant the use of a while loop and those where a for loop is a more suitable choice, demonstrating a keen understanding of loop selection based on the specific task or problem at hand.

Why We Use Loops

  • Increases flexibility in code (looping mechanisms can be variable)
  • Eliminates repetition in code (no typing the same commands over and over)
Consider this code

Read in 5 numbers, sum them, and print the output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Scanner scanner = new Scanner(System.in);
int sum = 0;

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("Input a number: ");
sum = sum + Integer.valueOf(scanner.nextLine());

System.out.println("The sum of the numbers is " + sum);
* This is not pretty even though it gets the job done.

Now consider this alternative
Read in 5 numbers, sum them, and print the output
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Scanner scanner = new Scanner(System.in);

int numbersRead = 0;
int sum = 0;

while (true) {
    if (numbersRead == 5) {
        break;
    }

    System.out.println("Input number");
    sum = sum + Integer.valueOf(scanner.nextLine());
    numbersRead = numbersRead + 1;
}

System.out.println("The sum of the numbers is " + sum);

What is a Loop and Loop Control

Info

Loops are grouped statements that are repeated until a control expression determines whether or not the loop should stop.

While Loop

Form

1
2
3
while ( boolean expression ) {
    // code statements we loop over
}

Loop Control

  • A while loop will continue executing as long as the boolean expression is true.
  • It’s easy to create an infinite loop by makeing the boolean expression always true.
    1
    2
    3
    while ( true ) {
        // This will never stop.
    }
    
  • To stop a while loop, we must either make the boolean expression false, or add another conditional to break from the loop.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    int number = 1;
    
    while (true) {
        System.out.println(number);
        if (number >= 5) {
            break;
        }
    
        number++;
    }
    
    System.out.println("Ready!");
    
Question

Why do we declare the int number = 1 outside the while loop?

Answer

If we didn’t, the local variable number would get redefined on each loop iteration causing it to never increment to 5. Thus, causing an infinite loop.

  • Let’s look at another way to stop a loop, via user-input:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    Scanner scanner = new Scanner(System.in);
    
    while (true) {
        System.out.println("Exit? (y or Y exits)");
        String input = scanner.nextLine();
        if (input.toLowerCase().equals("y")) {
            break;
        }
    
        System.out.println("Ok! Let's carry on!");
    }
    
    System.out.println("Left the loop!");
    
Excercise

Write a program by using the loop example that asks “Shall we carry on?” until the user inputs the string “no”.

Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Scanner s = new Scanner(System.in);
String input;
while(true) {
    System.out.print("Shall we carry on? (no exits): ");
    input = s.nextLine();
    if(input.toLowerCase().equals("no")) {
        break;
    }
    System.out.println("kept going!");
}
System.out.println("Exited loop!");
  • Other variables of types of User Input can be used to crontrol loops. Consider the following:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    Scanner scanner = new Scanner(System.in);
    
    while (true) {
        System.out.println("Input a number, 0 to quit");
        int command = Integer.valueOf(scanner.nextLine());
        if (command == 0) {
            break;
        }
    
        System.out.println("You input " + command);
    }
    
    System.out.println("Done, thank you!");
    
  • Here an integer input by the user is used.

How Does a Loop Start Over

  • When the execution reaches the end of the loop, the execution starts again from the start of the loop.
  • You can also return to the beginning from other places besides the end with the command continue.
    • When the computer encounters the continue command, it goes back to the start of the loop in the program.
Continue Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Scanner scanner = new Scanner(System.in);

while (true) {
    System.out.println("Insert positive integers");
    int number = Integer.valueOf(scanner.nextLine());

    if (number <= 0) {
        System.out.println("Unfit number! Try again.");
        continue;
    }

    System.out.println("Your input was " + number);
}
Excercise

Write a program, according to the preceding example, that asks the user to input values until they input the value 6.

Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Scanner s = new Scanner(System.in);
int input;
while(true) {
    System.out.print("Shall we carry on? (6 exits): ");
    input = Integer.parseInt(s.nextLine());
    if(input == 6) {
        break;
    }
    System.out.println("kept going!");
}
System.out.println("Exited loop!");
Question

What is wrong with the above loop?

Answer

Its INFINITE! There is no break or boolean expression to exit this loop.

Excercise

What does the program below print?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) {
    int number = 0;

    while (true) {
        number = number + 1;

        if (number >= 5) {
            break;
        }

        if (number < 5) {
            continue;
        }

        System.out.print(number + " ");
    }

    System.out.print(number + " ");
}

Answer

5 plus a space so: “5 “

Excercise

Write a program that asks the user for numbers. If the number is negative (smaller than zero), the program prints for user “Unsuitable number” and asks the user for a new number. If the number is zero, the program exits the loop. If the number is positive, the program prints the number to the power of two.

Answer

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Scanner s = new Scanner(System.in);
int input;
while(true) {
    System.out.print("Give me numbers: (0 exits): ");
    input = Integer.parseInt(s.nextLine());
    if(input < 0) {
        System.out.println("Unsuitable number");
        continue;
    } else if(input == 0) {
        break;
    } else {
        System.out.println(Math.pow(input, 2));
    }
}
System.out.println("Exited loop!");
* Another possible, and MORE CLEAR solution would be:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Scanner scanner = new Scanner(System.in);

while (true) {
    System.out.println("Input a number");
    int number = Integer.valueOf(scanner.nextLine());

    if (number == 0) {
        break;
    }

    if (number < 0) {
        System.out.println("Unfit number");
        continue;
    }

    System.out.println(number * number);
}
* The second version is more clear because the separated if statements have a clearly defined single purpose. * When combining if/else statements it’s difficult to define a single, clear task for if-else-else-block which makes the code less human readable.

A Common Loop Mistake

  • Declaring a variable inside the loop:
    Program to print 1's input by user
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    Scanner scanner = new Scanner(System.in);
    
    // The task is to read an input from the user
    while (true) {
    
        // The task is to keep count of number ones
        int ones = 0;
    
        System.out.println("Input a number (0 exits): ");
        // The task is to read a user inputted number
        int number = Integer.valueOf(scanner.nextLine());
    
        // The task is to exit the loop if the user
        // has inputted zero
        if (number == 0) {
            break;
        }
    
        // The task is to increase the amount of ones
        // if the user inputs a number one
        if (number == 1) {
            ones = ones + 1;
        }
    }
    
    // The task is to print out the total of ones
    // This doesn't work because the variable ones has been
    // introduced within the loop
    System.out.println("The total of ones: " + ones);
    
  • The variable ones is introduced within the loop so its value is initialized on each iteration.
  • An attempt is also made to use it after the loop at the end of the program, but by that time the variable is out of scope.

So what’s the fix? Some of you might consider putting the sout in the loop like so:

sout in the loop
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Scanner scanner = new Scanner(System.in);

// The task is to read an input from the user
while (true) {

    // The task is to keep count of number ones
    int ones = 0;

    System.out.println("Insert a number (0 exits): ");
    // The task is to read a user inputted number
    int number = Integer.valueOf(scanner.nextLine());

    // The task is to exit the loop if the user
    // has inputted zero
    if (number == 0) {
        break;
    }

    // The task is to increase the amount of ones
    // if the user inputs a number one
    if (number == 1) {
        ones = ones + 1;
    }

    // The task is to print out the total of ones
    System.out.println("The total of ones: " + ones);
}

  • Though this works for the ones variable, we only want it to print once, and this prints on every iteration.
  • The answer is to decalre the variable before the loop so that we don’t re-initialize it on each iteration and so we can use it outside the loop’s scope.
The Right Way
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Scanner scanner = new Scanner(System.in);

// The task is to keep track of number ones
int ones = 0;

// The task is to read an input from the user
while (true) {
    System.out.println("Give a number (end with 0): ");
    // The task is to read a user inputted number
    int number = Integer.valueOf(scanner.nextLine());

    // The task is to exit the loop if the user
    // has inputted zero
    if (number == 0) {
        break;
    }

    // The task is to increase the amount of ones
    // if the user inputs a number one
    if (number == 1) {
        ones = ones + 1;
    }
}

// The task is to print out the total of ones
System.out.println("The total of ones: " + ones);
Exercise

Write a program that reads values from the user until they input a 0. After this, the program prints the total number of inputted values. The zero that’s used to exit the loop should not be included in the total number count.

Answer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Scanner s = new Scanner(System.in);
int input;
int numInputs = 0;
while(true) {
    System.out.print("Give me numbers: (0 exits): ");
    input = Integer.parseInt(s.nextLine());
    if(input == 0) {
        break;
    }
    numInputs++;
}
System.out.printf("Read %d inputs!", numInputs);

Rewrite My Loops

  • So far we’ve exited our loops with a separate conditional and with break, but we can use the boolean expression instead.
    • Consider the last example:
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      Scanner s = new Scanner(System.in);
      int input;
      int numInputs = 0;
      while(true) {
          System.out.print("Give me numbers: (0 exits): ");
          input = Integer.parseInt(s.nextLine());
          if(input == 0) {
              break;
          }
          numInputs++;
      }
      System.out.printf("Read %d inputs!", numInputs);
      
    • This can be re-written like so:
      1
      2
      3
      4
      5
      6
      7
      8
      9
      Scanner s = new Scanner(System.in);
      int input;
      int numInputs = 0;
      System.out.print("Give me numbers: (0 exits): ");
      while((input = Integer.parseInt(s.nextLine())) != 0 ) {;
          numInputs++;
          System.out.print("Give me numbers: (0 exits): ");
      }
      System.out.printf("Read %d inputs!", numInputs);
      

For Loops

  • Consider the following while loop:

    1
    2
    3
    4
    5
    int i = 0;
    while (i < 10) {
        System.out.println(i);
        i++;
    }
    

  • While this works, its fairly verbose.

  • Let’s introduce a different style of loop to reduce our complexity.
    1
    2
    3
    for (int i = 0; i < 10; i++) {
        System.out.println(i);
    }
    

Form and Parts of the For Loop

1
2
3
for (*introducing a variable*; *condition*; *increasing the counter*) {
    // Functionality to be executed
}
  1. Introduce Variables
  2. Loop Condition
  3. Increase, Decrease, or Change loop counter values
  4. Body of the loop

Let’s talk about loop execution…

Question

What would the following program print?

1
2
3
4
5
int start = 3;
int end = 7;
for (int i = start; i < end; i++) {
    System.out.println(i);
}

Answer
1
2
3
4
3
4
5
6
Excercise

Write a program that reads an integer from the user. Next, the program prints numbers from 0 to the number given by the user with a for loop. You can assume that the user always gives a positive number.

Answer
1
2
3
4
5
6
Scanner s = new Scanner(System.in);
System.out.print("Give me a number: ");
int input = Integer.parseInt(s.nextLine());
for(int i=0; i<=input; i++) {
    System.out.println(i);
}

Loop Control

  • break and continue work the same way in a for loop as they do in a while loop!!!

If Time Permits More Exercises :-)