Download presentation
Presentation is loading. Please wait.
1
Repetition-Counter control Loop
Chapter 4: Control Structures Repetition-Counter control Loop
2
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 …
3
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);
4
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 ?Or to ?
5
Why Is Repetition Needed?
The Algorithm Create a variable to hold the sum. Initialize the sum to zero. Create a variable to hold a counter from 1 to 100. Initialize the counter to 1. While the counter is less-than-or-equal to 100 add the counter to the sum add one to the counter Now repeat Print the sum
6
Why Is Repetition Needed?
We can use pseudo-code: sum = 0 count = 1 loop while count <= 100 sum = sum + count count++ endloop print sum
7
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!
8
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.
9
Example i = 0 loop while (i <= 20) print(i) i = i + 5 end loop
start i = 0 loop while (i <= 20) print(i) i = i + 5 end loop i = 0 i <= 20 end No i i = i + 5 Print i Yes Output 5 5 10 15 20 10 15 20 25 What will happen if you omit (i= i + 5) ?
10
While Loop Types Counter-Controlled Loop Sentinel-Controlled Loop
Flag-Controlled Loop
11
Counter-Controlled Loop
Used when exact number of data or entry pieces is known. General form: N = … counter = 0 Loop while (counter < N) . counter = counter + 1 End loop N = … counter = 0 Read N or counter < N do operation counter = counter + 1 No Yes (1) Initialization stmt. (2) Loop condition (3) Update stmt.
12
Example Write a program to allow the user to enter a set of integer numbers, then print the sum of these numbers. Start 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
13
setSize counter sum number Output 3 1 10 4 15 start Read setSize
Start 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 start Read setSize counter = 0 sum = 0 counter < setSize No end Print sum counter = counter + 1 3 setSize counter sum 1 number Yes Read number Output 1 1 10 sum = sum + number 3 1 10 4 15 2 11 4 3 15
14
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).
15
The while Looping (Repetition) Structure
Example 5-1 i = 0; while (i <= 20) { System.out.print(i + " "); i = i + 5; } System.out.println(); Output
16
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) }
17
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++; }
18
Counter-Controlled while Loop-Example 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.");
19
Counter-Controlled while Loop-Example 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 The sum of the 4 numbers = 16 The average = 4
20
Counter-Controlled Loop: Another way for expressing it
While loop N = … counter = 1 Loop while (counter<=N) . counter = counter + 1 End loop For loop N = … For(counter = 1, counter <= N, counter = counter + 1) . End For Initialization Condition Increment \ Decrement counter = 1 to N Step 1
21
Counter-Controlled Loop –For Loop
The for loop does not have a standard flowcharting method and you will find it done in different ways. N = … counter = 1 Read N or counter <= N do operation counter = counter + 1 No Yes N = … or Read N Can be simplified to: For counter = 1 to N, step 1 do operation Next counter
22
Example 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. Verify your result by tracing the developed algorithm. (Assume N to be 4 and the following set to be the numbers { })
23
Solution start Read N max = 0 (1) For counter = 1 to N, step 1 Yes
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 Yes Read number number > max No max = number Yes Next counter end
24
N max counter number start start Read N (2)
Trace the developed algorithm. Assume N to be 4 and the following set to be the numbers { } max = 0 4 N max 1 counter 5 number 5 2 2 For counter = 1 to N, step 1 Yes Read number 6 3 6 number > max 4 1 No 5 max = number Yes Print max 6 Next counter end
25
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
26
The for Looping (Repetition) Structure
Execution: Initial statement executes. Loop condition is evaluated. If loop condition evaluates to true, execute for loop statement and execute update statement. Repeat step 2 until loop condition is false.
27
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 + " ");
28
The for Looping (Repetition) Structure
Example 5-10 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:
29
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.
30
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.
31
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
32
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.
33
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.