Download week-9-lec-1_2-ch04_control-structure-loops

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 4: Control Structures
REPETITION-SENTINEL,FLAG
LOOP/DO_WHILE
Sentinel-Controlled Loop



Used when exact number of entry pieces is unknown, but last entry
(special/sentinel value) is known.
The idea of a sentinel controlled loop is that there is a special value (the
"sentinel") that is used to say when the loop is done.
General form:
Input the first data item into variable
Loop while (variable != sentinel)
.
.
.
input a data item into variable;
.
.
.
End loop
Example

Write a program that adds up a list of positive
numbers entered by the user from the keyboard,
then prints the result.

What is the number of iterations ??

Unknown

Since the input are positive integers, we can use
(-1) as the sentinel.

Example of user input: 1 3 6 4 9 12 3 5 -1
Solution
Start Program
sum = 0
Read number
loop while (number != -1)
sum = sum + number
Read number
End loop
Print sum
End Program
sum
number
0
5
5
2
7
3
10
-1
Input
5
2
3
-1
start
sum = 0
Read number
number
!= -1
Yes
sum= sum+ number
Read number
Print sum
Print sum  10
end
No
Sentinel-Controlled while Loop
Example 5-4
5
//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);
Sentinel-Controlled while Loop
Example 5-4 (continued)
6
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");
}
}
Sentinel-Controlled while Loop
Example 5-5
7
//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);
Sentinel-Controlled while Loop
Example 5-5 (continued)
8
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;
Sentinel-Controlled while Loop
Example 5-5 (continued)
9
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;
Sentinel-Controlled while Loop
Example 5-5 (continued)
10
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
}
}
Flag-Controlled Loop

A flag is a boolean variable, used to indicate whether or
not a desired situation has occurred



A value of FALSE indicates that the desired event has not
yet occurred
TRUE indicates that it has occurred
General form:
boolean found = false
Loop while (!found)
.
.
if (expression)
found = true
.
.
End loop
Initialization
Testing
Updating
Example: Number Guessing Game





Write a program that generates a random number in the
range 0..100.
Then the user tries to guess the number.
If the user guessed the number correctly, then print the
message “You guessed the number correctly !”.
Otherwise:
 If the guessed number is less than the random
number, print message “Your guess is lower than the
number”.
 Otherwise: print message “Your guess is higher than
the number”.
 The user enters another number.
The user guesses until he\she enters the correct number.
Solution
Start Program
randomNumber = …  will be discussed later
guessedRight = false
loop while (not guessedRight)
Read guess
if (guess = randomNumber)
guessedRight = true
Print “You guessed the number correctly !”
else
if (guess < randomNumber)
Print “Your guess is lower than the number”
else
Print “Your guess is higher than the number”
End loop
End Program
start
randomNumber =
…
Solution
guessedRight =
false
Yes
Read guess
Yes
guess =
randomNumber
No
Not
guessedRight
N
o
guessedRight = true
Print
“Correct Guess”
guess <
randomNumber
N
Print
Printo
“Guess is
“Guess is
Lower”
Higher”
Yes
end
Flag-Controlled while Loop
15


Boolean value used to control loop.
General form:
boolean found = false;
while (!found)
{
.
.
.
if (expression)
found = true;
.
.
.
}
Flag-Controlled while LoopExample 5-6
16
/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;
while (!done)
{
System.out.print ("Enter an integer greater"
+ " than or equal to 0 and "
+ "less than 100: ");
17
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
}
The do…while Loop

Form:
do
statement(s)
while (expression)
Statements are executed first and then
expression is evaluated.
 Statements are executed at least once
and then continued if expression is true.

Difference
while Loop
do…while
Loop
for Loop
Example
SECRET_CODE = 1234
do
Print "Type the secret code number to enter."
Read code
while (code!=SECRET_CODE)
Print "Well done,
you can now enter"
SECRET_CODE = 1234
Print input msg
Read code
code !=
SECRET_CODE
No
Print msg
Yes
The do…while Loop (Repetition) Structure
21

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.
do…while Loop (Post-Test Loop)
22
do…while Loop (Post-Test Loop)
23
Example :
i=0;
do {
System.out.print(i + “ “ ) ;
i=i+5;
} while ( i <= 30 ) ;
output : 0 5 10 15 20 25 30
break Statements
24

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
break Statements
25
Example :
int count ;
for ( count = 1 ; count <= 10 ; count ++ )
{
if ( count == 5)
break ;
System.out.print(count + “ ” );
}
Output
1234
continue Statements
26




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.
continue Statements
27
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
break and continue example
(for loop)
System.out.println ("starting loop:");
for (int x=0 ; x < 7; x++) {
System.out.println ("in loop " + x);
if (x == 2)
continue;
System.out.println (" survived continue");
if (x == 4)
break;
System.out.println (" survived break");
} // end of for
// break out of loop
System.out.println ("end of loop or exit using break");
break and continue example

Output:
starting loop:
in loop 0
survived continue
survived break
in loop 1
survived continue
survived break
in loop 2
in loop 3
survived continue
survived break
in loop 4
survived continue
end of loop or exit using break
break and continue example
int i = 0;
while(true) {
i++;
if(i == 100) break; // Out of loop
if(i % 10 != 0) continue;// Top of loop
System.out.println(i);
}

(condition)
This is an infinite loop that keeps printing the
value of i if it is divisible by 10. We will exit
the loop only when ( i==100)
Nested loop: loop in loop
Example:
Print the following using loops.
5 rows :
*
**
***
****
*****
Row 1  1 star
Row 2  2 stars
…
Row 5  5 stars
We need a loop for the rows
We need loops for columns
The number of stars in a row is equal to the
row#
Need nested loop
Nested loop: loop in loop
Solution:
For (i = 1 to 5, step 1)
For (j = 1 to i, step 1)
print(" *")
End For
move cursor to next line
End Forutput:
*
**
***
****
*****
Nested Control Structures
33

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.

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:
*
**
***
****
*****
34
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
Chapter Summary
36

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