Lecture 5 Loop.ppt
Lecture 5 Loop.ppt
1
Motivation
Suppose that you need to print a string (e.g.,
"Welcome to Java!") a thousand times. It would
be tedious to have to write the following
statement a hundred times:
System.out.println("Welcome to
Java!");
2
Motivation
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!");
1000 …
times …
…
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
3
Motivation
A solution using While Loop:
int count = 0;
while (count < 1000)
{
System.out.println("Welcome to Java!");
count++;
}
4
1. Loop Statements
• Loops are repetition statements that allow us to
execute a statement (or block of statements)
multiple times
• Like conditional statements, they are controlled by
boolean expressions
• Java has three types of loop statements:
– the while loop
– the do-while loop
– the for loop
• The programmer should choose the right type of
loop for the situation at hand
5
Loop Statements
• The while and do-while loops are also called
conditional loops since they use boolean
expressions to control the loop behavior
• The while and do-while loops run
un-determined (unknown) number of iterations
(some call them non-deterministic loops)
• The for loop, on the other hand, runs a
pre-determined (known) number of iterations
(some call it deterministic loop or counting
loop)
6
2. while Loop Statement
7
while Loop Logic
conditio
n
evaluate
d Note: If the initial evaluation
of the condition is false, the
tru fals loop body executes zero
e e times. Therefore, the while
loop executes zero or more
Statement block
(loop body) times
Next Line
8
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
9
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
10
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
11
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now
12
Trace while Loop, cont.
(count < 2) is still true since count is 1
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
13
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
14
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now
15
Trace while Loop, cont.
(count < 2) is false since count is 2
int count = 0; now
16
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
17
while Loop Example
18
while Loop Sentinel Value
Question: How can we control a while loop?
19
Sentinel Value Example
// Demonstrates the use of a while loop using a sentinel value
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
public static void main (String[] args)
{ int sum = 0, value, count = 0;
double average;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
while (value != 0) //sentinel value of 0 to terminate loop
{ count = count + 1;
sum = sum + value;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
System.out.println ();
if (count == 0)
System.out.println ("No values were entered.");
else
System.out.println ("Sum of all values = " + sum);
}
}
20
while Loops for Input Validation
21
Input Validation Example
// Demonstrates the use of a while loop for input validation
import java.text.NumberFormat;
import java.util.Scanner;
public class WinPercentage
{
public static void main (String[] args)
{
final int NUM_GAMES = 12;
int won;
double ratio;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of games won (0 to "
+ NUM_GAMES + "): ");
won = scan.nextInt();
//input validation
while (won < 0 || won > NUM_GAMES)
{
System.out.print ("Invalid input. Please reenter: ");
won = scan.nextInt();
}
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println ();
System.out.println ("Winning percentage: " + fmt.format(ratio));
}
}
22
3. do-while Loop
23
Logic of do-while Loop
Statement
Block conditio
n
Loop body evaluate
d
tru fals
tru
e e e
conditio Statement
n block
evaluate
d
Next Line
24
do-while Loop Example
• An example of a do loop:
int count = 0;
do
{
count = count +1;
System.out.println (count);
} while (count < 5);
25
do-while Loop Example
// Demonstrates the use of a do loop
import java.util.Scanner;
public class ReverseNumber
{
public static void main (String[] args)
{
int number, lastDigit, reverse = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a positive integer: ");
number = scan.nextInt();
do
{
lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
number = number / 10;
} while (number > 0);
26
4. for Loop
27
for Loop Logic
While Loop
initializatio
conditio
n n
evaluate
conditio d
n tru fals
evaluate e e
d statement block
tru fals
e e
statement
block
Like a while loop, the condition of a for
increme
nt loop is tested prior to executing the loop
body. Therefore, the for loop body will
execute zero or more times
28
Trace for Loop
Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
29
Trace for Loop, cont.
Execute initializer
i is now 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
30
Trace for Loop, cont.
(i < 2) is true
since i is 0
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
31
Trace for Loop, cont.
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
32
Trace for Loop, cont.
Execute adjustment statement
i now is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
33
Trace for Loop, cont.
(i < 2) is still true
since i is 1
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
34
Trace for Loop, cont.
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
35
Trace for Loop, cont.
Execute adjustment statement
i now is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
36
Trace for Loop, cont.
(i < 2) is false
since i is 2
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
37
Trace for Loop, cont.
Exit the loop. Execute the next
statement after the loop
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
38
for Loop as a while Loop
initialization;
while (condition)
{
statement block;
increment;
}
39
for to while Loop Example
• The for loop:
for (int count=1; count <= 5; count = count+1)
System.out.println (count);
int count = 1;
while (count <= 5)
{
System.out.println (count);
count = count + 1;
}
40
for Loop Example
41
for Loop Example
// Demonstrates the use of a for loop to print multiples of a number
import java.util.Scanner;
public class Multiples
{
public static void main (String[] args)
{
final int PER_LINE = 5;
int value, limit, multiple, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a positive value: ");
value = scan.nextInt();
System.out.print ("Enter an upper limit: ");
limit = scan.nextInt();
System.out.println ();
System.out.println ("The multiples of " + value + " between " +
value + " and " + limit + " (inclusive) are:");
for (multiple = value; multiple <= limit; multiple = multiple + value)
{
System.out.print (multiple + "\t");
// Print a specific number of values per line of output
count = count + 1;
if (count % PER_LINE == 0)
System.out.println(); // go to next line
}
}
}
42
5. Infinite Loops
43
Example
44
Be Careful!
45
6. Nested Loops
46
Example
// Demonstrates the use of nested while loops.
import java.util.Scanner;
public class PalindromeTester
{
public static void main (String[] args)
{ String str, another = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome string:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right)
{
left = left + 1;
right = right - 1;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
47
Example
// Demonstrates the use of nested for loops to print starts
public class Stars
{
public static void main (String[] args)
{
final int MAX_ROWS = 10;
*
for (int row = 1; row <= MAX_ROWS; row++) **
{ ***
****
for (int star = 1; star <= row; star++) *****
System.out.print ("*"); ******
*******
********
*********
System.out.println(); **********
}
}
}
48
Nested Loops Iterations
How many times will the string "I am here" be printed?
// Demonstrates the use of nested loops
public class NestedLoops
{
public static void main (String[] args)
{ String str, another = "y";
int count1 = 1;
while (count1 <= 10)
{
int count2 = 1;
while (count2 <= 5)
{
System.out.println("I am here!");
count2 = count2 + 1;
}
System.out.println(); // blank line
count1 = count1 + 1;
}
}
} 49
7. Using break and continue
Examples for using the break statement:
// demonstrate break statement
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
50
Using break and continue
Examples for using the continue statement:
// demonstrate continue statement
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
}
}
51