0% found this document useful (0 votes)
3 views14 pages

Java Loop Control Structures Explained

Uploaded by

labtopahmed1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Java Loop Control Structures Explained

Uploaded by

labtopahmed1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5.

1 Introduction

Ѻ A loop can be used to tell a program to execute statements repeatedly; a loop controls how many times
an operation or a sequence of operations is performed in succession.

Ѻ I.e. suppose that you can display a string (Welcome to Java!) a hundred times as follows:

Ѻ The variable count is initially 0. The loop checks whether count < 100 is true. If so, it executes the loop
body; and increments count by 1. It repeatedly executes the loop body until count < 100 becomes false.

5.2 While loop

Ѻ A while loop executes statements repeatedly while the condition is true.

Ѻ The syntax for the while loop is:

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

Ѻ Recall the example for displaying Welcome to Java! A hundred times; you know exactly how many times
the loop body needs to be executed because the control variable count is used to count the number of
executions. This type of loop is known as a counter-controlled loop.

Ѻ A common programming error involves infinite loops (i. e., the loop runs forever); and this may be as a
result of forgetting the increment statement.

1|Page
Ѻ Programmers often make the mistake of executing a loop one more or less time. This is commonly
known as the off-by-one error; I.e. the following loop displays Welcome to Java 101 times rather than
100 times. The error lies in the condition, which should be count < 100 rather than count <= 100.

 5.2.1 Case Study: Guessing Numbers

Ѻ You will 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.

2|Page
 5.2.2 Controlling a Loop with a Sentinel Value

Ѻ A sentinel-controlled loop is a loop that uses a sentinel value to control its execution.

Ѻ A sentinel value is a special input value that is designated when reading and processing a set of values.

Ѻ You will write a program that reads and calculates the sum of an unspecified number of integers. The
input 0 signifies the end of the input. You can use one variable named data (line 12) to store the input
value and use a variable named sum (line 15) to store the total.

 5.2.3 Input and Output Redirections

Ѻ Input redirection; which store the data separated by whitespaces in a text file, say [Link]. The
command for input redirection is:

3|Page
Ѻ Output redirection; which sends the output to a file rather than displaying it on the console. The
command for output redirection is:

5.3 do...While loop

Ѻ A do-while loop is the same as a while loop except that it executes the loop body first and then checks
the loop continuation condition.

Ѻ The do-while loop is a variation of the while loop. Its syntax is:

Ѻ If the evaluation is true, the loop body is executed again; if it is false, the do-while loop terminates.

Ѻ For example, you can rewrite the while loop using a do-while loop.

4|Page
5.4 For loop

Ѻ A for loop has a concise syntax for writing loops.

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

Ѻ For example, the following for loop prints Welcome to Java! a hundred times:

Ѻ The initial-action, i = 0, initializes the control variable, i. The loop-continuation-condition, i < 100, is a
Boolean expression. The expression is evaluated right after the initialization and at the beginning of
each iteration. The action-after-each-iteration, i++, is a statement that is executed after each iteration
and increments the control variable.

5.5 Which Loop to Use?

Ѻ The while loop and for loop are called pretest loops because the continuation condition is checked
before the loop body is executed. The do-while loop is called a posttest loop because the condition is
checked after the loop body is executed.

Ѻ The three forms of loop statements—while, do-while, and for—are expressively equivalent;

Ѻ For example, a while loop in (a) in the following figure can always be converted into the for loop in (b).

5|Page
Ѻ For example, A for loop in (a) in the next figure can generally be converted into the while loop in (b).

Ѻ A for loop may be used if the number of repetitions is known in advance; A while loop may be used if the
number of repetitions is not fixed; A do-while loop can be used to replace a while loop if the loop body
has to be executed before the continuation condition is tested.

Ѻ Adding a semicolon at the end of the for clause before the loop body is a common mistake.

5.6 Nested Loops

Ѻ Nested loops consist of an outer loop and one or more inner loops.

Ѻ For example, this is a program that uses nested for loops to display a multiplication table.

6|Page
1. The program displays a title (line 5) on the first line in the output.
2. The first for loop (lines 9–10) displays the numbers 1 through 9 on the second line.
3. A dashed line (line 12) is displayed on the third line.
4. The next loop (lines 15–22) is a nested for loop with the control variable i in the outer loop and j in
the inner loop. For each i, the product i * j is displayed on a line in the inner loop.

5.7 Minimizing Numeric Errors

Ѻ Using floating-point numbers in the loop continuation condition may cause numeric errors.

Ѻ For example, this is a program summing a series that starts with 0.01 and ends with 1.0.

Ѻ The for loop (lines 7–8) repeatedly adds the control variable i to sum. This variable, which begins with
0.01, is incremented by 0.01 after each iteration. The loop terminates when i exceeds 1.0.

Ѻ The exact sum should be 50.50, but the answer is 50.499985. The result is imprecise because
computers use a fixed number of bits to represent floating-point numbers.

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

7|Page
Ѻ However, you will be stunned to see that the result is actually 49.50000000000003. The fundamental
problem is that the floating-point numbers are represented by approximation. To fix the problem, use
an integer count to ensure that all the numbers are added to sum. Here is the new loop:

5.8 Case Studies

 5.8.1 Case Study: Finding the Greatest Common Divisor

Ѻ How would you write this program to find the greatest common divisor?

1. Let the two input integers be n1 and n2.

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

3. Store the common divisor in a variable named gcd. Initially, gcd is 1.

4. Whenever a new common divisor is found, it becomes the new gcd.

5. When you have checked all the possible common divisors from 2 up to n1 or n2, the value in
variable gcd is the greatest common divisor.

6. Once you have a logical solution, type the code to translate the solution into a Java program
as follows:

8|Page
 5.8.2 Case Study: Predicting the Future Tuition

Ѻ 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?

Ѻ How would you write this program to predict the Future Tuition?

1. The tuition for a future year is the tuition of its preceding year * 1.07.

2. Keep computing the tuition for a new year until it is at least 20000.

3. By then you will know how many years it will take for the tuition to be doubled.

4. Once you have a logical solution, type the code to translate the solution into a Java program
as follows:

9|Page
5.9 Keywords break and continue

Ѻ The break statement is typically used to exit early from a loop (for, while, do…while).

Ѻ After the break statement, the remaining of the statements inside the loop are skipped. Then, execution
continues starting at the first statement after the loop.

Ѻ For example; the following program adds integers from 1 to 20 in this order to sum until sum is greater
than or equal to 100. With the if statement, the loop terminates when sum becomes greater than or
equal to 100.

10 | P a g e
Ѻ The continue statement may be used in all loop statements (for, while, do…while).

Ѻ The continue statement skips the remaining statements inside the loop; and proceeds with the next
iteration, if any.

Ѻ For example; the following program adds integers from 1 to 20 except 10 and 11 to sum. With the if
statement, the continue statement is executed when number becomes 10 or 11. The continue statement
ends the current iteration so that the rest of the statement in the loop body is not executed.

5.10 Case Study: Checking Palindromes

Ѻ A string is a palindrome if it reads the same forward and backward. For examples; the words “mom,”
“dad,” and “noon,” for instance, are all palindromes.

Ѻ The problem is to write a program that prompts the user to enter a string and reports whether the
string is a palindrome.

1. First you check whether the first character in the string is the same as the last character.

2. If so, check whether the second character is the same as the second-to-last character.

3. This process continues until a mismatch is found or all the characters in the string are checked,
except for the middle character if the string has an odd number of characters.

11 | P a g e
5.11 Case Study: Displaying Prime Numbers

Ѻ The problem is to write a program that display the first 50 prime numbers in five lines, each of which
contains ten numbers. The problem can be broken into the following tasks:

1. Determine whether a given number is prime.

2. For number = 2, 3, 4, 5, 6, ..., test whether it is prime.

3. Count the prime numbers.

4. Display each prime number, and display ten numbers per line.

12 | P a g e
Ѻ Here is the algorithm for the problem:

1. Set the number of prime numbers to be printed as a constant NUMBER_OF_PRIMES;

2. Use count to track the number of prime numbers and set an initial count to 0;

3. Set an initial number to 2;

4. To test whether a number is prime, check whether it is divisible by 2, 3, 4, and so on up to


number/2. If a divisor is found, the number is not a prime.

13 | P a g e

You might also like