Chapter 5: Control Structures II

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

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
COMP 14 Introduction to Programming Mr. Joshua Stough February 16, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
COMP 14 Introduction to Programming Miguel A. Otaduy May 21, 2004.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 4: Control Structures II
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
* What kind of loop would I use to complete the following: A. Output all of the prime numbers that are less than 100,000 B. Output the Fibonacci sequence.
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.
Chapter 5 Loops.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Repetition Statements while and do while loops
Control Structures II: Repetition.  Learn about repetition (looping) control structures  Explore how to construct and use count-controlled, sentinel-controlled,
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
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 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
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.
Java Fundamentals 4.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Loop Structures.
Control Structures II (Repetition)
Repetition-Counter control Loop
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
Control Statements Loops.
Chapter 5: Control Structures II (Repetition)
Control Statements Loops.
Repetition Statements
Presentation transcript:

Chapter 5: Control Structures II Java Programming: From Problem Analysis to Program Design,

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.

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 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? Develop the Algorithm Create a variable to hold the sum. Initialise the sum to zero. Create a variable to hold a counter from 1 to 100. Initialise 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 notation to make this less vague. sum = 0 count = 1 loop while count <= 100 sum = sum + count count++ endloop print sum • THIS IS NOT JAVA! This is only pseudo-code and won’t compile.

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 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 public class FirstLoop { public static void main(String[] args) int sum = 0; int count = 1; while (count <= 100) { sum = sum + count; count++; } System.out.println("Sum = “ + sum);

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.

The while Looping (Repetition) Structure i is called LCV Example 5-1 i = 0; //Line 1 while (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 20 What 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; ?

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 Example5_3 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 Loop 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 } } Line 1: Enter data for processing 12 8 9 2 3 90 38 56 8 23 89 7 2 8 3 8 Line 9: The sum of the 12 numbers = 335 Line 11: The average = 27

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

Sentinel-Controlled while Loop Example5_4 Line 1: Enter positive integers ending with -999 34 23 9 45 78 0 77 8 3 5 -999 Line 7: The sum of 10 numbers = 282 Line 9: The average = 28 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."); } }

Flag-Controlled while Loop Boolean value used to control loop. General form: boolean found = false; //initialize LCV while (!found) // test LCV { . if (expression) found = true; //update LCV }

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.

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 }

Input - Controlled while Loop Example5_7 Enter numbers then press Ctrl key and press z: 2 4 5 <eof> Sum = 11 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); } }

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.

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.

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

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.

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(); Output 0 1 2 3 4 5 6 7 8 9

The for Looping (Repetition) Structure Example 5-9 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 * 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("*"); Hello *

The for Looping (Repetition) Structure Example 5-10 What will the following for loop execute? for ( i = 0; i < 5; ++i); System.out.println(“*”); Check examples 5-11, 5-12, 5-13 for nice ideas when using for loop.

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.

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.

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

The do…while Loop (Repetition) Structure 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

do…while Loop (Post-Test Loop) 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) Example 5-16: what does each loop produce? (a) i = 11; while(i <= 10) { System.out.print(i + " "); i = i + 5; } System.out.println(); (b) i = 11; do { System.out.print(i + " "); i = i + 5; } while(i <= 10); System.out.println(); 11

do…while Loop (Post-Test Loop) When is do…while loop useful ?? Check example 5-17 to figure out!

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)

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.

break Statements Example: Find the sum of a set of positive numbers, if the data set contains a negative number stop summing. 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;

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.

continue Statements Example: 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;

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.

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!

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!

Examples Example 5-6: Guessing the number game public class Example5_6 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { int num, guess; boolean done = false; num = (int) (Math.random() * 100); while (!done) { System.out.println("Enter an integer number between 0 and 100"); guess = console.nextInt(); if ( guess == num) { System.out.println("you guessed the correct number \n"); done = true; } else if ( guess < num ) System.out.println("your guess is lower than the number. \nGuess Again."); else System.out.println("your guess is higher than the number. \nGuess Again."); } // end while } //end main }//end class

Examples Example 5-6: Sample Run Enter an integer number between 0 and 100 2 your guess is lower than the number. Guess Again. 30 your guess is higher than the number. 10 1 3 you guessed the correct number

Math.random() syntax Math.random(); Does not take any parameters, Returns a random double between 0.0 and 1.0 but not including 1.0. So for example if you wanted a random number from 0 to 10 you would do the following: int randomNumber = ((int)Math.random()*10)

Examples What is the output of the following loops? for ( i =5 ; i >=1; i--) System.out.print( i + “ “ ); for ( i =0; i < 10 ; i+=2) System.out.print( i + “ “ ); for (i=1; ; i++) System.out.print( i + “ “ ); for (int i = 5; i <= 1; i--) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); }

Examples Trace the following segment: suppose input: 38 45 71 4 -1 sum = console.nextInt(); num = console.nextInt(); while ( num != -1 ) { sum +=num; } System.out.println(“ Sum = “ + sum);

Examples Write a while and a do…while loops that have the same output of: for ( num = 1; num < = 10 ; num ++) System.out.println(num + “ “); System.out.println();

Examples T or F: the following are equivalent increment expressions in a for statement. counter = counter + 1; counter += 1; ++counter; counter++;

Chapter Summary Looping mechanisms: Nested control structures Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop for loop do…while loop break statements continue statements Nested control structures