Chapter 4 Loops, Exercises of Computer Programming

program will terminate. • A common programming error involves infinite loops. Loop. Continuation. Condition? true. Statement( ...

Typology: Exercises

2022/2023

Uploaded on 02/28/2023

ameen
ameen 🇺🇸

4.6

(5)

236 documents

1 / 25

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CMPS161 Class Notes (Chap 04) Kuo-pao Yang
Page 1 /25
Chapter 4
Loops
4.1 Introduction
Loops are structures that control repeated executions of a block of statements.
Java provides a powerful control structure called a loop, which controls how many
times an operation or a sequence of operation is performed in succession.
Java provides three types of loop statements while loops, do-while loops, and for
loops.
4.2 The while Loop
The syntax for the while loop is as follows:
while (loop-continuation-condition) {
// loop-body
Statement(s);
}
The braces enclosing a while loop or any other loop can be omitted only if the loop
body contains one or no statement. The while loop flowchart is in Figure (a).
The loop-continuation-condition, a Boolean expression, must appear inside the
parentheses. It is always evaluated before the loop body is executed.
If its evaluation is true, the loop body is executed; if its evaluation is false, the entire
loop terminates, and the program control turns to the statement that follows the while
loop.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Chapter 4 Loops and more Exercises Computer Programming in PDF only on Docsity!

Chapter 4

Loops

4.1 Introduction

  • Loops are structures that control repeated executions of a block of statements.
  • Java provides a powerful control structure called a loop , which controls how many times an operation or a sequence of operation is performed in succession.
  • Java provides three types of loop statements while loops, do-while loops, and for loops.

4.2 The while Loop

  • The syntax for the while loop is as follows:

while (loop-continuation-condition) { // loop-body Statement(s); }

  • The braces enclosing a while loop or any other loop can be omitted only if the loop body contains one or no statement. The while loop flowchart is in Figure (a).
  • The loop-continuation-condition, a Boolean expression, must appear inside the parentheses. It is always evaluated before the loop body is executed.
  • If its evaluation is true , the loop body is executed; if its evaluation is false, the entire loop terminates, and the program control turns to the statement that follows the while loop.
  • For example, the following while loop prints Welcome to Java! 100 times.

int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }

FIGURE 4.1 The while loop repeatedly executes the statements in the loop body when the loop-continuation-condition evaluates to true.

Caution

  • Make sure that the loop-continuation-condition eventually becomes false so that the program will terminate.
  • A common programming error involves infinite loops.

Loop Continuation Condition? true Statement(s) (loop body)

false (count < 100)?

true System.out.println("Welcome to Java!"); count++;

false

(A) (B)

count = 0;

4.2.3 Example: An Advanced Math Learning Tool (Page 121)

  • 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.
  • LISTING 4.3 SubtractionQuizLoop.java

import 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 = ""; // output string is initially empty 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);

// 2. If number1 < number2, swap number1 with number 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();

// 4. Grade the answer and display the result if (number1 - number2 == answer) { System.out.println("You are correct!"); correctCount++; } else System.out.println("Your answer is wrong.\n" + number

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

What is 9 - 2? 7 Your answer is correct!

What is 3 - 0? 3 Your answer is correct!

What is 3 - 2? 1 Your answer is correct!

What is 7 - 4? 4 Your answer is wrong. 7 - 4 should be 3

What is 7 - 5? 4 Your answer is wrong. 7 - 5 should be 2

Correct count is 3 Test time is 1021 seconds Ï 9-2=7 correct 3-0=3 correct 3-2=1 correct 7-4=4 wrong 7-5=4 wrong

Caution

  • Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:

double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum);

  • Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0 , because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop.

4.2.5 Input and Output Redirections

  • If you have a large number of data to enter, it would be cumbersome to type from the key board. You may store the data separated by whitespaces in a text file, say input.txt, and run the program using the following command:

java SentinelValue < input.txt

  • This command is called input redirection. The program takes the input from the file input.txt rather thatn having the user to type the data from the keyboard at runtime.
  • There is output redirection which sends the output to a file rather than displaying it on the console. The command for output redirection is:

java ClassName > output.txt

  • Input and output redirection can be used in the same command. For example, the following command gets input from input.txt and sends output to output.txt:

java SentinelValue < input.txt > output.txt

  • You can rewrite the TestWhile program shown previously as follows:
  • LIST 4.5 TestDoWhile.java ( Page 125)

import java.util.Scanner;

public class TestDoWhile { /** Main method */ public static void main(String[] args) { int data; int sum = 0;

// Create a Scanner Scanner input = new Scanner(System.in);

// Keep reading data until the input is 0 do { // Read the next data System.out.print( "Enter an int value (the program exits if the input is 0): "); data = input.nextInt();

sum += data; } while (data != 0);

System.out.println("The sum is " + sum); } }

Enter an int value (the program exits if the input is 0): 2 Enter an int value (the program exits if the input is 0): 3 Enter an int value (the program exits if the input is 0): 4 Enter an int value (the program exits if the input is 0): 0 The sum is 9

4.4 The for Loop

  • The syntax of a for loop is as shown below.

for (initial-action; loop-continuation-condition; action-after-each-iteration) { //loop body; Statement(s); }

  • The for loop statement starts with the keyword for , followed by a pair of parentheses enclosing initial- action, loop-continuation-condition , and action-after-each-iteration, and the loop body, enclosed inside braces.
  • initial- action, loop-continuation-condition , and action-after-each-iteration are separated by semicolons ;
  • A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates.
  • This variable is referred to as a control variable. The initial-action often initializes a control variable, the action-after-each-iteration usually increments or decrements the control variable, and the loop-continuation-condition tests whether the control variable has reached a termination value.
  • Example: The following for loop prints Welcome to Java! 100 times.

int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java! ”); }

FIGURE 4.3 A for loop performs an initial action one, then repeatedly executes the statements in the loop body, and performs an action after an iteration when the loop- continuation-condition evaluates as true

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

4.5 Which Loop to Use?

  • The three forms of loop statements, while , do , 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.

Recommendations

  • The author recommends that you 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.

while (loop-continuation-condition) { // Loop body } (a)

Equivalent

(b)

for ( ; loop-continuation-condition; ) // Loop body }

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; }

Caution

  • Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:

for (int i = 0; i < 10; i++); // Logic Error (‘;’) { System.out.println("i is " + i); }

  • Similarly, the following loop is also wrong:

int i=0; while (i<10); // Logic Error (‘;’) { 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); // Correct, The semicolon is needed

4.7 Minimizing Numerical Errors

  • Numeric errors involving floating-point numbers are inevitable.
  • Write a program 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.
  • LISTING 4.7 TestSum.java ( Page 130)

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

o The for loop repeatedly adds the control variable i to the sum. This variable, which begins with 0.01, is incremented by 0.01 after each iteration. The loop terminates when i exceeds 1.0. o The exact sum should be 50.50 , but the answer is 50.499985. The result is not precise because computers use a fixed number of bits to represent floating-point numbers, and thus cannot represent some floating-point number exactly.

  • If you change float in the program to double as follows, you should see a slight improvement in precision because a double variable takes 64 bits, whereas a float variable takes 32 bits.

public class TestSum { public static void main(String[] args) { // Initialize sum double sum = 0;

// Add 0.01, 0.02, ..., 0.99, 1 to sum for (double i = 0.01; i <= 1.0; i = i + 0.01) sum += i;

// Display result System.out.println("The sum is " + sum); } }

The sum is 50.

The sum is 49.

  • To fix the problem: Using an integer count to ensure that all the numbers are processed.

public class TestSum { public static void main(String[] args) { // Initialize sum double sum = 0; double currentValue = 0.01;

// Add 0.01, 0.02, ..., 0.99, 1 to sum for (int count = 0; count < 100; count++) { sum += currentValue; currentValue += 0.01; }

// Display result System.out.println("The sum is " + sum); } }

The sum is 50.

4.8.2 Problem: Predicating the Future Tuition (Page 133)

  • Problem: Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled?

double tuition = 10000; int year = 1 // Year 1 tuition = tuition * 1.07; year++; // Year 2 tuition = tuition * 1.07; year++; // Year 3 tuition = tuition * 1.07; year++; // Year 4 ...

  • LISTING 4.9 FutureTuition.java ( Page 133 )

public class FutureTuition { public static void main(String[] args) { double tuition = 10000; // Year 1 int year = 1; while (tuition < 20000) { tuition = tuition * 1.07; year++; }

System.out.println("Tuition will be doubled in "

  • year + " years"); } }

Tuition will be doubled in 12 years

4.9 Keywords break and continue

  • The break control immediately ends the innermost loop that contains it. It is generally used with an if statement.
  • The continue control only ends the current iteration. Program control goes to the end of the loop body. This keyword is generally used with an if statement.
  • The break statement forces its containing loop to exit.
  • The continue statement forces the current iteration of the loop to end.

false

true

Statement(s)

Next Statement

Continue condition?

Statement(s)

continue

false

true

Statement(s)

Next Statement

Continuation condition?

Statement(s)

break