33
Chapter 4: Control Structure REPETITION- COUNTER CONTROL LOOP

Repetition-Counter control Loop

  • Upload
    sibyl

  • View
    41

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 4: Control Structures. Repetition-Counter control Loop. Why Is Repetition Needed?. How can you solve the following problem: What is the sum of all the numbers from 1 to 100. The answer will be 1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100. Why Is Repetition Needed?. - PowerPoint PPT Presentation

Citation preview

Page 1: Repetition-Counter control Loop

Chapter 4: Control Structures

REPETITION-COUNTER CONTROL LOOP

Page 2: Repetition-Counter control Loop

Why Is Repetition Needed?How can you solve the following problem: What is the sum of all the numbers from 1

to 100. The answer will be

1 + 2 + 3 + 4 + 5 + 6 + … + 99 + 100.

Page 3: Repetition-Counter control Loop

Why Is Repetition Needed?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);

Page 4: Repetition-Counter control Loop

Why Is Repetition Needed?This solution has problems: It would take a long time to type in. There is a high risk of making an error

while typing it in. 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?

Page 5: Repetition-Counter control Loop

Why Is Repetition Needed?

The Algorithm

1. Create a variable to hold the sum.2. Initialize the sum to zero.3. Create a variable to hold a counter from 1 to 100.4. Initialize 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

Page 6: Repetition-Counter control Loop

Why Is Repetition Needed?We can use pseudo-code:sum = 0count = 1loop while count <= 100 sum = sum + count count++endloopprint sum

Page 7: Repetition-Counter control Loop

Why Is Repetition Needed?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!

Page 8: Repetition-Counter control Loop

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. 8

Page 9: Repetition-Counter control Loop

Examplei = 0loop while (i <= 20)print(i)i = i + 5

end loop

start

i = 0

i <= 20

end

No

i = i + 5

Print i

Yes0

i

Output

05101520

5

10

15

20

25 What will happen if you omit (i= i + 5) ?

Page 10: Repetition-Counter control Loop

While Loop Types

Counter-Controlled Loop Sentinel-Controlled Loop Flag-Controlled Loop

Page 11: Repetition-Counter control Loop

Counter-Controlled Loop Used when exact number of data or entry pieces is

known. General form:

N = …counter = 0Loop while (counter < N) . . . counter = counter + 1 . . .End loop

N = …

counter = 0

Read Nor

counter < N

do operation

counter = counter + 1

No

Yes

(1) Initialization

stmt.

(3) Update stmt.

(2) Loop condition

Page 12: Repetition-Counter control Loop

Example Write a program to allow the user to enter a

set of integer numbers, then print the sum of these numbers.

Start ProgramRead setSizecounter = 0sum = 0Loop while (counter < setSize)

Read numbersum = sum + numbercounter = counter + 1

End loopPrint sum

End Program

Page 13: Repetition-Counter control Loop

startStart Program

Read setSize

counter = 0

sum = 0

Loop while (counter < setSize)

Read number

sum = sum + number

counter = counter + 1

End loop

Print Sum

End Program

counter = counter + 1

Read setSize

counter = 0

sum = 0

counter < setSize

YesRead number

sum = sum + number

Output

3110415

1

2

3

0counter

3setSize

0sum

No

end

Print sum

1

11

15

1number

10

4

Page 14: Repetition-Counter control Loop

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).

14

Page 15: Repetition-Counter control Loop

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

15

Page 16: Repetition-Counter control Loop

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)

.

.

}

16

Page 17: Repetition-Counter control Loop

Counter-Controlled while Loop17

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 18: Repetition-Counter control Loop

Counter-Controlled while Loop-Example 5-3

18//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.");

Page 19: Repetition-Counter control Loop

Counter-Controlled while Loop-Example 5-3 (continued)

19

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 Integers2 1 5 8The sum of the 4 numbers = 16

The average = 4

Page 20: Repetition-Counter control Loop

Counter-Controlled Loop: Another way for expressing it

N = …counter = 1Loop while (counter<=N) .

.

counter = counter + 1End loop

N = …For(counter = 1, counter <= N, counter = counter + 1) .

.

End For

While loop

For loop

Initialization Condition Increment \ Decrement

Step 1counter = 1 to N

Page 21: Repetition-Counter control Loop

Counter-Controlled Loop –For Loop

N = …

counter = 1

Read Nor

counter <= N

do operation

counter = counter + 1

No

Yes

N = …Read

Nor

do operation

Next counter

Can be simplifie

d to:For counter = 1

to N, step 1

The for loop does not have a standard flowcharting method and you will find it done in different ways.

Page 22: Repetition-Counter control Loop

Example

1. Write down an algorithm and draw a flowchart to find and print the largest of N (N can be any number) positive numbers. Read numbers one by one.

2. Verify your result by tracing the developed algorithm. (Assume N to be 4 and the following set to be the numbers {5 2 6 1})

Page 23: Repetition-Counter control Loop

start

Solution

Start Program

Read N

max = 0

For(counter = 1 to N, step 1)

Read number

if (number > max)

max = number

End For

Print max

End Program

max = 0

Read N

YesRead number

number > max

end

No

max = number

Yes

(1) For counter = 1 to N,

step 1

Next counter

Page 24: Repetition-Counter control Loop

(2) • Trace the developed algorithm. • Assume N to be 4 and the following

set to be the numbers {5 2 6 1}

4N

0max 1

counter 5

number

5 2 2

3 66

4 1

5

Print max 6

startstart

max = 0

Read N

YesRead number

number > max

end

No

max = number

Yes

For counter = 1 to N,

step 1

Next counter

Page 25: Repetition-Counter control Loop

The for Looping (Repetition) Structure

25

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

Page 26: Repetition-Counter control Loop

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.

26

Page 27: Repetition-Counter control Loop

The for Looping (Repetition) StructureExample 5-9

The following for loop prints the first 10 nonnegative integers:

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

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

27

Page 28: Repetition-Counter control Loop

The for Looping (Repetition) StructureExample 5-10

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

}

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

28

Page 29: Repetition-Counter control Loop

The for Looping (Repetition) Structure29

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.

Page 30: Repetition-Counter control Loop

For Loop Programming Example: Classify Numbers

30

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 31: Repetition-Counter control Loop

For Loop Programming Example: Classify Numbers (solution)

31

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 32: Repetition-Counter control Loop

While Loop Programming Example: Fibonacci Number

32

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 33: Repetition-Counter control Loop

While Loop Programming Example: Fibonacci Number

33 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.