0% found this document useful (0 votes)
50 views20 pages

Repetition Statement (Loops)

The document discusses different types of repetition statements or loops in Java including while, do-while, and for loops. It provides examples of using each loop type to repeatedly print a string 100 times to demonstrate how loops can solve the problem of repetitive code. The key aspects covered are: - While loops execute a block of code as long as a given condition is true. - Do-while loops are similar but execute the block of code at least once even if the condition is false initially. - For loops allow specifying an initialization, condition, and increment in one statement and are commonly used when the number of iterations is known.

Uploaded by

wasik mahir
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)
50 views20 pages

Repetition Statement (Loops)

The document discusses different types of repetition statements or loops in Java including while, do-while, and for loops. It provides examples of using each loop type to repeatedly print a string 100 times to demonstrate how loops can solve the problem of repetitive code. The key aspects covered are: - While loops execute a block of code as long as a given condition is true. - Do-while loops are similar but execute the block of code at least once even if the condition is false initially. - For loops allow specifying an initialization, condition, and increment in one statement and are commonly used when the number of iterations is known.

Uploaded by

wasik mahir
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
You are on page 1/ 20

Repetition Statement (Loops)

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?

Liang, Introduction to Java Programming, Eighth Edition, (c)


Liang, Introduction to Java 1
2011 Programming, Eighth
Pearson Education, Edition,
Inc. All (c) 2011
rights reserved. Pearson Education, Inc. All
0132130807
rights reserved. 0132130807
Opening Problem

System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times



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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 2
rights reserved. 0132130807
Introducing while Loops

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 3
rights reserved. 0132130807
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;

(A) (B)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 4
rights reserved. 0132130807
Trace while Loop

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 5
rights reserved. 0132130807
Problem: Guessing Numbers

Write a program that randomly generates an integer between 0 and 10,


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:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 6
rights reserved. 0132130807
Guessing Numbers

import java.util.Scanner;

public class GuessNumberUsingBreak {


public static void main(String[] args) {
// Generate a random number to be guessed
int number = (int)(Math.random() * 11);
Scanner input = new Scanner(System.in);
System.out.println("Guess a magic number between 0 and 10");

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 7
rights reserved. 0132130807
Guessing Numbers
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
} // end main function
} // end of class

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 8
rights reserved. 0132130807
do-while Loop

Statement(s)
(loop body)

true Loop
Continuation
do { Condition?
// Loop body; false
Statement(s);
} while (loop-continuation-condition);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 9
rights reserved. 0132130807
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) {
// loop body; System.out.println(
Statement(s); "Welcome to Java!");
} }

Initial-Action i=0

Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");

Action-After-Each-Iteration i++

(A) (B)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 10
rights reserved. 0132130807
Trace for Loop

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 11
rights reserved. 0132130807
Note
The 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
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 12
rights reserved. 0132130807
Note
If 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 ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 13
rights reserved. 0132130807
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);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 14
rights reserved. 0132130807
Caution, cont.
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++; Correct
} while (i<10);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 15
rights reserved. 0132130807
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):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )
// Loop body // Loop body
} }
(a) (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; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 16
rights reserved. 0132130807
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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 17
rights reserved. 0132130807
Nested Loops

Problem: Write a program that uses nested for


loops to print a multiplication table.

Using break and continue

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 18
rights reserved. 0132130807
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.

GreatestCommonDivisor Run
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 19
rights reserved. 0132130807
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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 20
rights reserved. 0132130807

You might also like