0% found this document useful (0 votes)
16 views29 pages

04 Loops

Chapter 4 covers loop constructs in Java, including while, for, and do loops, as well as nested loops and common loop algorithms. It emphasizes the importance of hand-tracing program execution and provides examples for implementing loops in various applications, such as simulations and data processing. The chapter aims to equip readers with the skills needed to effectively use loops in programming.

Uploaded by

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

04 Loops

Chapter 4 covers loop constructs in Java, including while, for, and do loops, as well as nested loops and common loop algorithms. It emphasizes the importance of hand-tracing program execution and provides examples for implementing loops in various applications, such as simulations and data processing. The chapter aims to equip readers with the skills needed to effectively use loops in programming.

Uploaded by

b6642110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 29

CHAPTER 4

LOOPS

Slides by Donald W. Smith Final Draft


Copyright © 2013 by John Wiley & Sons. All rights reserved. TechNeTrain.com Oct 30, 2011
Chapter Goals
 To implement while, for, and do loops
 To hand-trace the execution of a program
 To become familiar with common loop algorithms
 To understand nested loops
 To implement programs that read and process
data sets
 To use a computer for simulations
In this chapter, you will learn about loop statements
in Java, as well as techniques for writing programs
that simulate activities in the real world.

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 2
Contents
 The while loop
 Problem Solving: Hand-Tracing
 The for loop
 The do loop
 Nested Loops
 Application: Random Numbers and Simulations

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 3
4.1 The while Loop
A loop executes instructions
repeatedly while a condition is true.

while (balance < TARGET)


{
year++;
double interest = balance *
RATE/100;
balance = balance + interest;
}

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 4
Syntax 4.1: while Statement

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 5
while Loop Examples (1)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 6
while Loop Examples (2)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 7
4.2: Hand-Tracing

 Example: Calculate the sum of digits (1+7+2+9)


 Make columns for key variables (n, sum, digit)
 Examine the code and number the steps
 Set variables to state before loop begins

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 8
Tracing Sum of Digits

 Start executing loop body statements


changing variable values on a new line
 Cross out values in previous line

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 9
Tracing Sum of Digits

 Continue executing loop statements changing


variables
 1729 / 10 leaves 172 (no remainder)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 10
Tracing Sum of Digits

 Test condition. If true, execute loop again


 Variable n is 172, Is 172 > 0?, True!
 Make a new line for the second time through and
update variables
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 11
Tracing Sum of Digits

 Third time through


 Variable n is 17 which is still greater than 0
 Execute loop statements and update variables

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 12
Tracing Sum of Digits

 Fourth loop iteration:


 Variable n is 1 at start of loop. 1 > 0? True
 Executes loop and changes variable n to 0 (1/10 = 0)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 13
Tracing Sum of Digits

 Because n is 0, the expression(n > 0) is False


 Loop body is not executed
 Jumps to next statement after the loop body
 Finally prints the sum!

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 14
4.3 The for Loop
 Use a for loop when you:
 Can use an integer counter variable
 Have a constant increment (or decrement)
 Have a fixed starting and ending value for the counter

int ii == 5;
int 5; //// initialize
initialize Use a for loop when a value
while (i
while (i <=
<= 10)
10) //// test
test runs from a starting point to an
{{ ending point with a constant
sum == sum
sum sum ++ 1;
1; increment or decrement.
while version
i++; // update
i++; // update
}}
for (int
for (int ii == 5;
5; ii <=
<= 10;
10; i++)
i++)
{{
sum ==
sum sum ++ i;
sum i;
for version
}}

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 15
Syntax 4.2: for Statement
 Two semicolons separate the three parts
 Initialization ; Condition ; Update

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 16
Good Examples of for Loops

 Keep it simple!

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 17
4.4 The do Loop
 Use a do loop when you want to:
 Execute the body at least once
 Test the condition AFTER your first loop

int ii == 1;
int 1; //// initialize
initialize
final int
final int FINGERS
FINGERS == 5;
5;
do
do
{{
// paint
// paint finger
finger
i++; //
i++; // update
update
}}
while (i
while (i <=
<= FINGERS);
FINGERS); //// test
test

Note the semicolon at the end!


Copyright © 2013 by John Wiley & Sons. All rights reserved.
.
Page 18
do Loop Example
 User Input Validation:
 Range check a value entered
 User must enter something to validate first!
int value;
int value;
do
do
{{
System.out.println(“Enter an
System.out.println(“Enter an integer
integer << 100:
100:
”);
”);
value == in.nextInt();
value in.nextInt();
}}
while (value
while (value >=
>= 100);
100); //
// test
test

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 19
4.5 Common Loop Algorithms

1: Sum and Average Value


2: Counting Matches
3: Finding the First Match
4: Prompting until a match is found
5: Maximum and Minimum
6: Comparing Adjacent Values

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 20
Sum and Average Examples
double total
double total == 0; 0;  Sum of Values
while (in.hasNextDouble())
while (in.hasNextDouble())  Initialize total to 0
{{  Use while loop with sentinel
double input
double input ==
in.nextDouble();
in.nextDouble();
total == total
total total ++ input; input;
}} double total
double total == 0;0;
 Average of Values int count
int count == 0;
0;
while (in.hasNextDouble())
(in.hasNextDouble())
 Use Sum of Values while
{{
 Initialize count to 0 double input
double input ==
 Increment per in.nextDouble();
in.nextDouble();
total == total
total total ++ input;
input;
input count++;
count++;
 Check for count 0 }}
double average
double average == 0; 0;
 Before divide!
if (count
if (count >> 0)
0)
Copyright © 2013 by John Wiley & Sons. All rights reserved.
{{ average
average == total
total // count;count; Page
}} 21
Counting Matches
int upperCaseLetters
int upperCaseLetters == 0; 0;
 Counting Matches
for (int
for (int ii == 0;
0; ii << str.length();
str.length();
 Initialize count to 0 i++)
i++)
{{
 Use a for loop char ch
char ch == str.charAt(i);
str.charAt(i);
 Add to count per if (Character.isUpperCase(ch))
if (Character.isUpperCase(ch))
match {{
upperCaseLetters++;
upperCaseLetters++;
}}
}}

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 22
Maximum and Minimum
double largest
double largest ==
in.nextDouble();
in.nextDouble();
while (in.hasNextDouble())
while (in.hasNextDouble()) double smallest
double smallest ==
{{ in.nextDouble();
in.nextDouble();
double input
double input == while (in.hasNextDouble())
while (in.hasNextDouble())
in.nextDouble();
in.nextDouble(); {{
if (input
if (input >> largest)
largest) double input
double input ==
{{ in.nextDouble();
in.nextDouble();
largest == input;
largest input; if (input
if (input >> smallest)
smallest)
}} {{
}} Get first input value smallest == input;
smallest input;
 This is the largest (or smallest)}}that you have seen so far!
}}
 Loop while you have a valid number (non-sentinel)
 Get another input value
 Compare new input to largest (or smallest)
 Update largest (or smallest) if necessary
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 23
4.8 Nested Loops
 How would you print a table with rows
and columns?
 Print top line (header)
• Use a for loop
 Print table body…
• How many rows?
• How many columns?
 Loop per row
• Loop per column

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 24
PowerTable.java

Body of outer loop

Body of inner loop

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 25
Nested Loop Examples (1)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 26
Nested Loop Examples (2)

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 27
RandomDemo.java

Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 28
Copyright © 2013 by John Wiley & Sons. All rights reserved. Page 29

You might also like