Repeating functionality
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
April 14, 2025
while
loop structurewhile
loop with a conditionfor
loopbreak
command to end a loop’s execution.continue
command to return to the beginning of a loop.while
loop condition.for
loop.while
loop should be used and those where a for
loop is more appropriate.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);
while (_expression_) {
// The content of the block wrapped in curly brackets
// The block can have an unlimited amount of content
}
true
as the loop’s expression for now.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.
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.Sample Output
Sample Output
continue
. When the computer executes the command continue
, the execution of the program moves to the beginning of the loop.continue
commandcontinue
command. The program asks the user to input positive numbers.break
command used for exiting the loop is not used.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);
}
What does the program below print?
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);
}
// 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);
}
// 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);
}
}
if-else if-else
-block.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);
ones
is introduced within the loop, and an attempt is made to use it after the loop at the end of the program.System.out.println("The total of ones: " + ones);
was inside the loop, the program would work, but not in the desired way.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);
}
Sample Output
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;
}
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 + "%");
}
while
loop with a conditiontrue
in its parenthesis we’ve been using is very handy when the program has to repeat a functionality until the user provides certain input.
true
in its parenthesis, meaning the loop continues forever (or until the loop is ended with the break
command ).if
statement.true
value can be replaced with an expression, which is evaluated as the program is executed.while
loop code tracingnumber
is more than 5, the while
-condition evaluates to false and the execution of the loop ends for good.while
loop with a condition can be used to go through numbers in a certain interval.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).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.System.out.println(i);
, which is followed by increasing the value of the variable i++
(a.k.a. the increment).i++
is shorthand for i = i + 1
.for
loopfor
loop like so.for
loop contains four parts:
for
loop code tracingstart
and end
to define the interval of numbers the loop goes through.while
loop with a condition, or a for
loop.Important
Remember that the lower and upper limits can be negative!
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.
number
equals 2 at one point, the loop runs forever.true
, execution continues from the top of the loop body.false
, execution continues from the first statement following the loop.for
loops.i
equals 100.4*3
somewhat clumsily, i.e., as the sum 3 + 3 + 3 + 3
: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);
3 + 4 + 5 = 12
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++;
}
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
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);
break
command to end a loop’s execution.continue
command to return to the beginning of a loop.while
loop condition.for
loop.while
loop should be used and those where a for
loop is more appropriate.Computer Language