Chapter 5: Control Structures II

Download Report

Transcript Chapter 5: Control Structures II

Chapter 4: Control Structures II
Java Programming: From Problem Analysis to Program Design, D.S. Malik
Chapter Objectives
• Learn about repetition (looping) control
structures.
• Explore how to construct and use countercontrolled, sentinel-controlled, and flagcontrolled structures.
• Examine break and continue statements.
• Discover how to form and use nested control
structures.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
2
Why is Repetition Needed?
• There are many situations in which the
same statements need to be executed
several times.
• Example:
– Formulas used to find average grades for
students in a class.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
3
Repetition
• Java has three repetition, or looping,
structures that let you repeat statements
over and over again until certain
conditions are met:
 while
 for
 do…while
Java Programming: From Problem Analysis to Program Design, D.S. Malik
4
The while Looping (Repetition) Structure
• Syntax:
while (expression)
statement
• Statements must change value of expression to false.
• A loop that continues to execute endlessly is called an
infinite loop (expression is always true).
Java Programming: From Problem Analysis to Program Design, D.S. Malik
5
The while Looping (Repetition) Structure
Example 5-1
i = 0;
while (i <= 20)
{
System.out.print(i + " ");
i = i + 5;
}
System.out.println();
Output
0 5 10 15 20
Java Programming: From Problem Analysis to Program Design, D.S. Malik
6
The while Looping (Repetition) Structure
Typically, while loops are written in the following form:
//initialize the loop control variable(s)
while (expression)
//expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
7
Counter-Controlled while Loop
• Used when exact number of data or entry pieces is
known.
• General form:
int N = //value input by user or specified
//in program
int counter = 0;
while (counter < N)
{
.
.
.
counter++;
.
.
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
8
Counter-Controlled while LoopExample 5-3
//Counter-controlled while loop
import java.util.*;
public class CounterControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int limit;
//store the number of items
//in the list
int number;
//variable to store the number
int sum;
//variable to store the sum
int counter;
//loop control variable
System.out.print("Enter the number of "
+ "integers in the list: ");
limit = console.nextInt();
System.out.println();
sum = 0;
counter = 0;
System.out.println("Enter " + limit+ " integers.");
Java Programming: From Problem Analysis to Program Design, D.S. Malik
9
Counter-Controlled while LoopExample 5-3 (continued)
while (counter < limit)
{
number = console.nextInt();
sum = sum + number;
counter++;
}
System.out.printf("The sum of the %d " +"numbers = %d%n", limit, sum);
if (counter != 0)
System.out.printf("The average = %d%n",(sum / counter));
else
System.out.println("No input.");
}
}
Sample Run:
Enter the number of integers I the list: 4
Enter 4 Integers
2158
The sum of the 4 numbers = 16
The average = 4
Java Programming: From Problem Analysis to Program Design, D.S. Malik
10
Sentinel-Controlled while Loop
• Used when exact number of entry pieces is
unknown, but last entry (special/sentinel value) is
known.
• General form:
Input the first data item into variable;
while (variable != sentinel)
{
.
.
.
input a data item into variable;
.
.
.
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
11
Sentinel-Controlled while Loop
Example 5-4
//Sentinel-controlled while loop
import java.util.*;
public class SentinelControlledWhileLoop
{
static Scanner console = new Scanner(System.in);
static final int SENTINEL = -999;
public static void main (String[] args)
{
int number;
//variable to store the number
int sum = 0;
//variable to store the sum
int count = 0;
//variable to store the total
//numbers read
System.out.println("Enter positive integers "
+ "ending with " + SENTINEL);
Java Programming: From Problem Analysis to Program Design, D.S. Malik
12
Sentinel-Controlled while Loop
Example 5-4 (continued)
number = console.nextInt();
while (number != SENTINEL)
{
sum = sum + number;
count++;
number = console.nextInt();
}
System.out.printf("The sum of the %d " +
"numbers = %d%n", count, sum);
if (count != 0)
System.out.printf("The average = %d%n",(sum / count));
else
System.out.println("No input");
}
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
13
Sentinel-Controlled while Loop
Example 5-5
//This program converts uppercase letters to their
// corresponding telephone digits.
//********************************************************
import java.util.*;
public class TelephoneDigit
{
static Scanner input = new Scanner (System.in);
public static void main (String[] args)
{
char letter;
String inputMessage;
String inputString;
String outputMessage;
inputMessage =
+
+
+
+
"Program to convert uppercase "
"letters to their corresponding "
"telephone digits.\n"
"To stop the program enter #.\n"
"Enter a letter:";
System.out.println(inputMessage);
Java Programming: From Problem Analysis to Program Design, D.S. Malik
14
Sentinel-Controlled while Loop
Example 5-5 (continued)
letter = input.next().charAt(0);
while (letter != '#' )
{
outputMessage = "The letter you entered is: "
+ letter + "\n"
+ "The corresponding telephone "
+ "digit is: ";
if (letter >= 'A' && letter <= 'Z')
{
switch (letter)
{
case 'A':
case 'B':
case 'C':
outputMessage = outputMessage+ "2";
break;
case 'D':
case 'E':
case 'F':
outputMessage = outputMessage+ "3";
break;
Java Programming: From Problem Analysis to Program Design, D.S. Malik
15
Sentinel-Controlled while Loop
Example 5-5 (continued)
case 'G':
case 'H':
case 'I':
outputMessage = outputMessage+ "4";
break;
case 'J':
case 'K':
case 'L':
outputMessage = outputMessage+ "5";
break;
case 'M':
case 'N':
case 'O':
outputMessage = outputMessage+ "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputMessage = outputMessage + "7";
break;
Java Programming: From Problem Analysis to Program Design, D.S. Malik
16
Sentinel-Controlled while Loop
Example 5-5 (continued)
case 'T':
case 'U':
case 'V':
outputMessage = outputMessage+ "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputMessage = outputMessage+ "9";
}
}
else
outputMessage = outputMessage + "Invalid input";
System.out.println(outputMessage);
inputMessage = "Enter another uppercase letter "
+ "to find its corresponding "
+ "telephone digit.\n"
+ "To stop the program enter #.\n"
+ "Enter a letter:";
System.out.println (inputMessage);
letter = input.next().charAt(0);
}//end while
}
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
17
Flag-Controlled while Loop
• Boolean value used to control loop.
• General form:
boolean found = false;
while (!found)
{
.
.
.
if (expression)
found = true;
.
.
.
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
18
Flag-Controlled while LoopExample 5-6
/Flag-controlled while loop.
//Guessing the number game.
import java.util.*;
public class FlagControlledLoop
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
//declare the variables
int num;
//variable to store the random number
int guess;
//variable to store the number
//guessed by the user
boolean done;
//boolean variable to control the loop
num = (int) (Math.random() * 100);
done = false;
Java Programming: From Problem Analysis to Program Design, D.S. Malik
19
Flag-Controlled while LoopExample 5-6 (continued)
while (!done)
{
System.out.print ("Enter an integer greater"
+ " than or equal to 0 and "
+ "less than 100: ");
guess = console.nextInt();
System.out.println();
if (guess == num)
{
System.out.println("You guessed the "
+ "correct number.");
done = true;
}
else if (guess < num)
System.out.println("Your guess is "
+ "lower than "
+ "the number.\n"
+ "Guess again!");
else
System.out.println("Your guess is “
+ "higher than "
+ "the number.\n"
+ "Guess again!");
} //end while
}
}
Java Programming: From Problem Analysis to Program Design, D.S. Malik
20
While Loop Programming
Example: Fibonacci Number
•
•
Fibonacci formula for any Fibonacci sequence:
an = an-1 + an-2
Input: First two Fibonacci numbers in sequence,
position in sequence of desired Fibonacci
number (n).
–
–
–
•
int previous1 = Fibonacci number 1
int previous2 = Fibonacci number 2
int nthFibonacci = Position of nth Fibonacci
number
Output: nth Fibonacci number.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
21
While Loop Programming Example: Fibonacci
Number
if (nthFibonacci == 1)
current = previous1;
else if (nthFibonacci == 2)
current = previous2;
else
{
counter = 3;
while (counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
}
•
Final result found in last value of current.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
22
The for Looping (Repetition)
Structure
• Specialized form of while loop.
• Its primary purpose is to simplify the writing of counter-controlled
loops. For this reason, the for loop is typically called a counted or
indexed for loop. .
• Syntax:
for (initial statement; loop condition; update statement)
statement
Java Programming: From Problem Analysis to Program Design, D.S. Malik
23
The for Looping (Repetition)
Structure
•
Execution:
1. Initial statement executes.
2. Loop condition is evaluated.
3. If loop condition evaluates to true,
1. execute for loop statement and
2. execute update statement.
4. Repeat step 2 until loop condition is false.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
24
The for Looping (Repetition)
Structure
Example 5-9
The following for loop prints the first 10
nonnegative integers:
for (i = 0; i < 10; i++)
System.out.print(i + " ");
Java Programming: From Problem Analysis to Program Design, D.S. Malik
25
The for Looping (Repetition)
Structure
Example 5-10
1. The following for loop outputs the word Hello and a star (on
separate lines) five times:
2.
for (i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
The following for loop outputs the word Hello five times and
the star only once:
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
Java Programming: From Problem Analysis to Program Design, D.S. Malik
26
The for Looping (Repetition)
Structure
• Does not execute if loop condition is initially false.
• Update expression changes value of loop control
variable, eventually making it false.
• If loop condition is always true, result is an infinite
loop.
• Infinite loop can be specified by omitting all three
control statements.
• If loop condition is omitted, it is assumed to be
true.
• Action of for loop ending in semicolon is empty.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
27
For Loop Programming Example:
Classify Numbers
• Input: N integers (positive, negative, and zeros).
int N = 20;
//N easily modified
• Output: Number of 0s, number of even integers,
number of odd integers.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
28
For Loop Programming Example: Classify
Numbers (solution)
for (counter = 1; counter <= N; counter++)
{
number = console.nextInt();
System.out.print(number + " ");
switch (number % 2)
{
case 0: evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1: odds++;
} //end switch
} //end for loop
Java Programming: From Problem Analysis to Program Design, D.S. Malik
29
The do…while Loop (Repetition)
Structure
• Syntax:
do
statement
while (expression);
• Statements are executed first and then
expression is evaluated.
• Statements are executed at least once and
then continued if expression is true.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
30
do…while Loop (Post-Test
Loop)
Java Programming: From Problem Analysis to Program Design, D.S. Malik
31
do…while Loop (Post-Test Loop)
Example :
i=0;
do {
System.out.print(i + “ “ ) ;
i=i+5;
} while ( i <= 30 ) ;
output : 0 5 10 15 20 25 30
Java Programming: From Problem Analysis to Program Design, D.S. Malik
32
break Statements
• Used to
– exit early from a loop. (while, for, and do...while)
– skip remainder of switch structure.
• Can be placed within if statement of a loop.
– If condition is met, loop is exited immediately.
• After the break statement executes, the program
continues to execute with the first statement
after the structure
Java Programming: From Problem Analysis to Program Design, D.S. Malik
33
break Statements
Example :
int count ;
for ( count = 1 ; count <= 10 ; count ++ )
{
if ( count == 5)
break ;
System.out.print(count + “ ” );
}
Output
1234
Java Programming: From Problem Analysis to Program Design, D.S. Malik
34
continue Statements
• Used in while, for, and do...while structures.
• When executed in a loop, the remaining
statements in the loop are skipped; proceeds with
the next iteration of the loop.
• When executed in a while/do…while structure,
expression is evaluated immediately after
continue statement.
• In a for structure, the update statement is
executed after the continue statement; the loop
condition then executes.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
35
continue Statements
Example :
int count ;
for ( count = 1; count <= 10 ; count ++ )
{
if ( count == 5)
continue;
System.out.print(count + “ ” );
}
Output
1 2 3 4 6 7 8 9 10
Java Programming: From Problem Analysis to Program Design, D.S. Malik
36
Nested Control Structures
• Provides new power, subtlety, and complexity.
• if, if…else, and switch structures can be
placed within while loops.
• for loops can be found within other for loops.
Java Programming: From Problem Analysis to Program Design, D.S. Malik
37
Nested Control Structures
(Example 5-18)
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
Output:
*
**
***
****
*****
Java Programming: From Problem Analysis to Program Design, D.S. Malik
38
Nested Control Structures
(Example 5-19)
//printing a multiplication table
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= 10; j++)
System.out.printf("%3d", i*j);
System.out.println();
}
Output
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
5
10
15
20
25
6
12
18
24
30
7
14
21
28
35
8
16
24
32
40
9
18
27
36
45
10
20
30
40
50
Java Programming: From Problem Analysis to Program Design, D.S. Malik
Chapter Summary
• Looping mechanisms:
–
–
–
–
–
Counter-controlled while loop
Sentinel-controlled while loop
Flag-controlled while loop
for loop
do…while loop
• break statements
• continue statements
• Nested control structures
Java Programming: From Problem Analysis to Program Design, D.S. Malik
40