Top Banner
Chapter 5: Control Chapter 5: Control Structures II Structures II J J ava ava P P rogramming: rogramming: From Problem Analysis to From Problem Analysis to Program Design, Program Design,
46

Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

Jan 04, 2016

Download

Documents

Adam Thornton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

Chapter 5: Control Chapter 5: Control Structures IIStructures II

JJavaava PProgramming:rogramming:

From Problem Analysis to Program From Problem Analysis to Program

Design,Design,

Page 2: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

2

Chapter Objectives

Learn about repetition (looping) control structures.

Explore how to construct and use count-controlled, sentinel-controlled and flag-controlled repetition structures.

Examine break and continue statements. Discover how to form and use nested control

structures.

Page 3: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

3

How can you solve the following problem: What is the sum of all the numbers from 1 to

100.

Why Is Repetition Needed?

The answer will be 1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.

Page 4: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

4

Here’s some sample Java code:int sum=0;

sum = sum+1;

sum = sum +2;

sum = sum +3;

sum = sum +4;

sum = sum +99;

sum = sum +100;

System.out.println(“The sum from 1 to 100 = “ +sum);

Why Is Repetition Needed?

Page 5: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

5

This solution has two major problems. Firstly, it’s tedious and it would take a long time to

type in. There is also a high risk of making an error while typing it in.

Secondly, it doesn’t easily scale. This may work for 100 numbers but how would you handle having to add from 1 to a 1000? Or to 1000000?Or to 1000000000?

Why Is Repetition Needed?

Page 6: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

6

Develop the Algorithm

1. Create a variable to hold the sum.2. Initialise the sum to zero.3. Create a variable to hold a counter from 1 to 100.4. Initialise the counter to 1.5. While the counter is less-than-or-equal to 1006. add the counter to the sum7. add one to the counter8. Now repeat9. Print the sum

Why Is Repetition Needed?

Page 7: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

7

We can use pseudo-code notation to make this less vague.sum = 0count = 1loop while count <= 100 sum = sum + count count++endloopprint sum

• THIS IS NOT JAVA! This is only pseudo-code and won’t compile.

Why Is Repetition Needed?

Page 8: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

8

loop while condition <body>endloop

This pseudo-code means: before executing the statements in the body, evaluate the condition. If the condition is true then execute the body once.

Once you have executed the body statements once, go back to the loop condition and re-evaluate it. If it is true, execute the body code again. If the condition is not true then the body will not be executed!

Why Is Repetition Needed?

Page 9: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

9

Now we need to turn our pseudo-code into Java. Java has 3 repetition structures: while, for and do … while. One way Java supports repetition is using While statements. Syntax:

while (expression) {// body statements}

The expression MUST be placed inside parentheses. As with an if statement, the expression part is evaluated to determine whether or not the statements should be executed.

The body of the loop is enclosed in { and }.

The while Looping (Repetition) Structure

Page 10: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

10

1. public class FirstLoop2. {3. public static void main(String[] args)4. {5. int sum = 0;6. int count = 1;7. while (count <= 100) {8. sum = sum + count;9. count++;10. }11. System.out.println("Sum = “ + sum);12. }13.}

The while Looping (Repetition) Structure

Page 11: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

11

The while Looping (Repetition) Structure

Infinite loop: is a loop that continues to execute endlessly.

So, expression is always true in an infinite loop. Statements must change value of expression to false.

Page 12: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

12

The while Looping (Repetition) Structure

Example 5-1

i = 0; //Line 1while (i <= 20) //Line 2{

System.out.print(i + " "); //Line 3 i = i + 5; //Line 4

}System.out.println(); //Line 5

Output

0 5 10 15 20What is the value of i at the end?What will happen if you omit i= i + 5; ?What will happen if you omit i =0; ?

i is called LCV

Page 13: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

13

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)

.

.

.

}

Page 14: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

14

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 programint counter = 0;while (counter < N){ . . . counter++; . . .}

Page 15: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

15

import java.util.*;

public class Example5_3{ 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.println("Line 1: Enter data for " + "processing"); //Line 1

limit =console.nextInt(); //Line 2 sum = 0; //Line 3 counter = 0; //Line 4

Counter-Controlled while LoopExample5_3

Page 16: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

16

Example5_3

while(counter < limit) //Line 5 { number = console.nextInt(); //Line 6 sum = sum + number; //Line 7 counter++; //Line 8 }

System.out.printf("Line 9: The sum of the %d " + " numbers = %d%n",limit, sum); //Line 9 if(counter != 0) //Line 10 System.out.printf("Line 11: The average = %d%n", (sum / counter)); //Line 11 else //Line 12 System.out.println("Line 13: No input."); //Line 13 }}

Counter-Controlled while Loop

Line 1: Enter data for processing12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8Line 9: The sum of the 12 numbers = 335Line 11: The average = 2

Page 17: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

17

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; . . .}

Page 18: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

18

import java.util.*;

public class Example5_4{ static Scanner console = new Scanner(System.in);

static final int SENTINEL = -999;

public static void main (String[] args) { int number; int sum = 0; int count = 0; System.out.println("Line 1: Enter positive integers " + "ending with "+ SENTINEL);

number = console.nextInt(); while(number != SENTINEL) { sum = sum + number; count++; number = console.nextInt(); }

System.out.println("Line 7: The sum of " + count + " numbers = " + sum);

if(count != 0) System.out.println("Line 9: The average = " + (sum / count)); else System.out.println("Line 11: No input."); }}

Sentinel-Controlled while LoopExample5_4

Line 1: Enter positive integers ending with -999

Line 9: The average = 28Line 7: The sum of 10 numbers = 28234 23 9 45 78 0 77 8 3 5 -999

Page 19: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

19

Flag-Controlled while Loop

Boolean value used to control loop. General form:

boolean found = false; //initialize LCVwhile (!found) // test LCV{ .

. . if (expression) found = true; //update LCV . . .}

Page 20: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

20

Input - Controlled while Loop

Sentinel value is not always appropriate, programmer sometimes does not know what sentinel is.

In this situation, we can use the input- controlled while loop structure.

console acts as LCV. The method hasNext, of the class Scanner,

returns true if there is an input in the input stream; otherwise, it returns false.

The expression console.hasNext() acts as the loop condition.

Expressions such as console.nextInt() update the value of the loop condition.

Page 21: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

21

Input - Controlled while Loop

A general form of the input - controlled while loop that uses the Scanner object console to input data is:

while (console.hasNext()){ //Get the next input and store it in an //appropriate variable //Process data}

Page 22: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

22

import java.util.*;

public class Example5_7{

static Scanner console = new Scanner(System.in); public static void main (String[] args) {

int num; int sum = 0; System.out.println("Enter numbers then press Ctrl key and press z: ");

while(console.hasNext()) { num = console.nextInt(); sum = sum + num; }

System.out.printf("Sum = %d%n", sum); }}

Input - Controlled while LoopExample5_7

Enter numbers then press Ctrl key and press z:

Sum = 112 4 5 <eof>

Page 23: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

23

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.

Page 24: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

24

Programming Example: Fibonacci Number (Solution)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.

Page 25: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

25

The for Looping (Repetition) Structure

Specialized form of while loop. Simplifies the writing of count-controlled loops. Syntax:

for (initial statement; loop condition;

update statement)

statement

Page 26: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

26

The for Looping (Repetition) Structure Execution:

Initial statement executes. // only executes once Loop condition is evaluated. If loop condition evaluates to true, execute for

loop statement and execute update statement. Repeat until loop condition is false.

Page 27: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

27

The for Looping (Repetition) Structure

Example 5-8

The following for loop prints the first 10 positive integers:

for (i = 0; i < 10; i++)

System.out.print(i + " ");

System.out.println();

Output0 1 2 3 4 5 6 7 8 9

Page 28: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

28

The for Looping (Repetition) StructureExample 5-91. The following for loop outputs the word Hello and a star (on separate lines) five times:

for (i = 1; i <= 5; i++){

System.out.println("Hello"); System.out.println("*");

}

Hello

Hello

Hello

Hello

Hello

*****

HelloHelloHelloHelloHello*

2. 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("*");

Page 29: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

29

Example 5-10

What will the following for loop execute?

for ( i = 0; i < 5; ++i);

System.out.println(“*”);

The for Looping (Repetition) Structure

Check examples 5-11, 5-12, 5-13 for nice ideas when using for loop.

Page 30: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

30

The for Looping (Repetition) Structure Does not execute if initial condition is 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: for (;;) System.out.println(“Hello”); //infinite loop printing Hello

If loop condition is omitted, it is assumed to be true.

for statement ending in semicolon is empty.

Page 31: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

31

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.

Page 32: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

32

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

Page 33: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

33

The do…while Loop (Repetition) Structure

Syntax:

do

statementwhile (expression);

Statements are executed first and then expression is evaluated.

Statements are executed at least once and then continued if expression is true.

Page 34: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

34

do…while Loop

Page 35: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

35

In a while or for loop:

condition is evaluated before executing the body of the loop pre-test loops.

In a do … while loop:

condition is evaluated after executing the body of the loop post-test loop.

do…while Loop (Post-Test Loop)

Page 36: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

36

(a) i = 11; while(i <= 10) { System.out.print(i + " "); i = i + 5; } System.out.println();

do…while Loop (Post-Test Loop)Example 5-16: what does each loop produce?

(b) i = 11; do { System.out.print(i + " "); i = i + 5; } while(i <= 10); System.out.println();

11

Page 37: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

37

When is do…while loop useful ??

Check example 5-17 to figure out!

do…while Loop (Post-Test Loop)

Page 38: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

38

Note… All three loops: while, for and do…while have

their place in Java. One loop can often replace another.

For example do..while loop can replace while loop as follow:

if (expression) do action while(expression); Replaces: while (expression) action

Page 39: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

39

break Statements

Used to exit early from a loop. Used to skip remainder of switch structure. Can be placed within if statement of a loop.

If condition is met, loop is exited immediately.

Page 40: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

40

sum = 0; while(console.hasNext()){ num = console.nextInt(); if(num < 0) //if number is negative, terminate the loop

{ System.out.println("Negative number found in data"); break; } sum= sum + num; }

break StatementsExample:

Find the sum of a set of positive numbers, if the data set contains

a negative number stop summing.

Page 41: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

41

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.

Page 42: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

42

continue StatementsExample:

Find the sum of a set of positive numbers, if a negative number

appears in the data set skip it and read the following number.

sum = 0; while(console.hasNext()){ num = console.nextInt(); if(num < 0) //if number is negative, read next number { System.out.println("Negative number found in data"); continue; } sum= sum + num; }

Page 43: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

43

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.

Page 44: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

44

Nested Control Structures (Example)

for (int i = 1; i <= 5; i++){ for (int j = 1; j <= i; j++)

System.out.print(" *"); System.out.println();}Output:

***************

Check the rest of the text book examples!

Page 45: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

45

Overall guidelines for loops If you know in advance how many times the loop has to iterate

- use a for loop.

Never change the counter variable of a for loop in the loop body - you can get some strange results.

For while and do…while loops, make sure that the variable you are checking in the condition is the same variable that you are changing in the loop body.

Finally, be aware of infinite loops!

Page 46: Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,

46

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