1 Loops
1
Loops
2
Motivations
Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times:
System.out.println("Welcome to Java!");
So, how do you solve this problem?
3
Objectives To use while, do-while, and for loop statements to control the
repetition of statements (§§4.2-4.4). To understand the flow of control in loop statements (§§4.2-4.4). To use Boolean expressions to control loop statements (§§4.2-4.4). To know the similarities and differences between three types of
loops (§4.5). To write nested loops (§4.6). To learn the techniques for minimizing numerical errors (§4.7). To implement program control with break and continue (§4.9). (GUI) To control a loop with a confirmation dialog (§4.10).
4
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
Statement(s);
}
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
count++;
}
Loop Continuation Condition?
true
Statement(s) (loop body)
false (count < 100)?
true
System.out.println("Welcome to Java!"); count++;
false
(A) (B)
count = 0;
5
Trace while Loop
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Initialize count
animation
count = 0
6
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is true
animation
count = 0
7
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
animation
count = 0
8
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 1 now
animation
count = 1
9
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is still true since count is 1
animation
count = 1
10
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Print Welcome to Java
animation
count = 1
11
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Increase count by 1count is 2 now
animation
count = 2
12
Trace while Loop, cont.
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
(count < 2) is false since count is 2 now
animation
count = 2
13
Trace while Loop
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
The loop exits. Execute the next statement after the loop.
animation
count = 2
14
Problem: Guessing Numbers
Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a sample run:
15
GuessNumberOneTime.javaimport java.util.Scanner; public class GuessNumberOneTime { public static void main(String[] args) { // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } }
16
GuessNumber.javaimport java.util.Scanner; public class GuessNumber { public static void main(String[] args) { // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); int guess = -1; while (guess != number) { // Prompt the user to guess the number System.out.print("\nEnter your guess: "); guess = input.nextInt(); if (guess == number) System.out.println("Yes, the number is " + number); else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } // End of loop } }
17
Problem: An Advanced Math Learning Tool
The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions.
18
SubtractionQuizLoop.javaimport java.util.Scanner; public class SubtractionQuizLoop { public static void main(String[] args) { final int NUMBER_OF_QUESTIONS = 5; // number of questions int correctCount = 0; // Count the number of correct answers int count = 0; // Count the number of questions long startTime = System.currentTimeMillis(); String output = ""; Scanner input = new Scanner(System.in); while (count < NUMBER_OF_QUESTIONS) { // 1. Generate two random single-digit integers int number1 = (int)(Math.random() * 10); int number2 = (int)(Math.random() * 10);
19
SubtractionQuizLoop.java // 2. If number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer “what is number1 – number2?”
System.out.print( "What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
20
SubtractionQuizLoop.java // 4. Grade the annser and display the result if (number1 - number2 == answer) { System.out.println("You are correct!"); correctCount++; } else System.out.println("Your answer is wrong.\n" + number1 + " - " + number2 +
" should be " + (number1 - number2)); // Increase the count count++; output += "\n" + number1 + "-" + number2 + "=" + answer + ((number1 - number2 == answer) ? " correct" : " wrong"); } long endTime = System.currentTimeMillis(); long testTime = endTime - startTime; System.out.println("Correct count is " + correctCount + "\nTest time is " + testTime / 1000 + " seconds\n" + output); } }
21
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value.
Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.
22
SentinelValue.javaimport java.util.Scanner; public class SentinelValue { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Read an initial data System.out.print( "Enter an int value (the program exits if the input is 0): "); int data = input.nextInt(); // Keep reading data until the input is 0 int sum = 0; while (data != 0) { sum += data; // Read the next data System.out.print( "Enter an int value (the program exits if the input is 0): "); data = input.nextInt(); } System.out.println("The sum is " + sum); } }
23
CautionDon’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations, using them could result in imprecise counter values and inaccurate results. This example uses int value for data. If a floating-point type value is used for data, (data != 0) may be true even though data is 0.
// data should be zerodouble data = Math.pow(Math.sqrt(2), 2) - 2; if (data == 0) System.out.println("data is zero");else System.out.println("data is not zero");
24
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Loop Continuation Condition?
true
Statement(s) (loop body)
false
25
do-while Loop
int i=0; do { System.out.println("i is " + i); i++;} while (i<10);
26
for Loopsfor (initial-action; loop-
continuation-condition; action-after-each-iteration) {
// loop body; Statement(s);}
int i;for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); }
Loop Continuation Condition?
true
Statement(s) (loop body)
false
(A)
Action-After-Each-Iteration
Initial-Action
(i < 100)?
true
System.out.println( "Welcome to Java");
false
(B)
i++
i = 0
27
Trace for Loop
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
Declare i
animation
i =
28
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
Execute initializeri is now 0
animation
i = 0
29
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }
(i < 2) is true since i is 0
animation
i = 0
30
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Print Welcome to Java
animation
31
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Execute adjustment statement i now is 1
animation
i = 1
32
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
(i < 2) is still true since i is 1
animation
i = 1
33
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Print Welcome to Java
animation
i = 1
34
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Execute adjustment statement i now is 2
animation
i = 2
35
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
(i < 2) is false since i is 2
animation
i = 2
36
Trace for Loop, cont.
int i;for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }
Exit the loop. Execute the next statement after the loop
animation
i = 2
37
NoteThe initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. Therefore, the following two for loops are correct. They are rarely used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
38
NoteIf the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
for ( ; ; ) { // Do something } (a)
Equivalent while (true) { // Do something }
(b)
39
Caution
Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:
Logic Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
40
Caution, cont.Similarly, the following loop is also wrong:int i=0; while (i < 10);{ System.out.println("i is " + i); i++;}
In the case of the do loop, the following semicolon is needed to end the loop.int i=0; do { System.out.println("i is " + i); i++;} while (i<10);
Logic Error
Correct
41
Which Loop to Use?The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b):
A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 3.19 for one of them):
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }
(a)
Equivalent
(b)
initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }
while (loop-continuation-condition) { // Loop body }
(a)
Equivalent
(b)
for ( ; loop-continuation-condition; ) { // Loop body }
42
Recommendations
Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
43
while, do while, for Loops
How are they different do while: executes statements one or more times while: executes statements zero or more times for: executes statements zero or more times
44
Nested Loops
Problem: Write a program that uses nested for loops to print a multiplication table.
45
MultiplicationTable.javapublic class MultiplicationTable { /** Main method */ public static void main(String[] args) { // Display the table heading System.out.println(" Multiplication Table"); // Display the number title System.out.print(" "); for (int j = 1; j <= 9; j++) System.out.print(" " + j); System.out.println("\n-----------------------------------------"); String output = ""; // Print table body for (int i = 1; i <= 9; i++) { output += i + " | "; for (int j = 1; j <= 9; j++) { // Display the product and align properly if (i * j < 10) output += " " + i * j; else output += " " + i * j; } output += "\n"; } // Display result System.out.println(output); } }
46
Minimizing Numerical Errors Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors through an example.
Listing 4.7 presents an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on.
TestSumTestSum Run
47
TestSum.java
public class TestSum { public static void main(String[] args) { // Initialize sum float sum = 0; // Add 0.01, 0.02, ..., 0.99, 1 to sum for (float i = 0.01f; i <= 1.0f; i = i + 0.01f) sum += i; // Display result System.out.println("The sum is " + sum); } }
48
TestSum2public class TestSum2 { public static void main(String[] args) { // Initialize sum float sum = 0; // Add 0.1, 0.2, ..., 0.9, 1 to sum while (sum != 1.0) {// while (sum <= 1.0) { sum += 0.1; // Display result System.out.println("The sum is " + sum); } } }
49
Problem:Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2.
50
GreatestCommonDivisor.javaimport java.util.Scanner; public class GreatestCommonDivisor { /** Main method */ public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter two integers System.out.print("Enter first integer: "); int n1 = input.nextInt(); System.out.print("Enter second integer: "); int n2 = input.nextInt(); int gcd = 1; int k = 2; while (k <= n1 && k <= n2) { if (n1 % k == 0 && n2 % k == 0) gcd = k; k++; } System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd); } }
51
Problem: Finding the Sales Amount
Problem: You have just started a sales job in a department store. Your pay consists of a base salary and a commission. The base salary is $5,000. The scheme shown below is used to determine the commission rate.
Sales Amount Commission Rate$0.01–$5,000 8 percent$5,000.01–$10,000 10 percent$10,000.01 and above 12 percent
Your goal is to earn $30,000 in a year. Write a program that will find out the minimum amount of sales you have to generate in order to make $30,000.
52
FindSalesAmount.javapublic class FindSalesAmount { /** Main method */ public static void main(String[] args) { // The commission sought final double COMMISSION_SOUGHT = 25000; final double INITIAL_SALES_AMOUNT = 0.01; double commission = 0; double salesAmount = INITIAL_SALES_AMOUNT; do { // Increase salesAmount by 1 cent salesAmount += 0.01; // Compute the commission from the current salesAmount; if (salesAmount >= 10000.01) commission = 5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12; else if (salesAmount >= 5000.01) commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10; else commission = salesAmount * 0.08; } while (commission < COMMISSION_SOUGHT); // Display the sales amount System.out.println( "The sales amount $" + (int)(salesAmount * 100) / 100.0 + "\nis needed to make a commission of $" + COMMISSION_SOUGHT); } }
53
Problem: Displaying a Pyramid of Numbers
Problem: Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid. For example, if the input integer is 12, the output is shown below.
54
PrintPyramid.java import java.util.Scanner; public class PrintPyramid { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter the number of lines System.out.print("Enter the number of lines: "); int numberOfLines = input.nextInt(); if (numberOfLines < 1 || numberOfLines > 15) { System.out.println("You must enter a number from 1 to 15"); System.exit(0); } // Print lines for (int row = 1; row <= numberOfLines; row++) { // Print NUMBER_OF_LINES – row) leading spaces for (int column = 1; column <= numberOfLines - row; column++) System.out.print(" "); // Print leading numbers row, row – 1, ..., 1 for (int num = row; num >= 1; num--) System.out.print((num >= 10) ? " " + num : " " + num); // Print ending numbers 2, 3, ..., row – 1, row for (int num = 2; num <= row; num++) System.out.print((num >= 10) ? " " + num : " " + num); // Start a new line System.out.println(); } } }
55
Using break and continueExamples for using the break and continue keywords:break: immediately ends the innermost loop that contains it. In other words, break breaks out of a loop.
continue: ends only the current iteration. Program control goes to the end of the loop body. In other words, continue breaks out of an iteration.
TestBreak.java
TestContinue.java
56
TestBreak.java and TestContinue.javapublic class TestBreak { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) break; } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } }
public class TestContinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) continue; sum += number; } System.out.println("The sum is " + sum); } }
57
Guessing Number Problem Revisited
Listing 4.2 gives a program for guessing a number. You can rewrite it using a break statement, as shown in Listing 4.13.
58
GuessNumberUsingBreak.javaimport java.util.Scanner; public class GuessNumberUsingBreak { public static void main(String[] args) { // Generate a random number to be guessed int number = (int)(Math.random() * 101); Scanner input = new Scanner(System.in); System.out.println("Guess a magic number between 0 and 100"); while (true) { // Prompt the user to guess the number System.out.print("\nEnter your guess: "); int guess = input.nextInt(); if (guess == number) { System.out.println("Yes, the number is " + number); break; } else if (guess > number) System.out.println("Your guess is too high"); else System.out.println("Your guess is too low"); } // End of loop } }
59
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.•Determine whether a given number is prime.•Count the prime numbers.•Print each prime number, and print 10 numbers per line.
60
PrimeNumbers.javapublic class PrimeNumber { public static void main(String[] args) { final int NUMBER_OF_PRIMES = 50; // Number of primes to display final int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line int count = 0; // Count the number of prime numbers int number = 2; // A number to be tested for primeness System.out.println("The first 50 prime numbers are \n"); // Repeatedly find prime numbers while (count < NUMBER_OF_PRIMES) { // Assume the number is prime boolean isPrime = true; // Is the current number prime? // Test if number is prime
61
PrimeNumbers.java for (int divisor = 2; divisor <= number / 2; divisor++) { if (number % divisor == 0) { // If true, number is not prime isPrime = false; // Set isPrime to false break; // Exit the for loop } } // Print the prime number and increase the count if (isPrime) { count++; // Increase the count if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { // Print the number and advance to the new line System.out.println(number); } else System.out.print(number + " "); } // Check if the next number is prime number++; } } }
62
(GUI) Controlling a Loop with a Confirmation Dialog
A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes or No to continue or terminate the loop. The template of the loop may look as follows:
int option = 0;while (option == JOptionPane.YES_OPTION) { System.out.println("continue loop"); option = JOptionPane.showConfirmDialog(null, "Continue?");}
63
SentinelValueUsingConfirmationDialog.java
import javax.swing.JOptionPane; public class SentinelValueUsingConfirmationDialog { public static void main(String[] args) { int sum = 0; // Keep reading data until the user answers No int option = 0; while (option == JOptionPane.YES_OPTION) { // Read the next data String dataString = JOptionPane.showInputDialog ( "Enter an int value: "); int data = Integer.parseInt(dataString); sum += data; option = JOptionPane.showConfirmDialog(null, "Continue?"); } JOptionPane.showMessageDialog(null, "The sum is " + sum); } }