Repetition-Counter control Loop

Slides:



Advertisements
Similar presentations
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Advertisements

Chapter 5: Control Structures II (Repetition)
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Building Java Programs Chapter 5 Program Logic and Indefinite Loops Copyright (c) Pearson All rights reserved.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Java Programming: From the Ground Up
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 4 Objectives  Learn about repetition (looping) control structures.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Slides by Evan Gallagher
Slides by Evan Gallagher
Java Fundamentals 4.
Chapter 9 Repetition.
Lecture 4b Repeating With Loops
CSC111 Quick Revision.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
CiS 260: App Dev I Chapter 4: Control Structures II.
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Chapter 5: Control Structures II
SELECTION STATEMENTS (1)
Loops CS140: Introduction to Computing 1 Savitch Chapter 4 Flow of Control: Loops 9/18/13 9/23/13.
Chapter 5 Repetition.
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Building Java Programs
Building Java Programs
Control Statements Loops.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 5: Control Structures II (Repetition)
Building Java Programs
Control Statements Loops.
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Building Java Programs
Building Java Programs
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Building Java Programs
Presentation transcript:

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

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

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

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!

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.

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

While Loop Types Counter-Controlled Loop Sentinel-Controlled Loop Flag-Controlled Loop

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.

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

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

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

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

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

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

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

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

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

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

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 {5 2 6 1})

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

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 {5 2 6 1} 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

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

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.

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 + " ");

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:

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.

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.

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

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.

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.