and Conditional Statements Loops for and while 1 2 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements they are controlled by boolean expressions ID: 693534
Download Presentation The PPT/PDF document "Chapter 3 Part 2 More about Strings" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Chapter 3 Part 2
More about Strings andConditional StatementsLoops (for and while)
1Slide2
2
Repetition Statements
Repetition statements
allow us to execute a statement multiple times
Often they are referred to as
loops
Like conditional statements, they are controlled by boolean expressions
The text covers two kinds of repetition statements:
the
while loop
the
for loop
The programmer should choose the right kind of loop for the situationSlide3
3
The while Statement
The
while statement
has the following syntax:
while (
condition
)
statement;
while
is areserved word
If the
condition
is true, the statement is executed.Then the condition is evaluated again.
The
statement
is executed repeatedly until
the
condition
becomes false.Slide4
4
Logic of a while Loop
statement
true
condition
evaluated
falseSlide5
5
The while Statement
Note that if the condition of a
while
statement is false initially, the statement is never executed
Therefore, the body of a
while
loop will execute zero or more times
See
Counter.java (page 147)See Average.java (page 148)A sentinel
value indicates the end of the inputThe variable
sum maintains a running sumSee WinPercentage.java (page 151)A loop is used to validate the input, making the program more robustSlide6
while (value != 0) // sentinel value of 0 to terminate loop
{ count++; 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 (); System.out.println ("Number of values entered: " + count); average = (double)sum / count; DecimalFormat fmt
= new DecimalFormat ("0.###");
System.out.println ("The average is " + fmt.format(average)); }}6Slide7
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)); }}
7Slide8
8
Infinite Loops
The body of a
while
loop eventually must make the condition false
If not, it is an
infinite loop
, which will execute until the user interrupts the program
This is a common logical error
You should always double check to ensure that your loops will terminate normallySee Forever.java (page 152) Slide9
public class Forever
{ //----------------------------------------------------------------- // Prints ever-decreasing integers in an INFINITE LOOP! //----------------------------------------------------------------- public static void main (String[]
args
)
{
int
count = 1;
while (count <= 25)
{ System.out.println (count); count = count - 1; } System.out.println ("Done"); // this statement is never reached }}
9Slide10
10
Nested Loops
Similar to nested
if
statements, loops can be nested as well
That is, the body of a loop can contain another loop
Each time through the outer loop, the inner loop goes through its full set of iterations
See
PalindromeTester.java
(page 155)Slide11
while (
another.equalsIgnoreCase("y")) // allows y or Y { System.out.println ("Enter a potential palindrome:");
str
=
scan.nextLine
();
left = 0;
right =
str.length
() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; }
11Slide12
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(); } }}12Slide13
Conditional Operator
Conditional operators are a shortcut way to express an if-else situation. Format:
result = (condition)? value1 : value2;
13
“if” part
“else” partSlide14
Conditional Operator
14
Example: (
orig
if-else
)
i
f (x > 0)
count = count + 1;
else count = count – 1;
Example:
(cond. operator)count =(x > 0)? (count +
1) : (count – 1);Slide15
The Do-While Loop
The do-while loop works like the while loop, BUT in a different order. The do portion is done first, before the while condition is checked.Format:
15
do
{
… statements for what to do
}
w
hile (condition); Slide16
Example of Do-While loop
int count = 0; int sum = 0;
do
{
sum = sum + count;
count ++;
} while (count < 10);16
Notice the while condition is not checked until the do loop is executed at least once.Slide17
17
The for Statement
The
for statement
has the following syntax:
for (
initialization
;
condition
; increment )
statement
;Reserved
word
The
initializationis executed oncebefore the loop begins
The
statement
is
executed until the
condition
becomes false
The
increment
portion is executed at the end of each iteration
The
condition
-
statement
-
increment
cycle is executed repeatedlySlide18
18
The for StatementA
for
loop is functionally equivalent to the following
while
loop structure:
initialization
;
while (
condition )
{
statement; increment;}Slide19
19
Logic of a for loop
statement
true
condition
evaluated
false
increment
initializationSlide20
20
The for Statement
Like a
while
loop, the condition of a
for
statement is tested prior to executing the loop body
Therefore, the body of a
for
loop will execute zero or more timesIt is well suited for executing a loop a specific number of times that can be determined in advanceSee Counter2.java (page 161)See Multiples.java (page 163)See
Stars.java (page 165)Slide21
public class Counter2
{ //----------------------------------------------------------------- // Prints integer values from 1 to a specific limit. //----------------------------------------------------------------- public static void main (String[]
args
)
{
final
int
LIMIT = 5;
for (
int count=1; count <= LIMIT; count++) System.out.println (count); System.out.println ("Done"); }}21Slide22
final
int PER_LINE = 5; int value, limit, mult, 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 (
mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t"); // Print a specific number of values per line of output
count++; if (count % PER_LINE == 0) System.out.println();
} }
22Slide23
public class Stars
{ //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- 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(); }
}}
23Slide24
24
The for StatementEach expression in the header of a for loop is optional
If the
initialization
is left out, no initialization is performed
If the
condition
is left out, it is always considered to be true, and therefore creates an infinite loop
If the
increment is left out, no increment operation is performedBoth semi-colons are always required in the for loop headerSlide25
25
Choosing a Loop Structure
When you can’t determine how many times you want to execute the loop body, use a
while
statement
If you can determine how many times you want to execute the loop body, use a
for
statementSlide26
26
Program Development
We now have several additional statements and operators at our disposal
Following proper development steps is important
Suppose you were given some initial requirements:
accept a series of test scores
compute the average test score
determine the highest and lowest test scores
display the average, highest, and lowest test scoresSlide27
27
Program Development
Requirements Analysis – clarify and flesh out specific requirements
How much data will there be?
How should data be accepted?
Is there a specific output format required?
After conferring with the client, we determine:
the program must process an arbitrary number of test scores
the program should accept input interactively
the average should be presented to two decimal placesThe process of requirements analysis may take a long timeSlide28
28
Program Development
Design – determine a possible general solution
Input strategy? (Sentinel value?)
Calculations needed?
An initial algorithm might be expressed in pseudocode
Multiple versions of the solution might be needed to refine it
Alternatives to the solution should be carefully consideredSlide29
29
Program Development
Implementation – translate the design into source code
Make sure to follow coding and style guidelines
Implementation should be integrated with compiling and testing your solution
This process mirrors a more complex development model we'll eventually need to develop more complex software
The result is a final implementation
See
ExamGrades.java
(page 170)Slide30
max = min = grade;
// Read and process the rest of the grades while (grade >= 0) { count++; sum += grade;
if (grade > max)
max = grade;
else
if (grade < min)
min = grade;
System.out.print
("Enter the next grade (-1 to quit): "); grade = scan.nextInt (); }30Slide31
// Produce the final results
if (count == 0) System.out.println ("No valid grades were entered."); else {
DecimalFormat
fmt
= new
DecimalFormat
("0.##");
average = (double)sum / count; System.out.println(); System.out.println ("Total number of students: " + count); System.out.println ("Average grade: " + fmt.format(average)); System.out.println ("Highest grade: " + max);
System.out.println ("Lowest grade: " + min);
} }31Slide32
32
Program Development
Testing – attempt to find errors that may exist in your programmed solution
Compare your code to the design and resolve any discrepancies
Determine test cases that will stress the limits and boundaries of your solution
Carefully retest after finding and fixing an errorSlide33
33
More Drawing Techniques
Conditionals and loops can greatly enhance our ability to control graphics
See
Bullseye.java
(page 173)
See
Boxes.java
(page 175)
See BarHeights.java (page 177) Slide34
34
SummaryChapter 3 has focused on:
program development stages
the flow of control through a method
decision-making statements
expressions for making complex decisions
repetition statements
drawing with conditionals and loopsSlide35
35
Assignment 3
COMPLETE ALL ASSIGNMENTS IN THE ORDER LISTED
Lab 2 -- Grades
Lab 3 Phase 1
Counting and Looping – Love CS
Powers of 2 – Powers
A guessing Game – Guess
Chapter 3 Exercises continued
numbers 9- 13Lab 3 Phase 2Factorials – Factorial (Ex. Credit)More Guessing – GuessDoChapter 3 Exercises continuednumbers 14 - 22 Slide36
36
Assignment 4
COMPLETE ALL ASSIGNEMENTS IN THE ORDER LISTED
Lab 4 Phase 1
Counting Characters –
CharCount
Chapter 3 Programming Projects (pp. 187 – 188)
3.1, 3.4, 3.5, 3.7, 3.8, 3.12 a, b, 3.13
Lab 4 Phase 2Finding Maximum & Minimum Values – MaxMinChapter 3 Exercises Continuednumbers 23 – 27Chapter 3 Exercises from textbook pp. 1893.15 – 3.17 (Ex. Credit)Lab 5
A Rainbow Applet – Rainbow (Ex. Credit)