Computer Language
Lecture 5

Repeating functionality

Josue Obregon

Seoul National University of Science and Technology
Information Technology Management
Lecture slides index

April 14, 2025

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input and Strings
  3. Variables and calculation with numbers
  4. Conditional statements
  5. Repeating functionality
  6. Methods & Debugging
  7. Lists, Arrays and Strings
  8. Midterm
  1. Introduction to Object Oriented Programming
  2. Deeper look into Object Oriented Programming
  3. Inheritance and Interfaces I
  4. Inheritance and Interfaces II
  5. Class diagrams, packages and exceptions
  6. Project Live Code Review and Evaluation
  7. Final examination

Class contents

  1. Introduction to Computer Programming and Java
  2. Reading Input and Strings
  3. Variables and calculation with numbers
  4. Conditional statements
  5. Repeating functionality
  6. Methods & Debugging
  7. Lists, Arrays and Strings
  8. Midterm
  1. Introduction to Object Oriented Programming
  2. Deeper look into Object Oriented Programming
  3. Inheritance and Interfaces I
  4. Inheritance and Interfaces II
  5. Class diagrams, packages and exceptions
  6. Project Live Code Review and Evaluation
  7. Final examination

Agenda

  • while loop structure
  • Sentinel-controlled loops (infinite loops)
  • Ending, skipping and breaking loops
  • Calculation with loops
  • while loop with a condition
  • Counter-controlled loops
  • The for loop
  • Structure of programs using loops

Learning objectives

  • You are familiar with loops and know how to create a program that contains one.
  • You know how to use the break command to end a loop’s execution.
  • You know how to use the continue command to return to the beginning of a loop.
  • You are able to create a program that reads inputs from a user until a specific input is given.
    • For example, the number 0 or the string “end”, after which the program prints something about the provided inputs (e.g., the input count, and in the case of numbers their sum and average).
  • You’re familiar with the condition of the while loop condition.
  • You know how to use the for loop.
  • You recognize situations where a while loop should be used and those where a for loop is more appropriate.

Introduction

  • A computer’s processor, which specializes in executing commands, is capable of executing – in a modern computer – over a billion (machine code) commands in a second.
  • In this section, we’ll get used to writing often-repeated program code with the help of loops.
  • Let’s motivate ourselves to use loops.
  • Below you’ll find an example of a program that asks the user for five numbers and calculates their sum.
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);

Motivating example

  • It does the job, but not elegantly.
  • What if the program had to read a hundred, or perhaps a thousand numbers and print their sum? What if the program had to read three numbers only?
  • The problem can be solved with a loop which keeps track of both the sum and the number of times input has been read. The program that prints the sum of five numbers now looks as follows
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);

Loops

  • A loop consists of an expression that determines whether or not the code within the loop should be repeated, along with a block containing the source code to be repeated.
  • A loop takes the following form.
while (_expression_) {
    // The content of the block wrapped in curly brackets
    // The block can have an unlimited amount of content
}
  • We’ll use the value true as the loop’s expression for now.
  • This way, the loop’s execution is always continued when the program arrives at the point that decides whether it should be repeated or not.
  • This happens when the execution of the program first arrives at the loop expression for the first time, and also when it reaches the end of the loop’s block.

Infinite loops

  • The loop execution proceeds line-by-line. The following program outputs I can program an infinite number of times.
while (true) {
    System.out.println("I can program!");
}
  • A program that runs infinitely does not end on its own. In NetBeans, it can be shut down by clicking the red button located on the left side of the output window.

Ending a Loop

  • The loop can be broken out of with command ‘break’.

  • When a computer executes the command ‘break’, the program execution moves onto the next command following the loop block.

  • The example below is a program that prints numbers from one to five.

  • Note how the variable that’s used within the loop is defined before the loop.

  • This way the variable can be incremented inside the loop and the change sticks between multiple iterations of the loop.

int number = 1;

while (true) {
    System.out.println(number);
    if (number >= 5) {
        break;
    }

    number = number + 1;
}

System.out.println("Ready!");
1
2
3
4
5
Ready!

Breaking a loop

  • Breaking out of the loop occurs when a user enters a specified input or whenever a calculation performed in the loop ends in the desired result.
  • These kinds of programs contain both a loop used to define a section to be repeated and also a conditional expression used to check whether or not the condition to exit the loop has been fulfilled.
  • Users can also be asked for input within a loop.
  • The variables that are commonly used in loops (such as Scanner readers) are defined before the loop, whereas variables (such as the value read from the user) that are specific to the loop are defined within it.
  • This loops are also known as sentinel-controlled loop or indefinite iteration
    • A special value called a sentinel value (also called a signal value, a dummy value or a flag value) can be used to indicate “end of data entry.”

Example of breaking a loop

  • In the example below, the program asks the user whether to exit the loop or not.
  • If the user inputs the string “y”, the execution of the program moves to the command following the loop block, after which the execution of the program ends.
Scanner scanner = new Scanner(System.in);

while (true) {
    System.out.println("Exit? (y exits)");
    String input = scanner.nextLine();
    if (input.equals("y")) {
        break;
    }

    System.out.println("Ok! Let's carry on!");
}

System.out.println("Ready!");
Exit? (y exits)
  (user input) no
Ok! Let's carry on!
Exit? (y exits)
  (user input) non
Ok! Let's carry on!
Exit? (y exits)
  (user input) y
Ready!

Exercise 1 - Carry on?

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

Sample Output

Shall we carry on?
  (user input) yes
Shall we carry on?
  (user input) ye
Shall we carry on?
  (user input) y
Shall we carry on?
  (user input) no

Carry on with a number

  • In the previous example, the program read inputs of type string from the user.
  • The program can also be implemented with other types of variables.
  • The program below asks numbers from the user until the user inputs a zero.
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!");
Input a number, 0 to quit
  (user input) 5
You input 5
Input a number, 0 to quit
  (user input) -2
You input -2
Input a number, 0 to quit
  (user input) 0
Done, thank you!

Exercise 2 - Are we there yet?

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

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 744
Give a number:
  (user input) -12
Give a number:
  (user input) 4

Returning to the start of the loop

  • When the execution reaches the end of the loop, the execution starts again from the start of the loop.
  • This means that all the commands in the loop have been executed.
  • You can also return to the beginning from other places besides the end with the command continue. When the computer executes the command continue, the execution of the program moves to the beginning of the loop.

The continue command

  • The example below demonstrates the use of the continue command. The program asks the user to input positive numbers.
  • If the user inputs a negative number or a zero, the program prints the message “Unfit number, try again”, after which the execution returns to the beginning of the loop.
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);
}

Breaking the loop

  • The previous program is repeated infinitely since the break command used for exiting the loop is not used.
  • To exit the loop, the break command must be added to it.
Scanner scanner = new Scanner(System.in);

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

    if (number == 0) {
        break;
    }

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

    System.out.println("Your input was " + number);
}
  • In this example, the program is modified in such a way that the user is asked to input positive numbers.
  • If the user inputs a negative number, the program informs them that the number was unfit and returns to the beginning of the loop.
  • If the number was zero, the program exits the loop.

Exiting loop and limit

What does the program below print?

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 + " ");
}

Options:

  1. 1 2 3 4 5
  2. 5
  3. 4
  4. 6

Exercise 3 - Only positives?

  • 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.

Sample Output

Give a number:
  (user input) 5
25
Give a number:
  (user input) 4
16
Give a number:
  (user input) -3
Unsuitable number
Give a number:
  (user input) 1
1
Give a number:
  (user input) 0

Analyizing our solution

  • In the previous exercise, you made a program that asks the user for numbers.
  • If the user entered a negative number, the program would inform them that the number was unfit, and if the user entered a zero, the program would exit.
  • A possible solution to the exercise is the following.
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);
}

Alternative solution

  • The program could be made by modifying the if-statement to another form.
  • In the example below, the conditionals have been combined to replace separate if-statements.
Scanner scanner = new Scanner(System.in);

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

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

    System.out.println(number * number);
}
  • Which of the previous examples was more clear?

Checking the clarity of the first solution

// The task is to read an input from the user
Scanner scanner = new Scanner(System.in);

// The task is to repeat the block until the block is exited
while (true) {
    // The task is to ask the user for an input
    System.out.println("Input a number ");
    // The task is to read a number from the user
    int number = Integer.valueOf(scanner.nextLine());

    // The task is to guard and prevent unfit numbers
    // for further processing
    if (number < 0) {
        System.out.println("Unfit number");
        continue;
    }

    // The task is to check if the loop should be exited
    if (number == 0) {
        break;
    }

    // The task is to print the square of the number
    System.out.println(number * number);
}
  • Let’s examine the previous programs with comments.
  • Before each command, there’s a comment that aims to explain what’s happening in the program.
  • This program is written with separate if-statements.
  • Note that every if-statement has a single, clear task.

Checking the clarity of the alternative solution

// The task is to read an input from the user
Scanner scanner = new Scanner(System.in);

// The task is to repeat the block until the block is exited
while (true) {
    // The task is to ask the user for an input
    System.out.println("Input a number ");
    // The task is to read a number from the user
    int number = Integer.valueOf(scanner.nextLine());

    // The purpose of the if-else if-else block?
    // The task is the processing of the number?
    if (number < 0) {
        System.out.println("Unfit number");
    } else if (number == 0) {
        break;
    } else {
        System.out.println(number * number);
    }
}
  • When we comment on a program containing combined if-statements, the comments take the following form.
  • We notice that it’s difficult to define a single, clear task for if-else if-else-block.
  • During the design and implementation of a program, it’s desirable to aim for a situation in which every part of the program has a a single, clear task.
  • This theme repeats throughout the course.

Calculation with loops

  • Loops are used in computing many different things.
  • For example, programs that process indefinite numbers of user-inputted values make use of loops.
  • These kinds of programs typically print out some sort of statistics about the numbers that were read or other inputs after the end loop.
  • For the program to print out information from the loop execution after the loop, the information must be saved and modified during the loop.
  • If the variable used to store the data is introduced within the loop, the variable is only available within that loop and nowhere else.

Calculation example

  • Let’s create a program to count and print out the number of ones entered by the user.
  • Let’s first create a non-working version and examine the action of the blocks.
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);

What was the problem?

  • The previous program does not work because the variable ones is introduced within the loop, and an attempt is made to use it after the loop at the end of the program.
  • The variable only exists inside the loop.
  • If the print statement System.out.println("The total of ones: " + ones); was inside the loop, the program would work, but not in the desired way.
  • Let’s examine this next.
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
    System.out.println("The total of ones: " + ones);
}

Is it working correctly?

  • The example above works, but not in a way we hoped it would.
  • Below the example output of the program

Sample Output

Insert a number (0 exits)
  (user input) 5
The total of ones: 0
Insert a number (0 exits)
  (user input) 1
The total of ones: 1
Insert a number (0 exits)
  (user input) 1
The total of ones: 1
Insert a number (0 exits)
  (user input) 2
The total of ones: 0
Insert a number (0 exits)
  (user input) 0

How to solve that problem?

  • If you wish to use a variable after a loop, it needs to be introduced before the loop.
  • In the example below, the program has the same steps as our previous solution.
  • The program uses variable ones to keep track of the number ones.
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);
Give a number (end with 0):
  (user input) 1
Give a number (end with 0):
  (user input) 2
Give a number (end with 0):
  (user input) 1
Give a number (end with 0):
  (user input) -1
Give a number (end with 0):
  (user input) 0
Total of ones: 2

Exercise 4 - Number of numbers

  • 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.

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 22
Give a number:
  (user input) 9
Give a number:
  (user input) -2
Give a number:
  (user input) 0
Number of numbers: 4

Exercise 5 - Number of negative numbers

  • 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 that are negative.
  • The zero that’s used to exit the loop should not be included in the total number count.

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 22
Give a number:
  (user input) 9
Give a number:
  (user input) -2
Give a number:
  (user input) 0
Number of negative numbers: 1

Let’s practice more

  • The programs written in the previous exercises have read input from the user and kept track of the count of certain types of numbers.
  • In the next exercise, the requested sum of numbers is not much different
    • this time, rather than keeping track of the number of values entered, you add the number entered by the user to the sum.

Exercise 6 - Sum of numbers

  • Write a program that reads numbers from the user until the user inputs a number 0.
  • After this the program outputs the sum of the numbers.
  • The number zero does not need to be added to the sum, even if it does not change the results.

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 22
Give a number:
  (user input) 9
Give a number:
  (user input) -2
Give a number:
  (user input) 0
Sum of the numbers: 34

Using multiple variables

  • Sometimes you need to use multiple variables.
  • The example in th e following slide shows a program which reads numbers from the user until the user writes 0.
  • Then the program prints the number of positive and negative numbers given, and the percentage of positive numbers from all numbers given.

Using multiple variables (code)

Scanner reader = new Scanner(System.in);

// For saving number of numbers
int numberOfPositives = 0;
int numberOfNegatives = 0;

// For repeatedly asking for numbers
while (true) {
    System.out.println("Give a number (0 to stop): ");
    // For reading user input
    int numberFromUser = Integer.valueOf(reader.nextLine());

    // For breaking the loop when user writes 0
    if (numberFromUser == 0) {
        break;
    }

    // For increasing numberOfPositives by one
    // when user gives a positive number
    if (numberFromUser > 0) {
        numberOfPositives = numberOfPositives + 1;
    }

    // For increasing numberOfNegatives by one
    // when user gives a negative number
    if (numberFromUser < 0) {
        numberOfNegatives = numberOfNegatives + 1;
    }

    // Also could have used..
    // if (numberFromUser > 0) {
    //     numberOfPositives = numberOfPositives + 1;
    // } else {
    //     numberOfNegatives = numberOfNegatives + 1;
    // }

}

// For printing the number of positive numbers
System.out.println("Positive numbers: " + numberOfPositives);
// For printing the number of negative numbers
System.out.println("Negative numbers: " + numberOfNegatives);

// For printing the percentage of positive numbers from all numbers

if (numberOfPositives + numberOfNegatives > 0) {
    // Print only if user has given numbers
    // to avoid dividing by zero
    double percentageOfPositives = 100.0 * numberOfPositives / (numberOfPositives + numberOfNegatives);
    System.out.println("Percentage of positive numbers: " + percentageOfPositives + "%");
}

Exercise 7 - Number and sum of numbers

  • Write a program that asks the user for input until the user inputs 0.
  • After this the program prints the amount of numbers inputted and the sum of the numbers.
  • The number zero does not need to be added to the sum, but adding it does not change the results.
    • You need two variables to keep track of the information.
    • Use one for keeping track of the numbers inputted and other for keeping track of the sum

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 22
Give a number:
  (user input) 9
Give a number:
  (user input) -2
Give a number:
  (user input) 0
Number of numbers: 4
Sum of the numbers: 34

Exercise 8 - Average of numbers

  • Write a program that asks the user for input until the user inputs 0.
  • After this, the program prints the average of the numbers.
  • The number zero does not need to be counted to the average.
  • You may assume that the user inputs at least one number.
    • The average of the numbers can be calculated by dividing the sum of numbers with the amount of the numbers

Sample Output

Give a number:
  (user input) 5
Give a number:
  (user input) 22
Give a number:
  (user input) 9
Give a number:
  (user input) -2
Give a number:
  (user input) 0
Average of the numbers: 8.5

Exercise 9 - Average of positive numbers

  • Write a program that asks the user for input until the user inputs 0.
  • After this, the program prints the average of the positive numbers (numbers that are greater than zero).
  • If no positive number is inputted, the program prints “Cannot calculate the average”

Sample Output 1

  (user input) 3
  (user input) 5
  (user input) 1
  (user input) -3
  (user input) 0
3.0

Sample Output 2

  (user input) 0
Cannot calculate the average

Sample Output 3

  (user input) -3
  (user input) 1
  (user input) 0
1.0

Sample Output 4

  (user input) 1
  (user input) 1
  (user input) 0
1.0

while loop with a condition

  • The “while-true” loop (a loop with the boolean true in its parenthesis we’ve been using is very handy when the program has to repeat a functionality until the user provides certain input.
    • a loop with the boolean true in its parenthesis, meaning the loop continues forever (or until the loop is ended with the break command ).
  • Actually, the parenthesis of a loop can contain a conditional expression, or a condition, just like the parenthesis of an if statement.
  • The true value can be replaced with an expression, which is evaluated as the program is executed.
  • The expression is defined the same way as the condition of a conditional statement.

while loop code tracing

  • The following code prints the numbers 1,2,…,5.
  • When the value of the variable number is more than 5, the while-condition evaluates to false and the execution of the loop ends for good.
int number = 1;

while (number < 6) {
    System.out.println(number);
    number++;
}

  • The code above can be read “As long as the value of the variable number is less than 6, print the value of the variable number and increase the value of the variable number by one”.

Counter-controlled loop

  • In the previous slide, we learned how a while loop with a condition can be used to go through numbers in a certain interval.
  • The structure of this kind of loop is the following.
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++;
}
  • The above loop can be split into three parts.
    1. First we introduce the variable i (a.k.a. the counter variable), used to count the number of times the loop has been executed so far, and set its value to 0: int i = 0; (a.k.a. the initial value).
    2. This is followed by the definition of the loop – the loop’s condition is i < 10 (a.k.a. the loop-continuation condition) so the loop is executed as long as the value of the variable i is less than 10.
    3. The loop body contains the functionality to be executed System.out.println(i);, which is followed by increasing the value of the variable i++ (a.k.a. the increment).
  • The command i++ is shorthand for i = i + 1.

The for loop

  • The same can be achieved with a for loop like so.
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
  • A for loop contains four parts:
    1. introducing the counter variable with the initial value for counting the number of executions;
    2. the loop-continuation condition;
    3. the increment (or decrement or change) in the value of the counter variable; and
    4. the functionality to be executed.
for (*counter variable initialization*; *condition*; *increasing the counter*) {
    // Functionality to be executed
}

for loop code tracing

  • The following code prints the numbers from three to six.
  • The interval can also be defined using variables – the example below uses variables start and end to define the interval of numbers the loop goes through.
int start = 3;
int end = 7;
for (int i = start; i < end; i++) {
    System.out.println(i);
}

  • We will continue practicing loops in the following exercises.
  • You can use either a while loop with a condition, or a for loop.

Exercise 10 - Counting

  • Write a program that reads an integer from the user.
  • Next, the program prints numbers from 0 to the number given by the user.
  • You can assume that the user always gives a positive number.
  • Beside are some examples of the expected functionality.

Sample Output 1

  (user input) 4
0
1
2
3
4

Sample Output 2

  (user input) 1
0
1

Exercise 11 - Counting to hundred

  • Write a program, which reads an integer from the user.
  • Then the program prints numbers from that number to 100.
  • You can assume that the user always gives a number less than 100.
  • Beside are some examples of the expected functionality.

Sample Output 1

  (user input) 99
99
100

Sample Output 2

  (user input) -4
-4
-3
-2
-1
0
1
2
... (many numbers in between) ...
98
99
100

Exercise 12 - From where to where?

  • Ask the user for two numbers: the starting point and the ending point of a sequence of numbers.
  • Write a program which prints the integers from the starting to the ending point given by the user.
  • If the upper limit is smaller than the starting point, nothing is printed:
  • Beside are some examples of the expected functionality.

Important

Remember that the lower and upper limits can be negative!

Sample Output 1

Where to? 
  (user input) 8
Where from? 
  (user input) 5
5
6
7
8

Sample Output 2

Where to? 
  (user input) 12
Where from? 
  (user input) 16

On Stopping a loop execution

  • A loop does not stop executing immediately when its condition evaluates to true.

  • A loop’s condition is evaluated at the start of a loop, meaning when (1) the loop starts for the first time or (2) the execution of a previous iteration of the loop body has just finished.

  • Let’s look at the following loop.

int number = 1;

while (number != 2) {
    System.out.println(number);
    number = 2;
    System.out.println(number);
    number = 1;
}
1
2
1
2
1
2
...
  • Even though number equals 2 at one point, the loop runs forever.

Loop-continuation condition evaluation

  • The condition of a loop is evaluated when the execution of a loop starts and when the execution of the loop body has reached the closing curly bracket.
    • If the condition evaluates to true, execution continues from the top of the loop body.
    • If the condition evaluates to false, execution continues from the first statement following the loop.
  • This also applies to for loops.
  • In the example below, it would be incorrect to assume that the loop execution ends when i equals 100.
  • However, it doesn’t.
for (int i = 0; i != 100; i++) {
    System.out.println(i);
    i = 100;
    System.out.println(i);
    i = 0;
}
  • The loop above never stops executing.

Repeating Functionality

  • One common subproblem type is to “do something a certain amount of times”.
  • What’s common to all these programs is repetition.
  • Some functionality is done repeatedly, and a counter variable is used to keep track of the repetitions.
  • We call this counter-controlled iteration
  • The following program calculates the product 4*3 somewhat clumsily, i.e., as the sum 3 + 3 + 3 + 3:
int result = 0;

int i = 0;
while (true) {
    result += 3; // shorthand for result = result + 3
    i++;  // shorthand for i = i + 1

if (i == 4) {
        break;
    }
}

System.out.println(result);

A better solution

  • The same functionality can be achieved with the following code.
int result = 0;

int i = 0;
while (i < 4) {
    result += 3; // shorthand for result = result + 3
    i++;  // shorthand for i = i + 1

}

System.out.println(result);
  • Or by using a for loop as seen in the following.
int result = 0;

for (int i = 0; i < 4; i++) {
    result += 3;
}

System.out.println(result);

Another code tracing exercise

  • Let’s trace the following code using the memory table
public class Example {
    public static void main(String[] args) {
        int result = 0;

        int i = 0;
        while (i < 4) {
            result += 3;
            i++;
        }

        System.out.println(result);
    }
}

Exercise 13 - Sum of a sequence?

  • Implement a program which calculates the sum of a closed interval, and prints it.
  • Expect the user to write the smaller number first and then the larger number.

Sample Output 1

First number?
  (user input) 3
Last number? 
  (user input) 5
The sum is 12
  • The code example internally calculated 3 + 4 + 5 = 12

Sample Output 2

First number?
  (user input) 2
Last number?
  (user input) 8
The sum is: 35
  • And now the internal calculation was 2 + 3 + 4 + 5 + 6 + 7 + 8 = 35

On the structure of programs using loops

  • In the previous examples, we have concentrated on cases where the loop is executed a predetermined number of times (a counter-controlled loop).
  • The number of repetitions can be based on user input – in these cases, the for loop is quite handy.
  • In programs where the loop body has to be executed until the user gives certain input, the for loop is not too great.
  • In these cases, the while-true loop we practiced earlier works well.
  • This loop is also known as sentinel-controlled loop or indefinite iteration
  • A special value called a sentinel value (also called a signal value, a dummy value or a flag value) can be used to indicate “end of data entry.”

Another example

  • Let’s take a look at a somewhat more complex program that reads integers from the user.
  • The program handles negative numbers as invalid, and zero stops the loop.
  • When the user enters zero, the program prints the sum of valid numbers, the number of valid numbers and the number of invalid numbers.
Scanner reader = new Scanner(System.in);

System.out.print("Write numbers, negative numbers are invalid: ");
int sum = 0;
int validNumbers = 0;
int invalidNumbers = 0;

while (true) {
    int input = Integer.valueOf(reader.nextLine());

    if (input == 0) {
        System.out.println("Sum of valid numbers: " + sum);
        System.out.println("Valid numbers: " + validNumbers);
        System.out.println("Invalid numbers: " + invalidNumbers);
        break;
    }

    if (input < 0) {
        invalidNumbers++;
        continue;
    }

    sum += input;
    validNumbers++;
}

Is that code structure good?

  • In the previous code , the computation executed after the loop has ended has been implemented inside of the loop.
  • This approach is not recommended as it can easily lead to very complex program structure.
  • If something else – for example, reading more input – is to be done when the loop ends, it could also easily end up being placed inside of the loop.
  • As more and more functionality is needed, the program becomes increasingly harder to read.

A better code structure

  • Let’s stick to the following loop structure:
Scanner reader = new Scanner(System.in);

// Create variables needed for the loop

while (true) {
    // read input

    // end the loop -- break

    // check for invalid input -- continue

    // handle valid input
}

// functionality to execute after the loop ends
  • In other words, the program structure is cleaner if the things to be done after the loop ends are placed outside of it.

A better code structure (code)

Scanner reader = new Scanner(System.in);

System.out.print("Write numbers, negative numbers are invalid: ");
int sum = 0;
int validNumbers = 0;
int invalidNumbers = 0;

while (true) {
    int input = Integer.valueOf(reader.nextLine());

    if (input == 0) {
        break;
    }

    if (input < 0) {
        invalidNumbers++;
        continue;
    }

    sum += input;
    validNumbers++;
}

System.out.println("Sum of valid numbers: " + sum);
System.out.println("Valid numbers: " + validNumbers);
System.out.println("Invalid numbers: " + invalidNumbers);

Checking our learning objectives

  • You are familiar with loops and know how to create a program that contains one.
  • You know how to use the break command to end a loop’s execution.
  • You know how to use continue command to return to the beginning of a loop.
  • You are able to create a program that reads inputs from a user until a specific input is given. For example, the number 0 or the string “end”, after which the program prints something about the provided inputs (e.g., the input count, and in the case of numbers their sum and average).
  • You’re familiar with the condition of the while loop condition.
  • You know how to use the for loop.
  • You recognize situations where a while loop should be used and those where a for loop is more appropriate.

Next week

  • Methods

Acknowledgements


Back to title slide Back to lecture slides index