Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS0004: Introduction to Programming Repetition – Do Loops.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
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.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Chapter 4 Loops Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
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
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Java Programming: From the Ground Up
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.1 Chapter 5 Loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Loops 1. Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved while Loop Flow.
Chapter 5 Loops.
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.
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
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
1 Fall 2009ACS-1903 Ch 4 Loops and Files while loop do-while loop for loop Other topics later on …
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 06 Title: Iterative/Repetitive Control Structures Reference: MalikFarrell, chap 1, Liang Ch 4.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
The switch Statement, and Introduction to Looping
Chapter 5: Control Structures II
Loop Structures.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Repetition Structures
Repetition-Counter control Loop
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 4 Control structures and Loops
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Looping and Repetition
Outline Altering flow of control Boolean expressions
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 6: Repetition Statements
Loop Strategies Repetition Playbook.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Looping and Repetition
Chapter 4: Loops and Iteration
Presentation transcript:

Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles

What we will cover… Intro to loops While loops Loop design Sentinels Input / Output Redirections The do-while Loop The for Loop Which Loop to use? Nested Loops break and continue

Introduction to Loops! Suppose you want to do something many different times ▫5 times – 5 lines of code ▫10 times – maybe 10 separate lines of code ▫100, 1000 times?  You can’t write the same lines of code so many times.  Instead, we use loops! Loops can be used to control how many times an operation (or sequence) is performed

Introduction to Loops (2) Ex: You want to print something out 100 times ▫Instead of copy/pasting the same line of code:  System.out.println(“Welcome to Java!”); ▫We say: int count=0; while (count < 100) { System.out.println(“Welcome to Java!”); count++; } ▫We are using what’s called a while loop

The while Loop while(loop_condition) { //Loop Body Statements; } The while loop continually executes the statements within the block so long as the loop condition is true ▫As soon as the condition turns false, the loop is stopped and the program continues

The while Loop (2) Terminology ▫Loop continuation condition  A condition that must be true in order for the loop to repeat  Boolean ▫Loop body  Part that contains statements to be repeated ▫Iteration  A Single execution of the loop  Also called a repetition while(loop_condition) { //Loop Body Statements; }

The while Loop (3) If the loop condition in the while loop is true, the loop will continue to iterate while(loop_condition) Loop Body Statements

The while Loop (4) Ex: Print out 100 numbers starting with zero. ▫How to code? ▫Write out all numbers ▫Use a loop! We are doing something 100 times, so let’s start with a counter ▫Call it count We will make the counter keep track of how many times the loop is running ▫Increment the counter during the loop We will stop after 100 times ▫Make the loop condition false after counter runs 100 times Start with zero ▫Make counter start with 0.

The while Loop (5) We have used count as output, but also to keep track of the loop ▫This is called a counter-controlled loop int count = 0; while(count < 100) { System.out.println(count); count++; }

The while Loop (6) What about these examples? int sum =0, i=1; while(i<10) { sum = sum + i; i++; } System.out.println(“Sum is “+sum); int sum =0, i=1; while(i<10) { sum = sum + i; } System.out.println(“Sum is “+sum);

The while Loop (7) The first example works how we want, but the second results in an infinite loop! ▫A loop that doesn’t stop ▫Your program runs forever! ▫Avoid! What happens here? ▫while(true);

Off by One Errors Any time you add/sum/multiply/account for a long interval of numbers, you run the risk of an “Off by one error” ▫You have run your loop one more or less time than expected Ex:Display “Welcome to Java” 100 times ▫(Incorrect) Answer:  Why? int count=0; while(count <= 100) { System.out.println(“Welcome to Java!”); count++; }

Off by One Errors Let’s look at this again: ▫Count starts with 0 ▫Loop ends with count less than or equal to 100  This includes 100 ▫Therefore the while loop executes from 0 to 100 times, including both 0 and 100  Loop actually executes 101 times int count=0; while(count <= 100) { System.out.println(“Welcome to Java!”); count++; }

Loop Design Strategies Loops can be hard if you don’t plan for them Strategies: ▫Identify the statements that need to be repeated ▫Wrap those statements in a loop block ▫Code the loop condition and add statements for controlling the loop  1  2  3 while(loop_condition) { // Loop body // Statements; }

Example Let’s look at the Guess Number example ▫p162

Controlling a Loop with a Sentinel Value So far, we’ve used a counter to control a loop Now we use sentinels ▫Sentinels are special variables that you designate to signal the end of a loop Use by creating a variable to designate as a sentinel ▫Select a value to represent the end of a loop Called a sentinel-controlled loop

Controlling a Loop with a Sentinel Value (2) Sentinels are easy to use ▫Create a variable;  int, boolean, fine ▫Give the sentinel an initial value ▫Make the loop true so long as the sentinel is that value ▫Change the sentinel value when you’re done. boolean sentinel=true; //sentinel while(sentinel) { //Statements; // When I’m done: sentinel = false; }

Controlling a Loop with a Sentinel Value (3) Let’s look at an example: ▫P166 ▫SentinelValue.java

Possible Errors Don’t use floating-point values for equality checking in a loop control! ▫Floating point values are approximations for some values ▫May not give correct results  Infinite loop!!!

Input/Output Redirections You can type in inputs from a file simulating console input. ▫Called input redirection ▫Use < to designate input from a file directly to your program (used like console input) Ex: ▫java SentinelValue < input.txt ▫Takes the values from input.txt and uses them like console input ▫Make sure you use spaces between values in your file!

Input/Output Redirections (2) You can automatically save the output of a program in a file using output redirection ▫Use > to put the results of a program directly into a file Ex: ▫java ClassName > output.txt Note: You can use both input and output redirection at the same time Ex:  java SentinelValue output.txt  java SentinelValue > output.txt < input.txt

The do-while Loop The do-while is the same as the while loop, but it executes it’s loop body first Use the same way as the while loop, but for when you need to execute the body at least once ▫Typically for checking bad input ▫Not used often ▫Don’t forget the semicolon(;) after the while portion!!! do { //Loop body //Statements; } while(loop_condition);

The do-while Loop (2) Typical use of a do-while loop: The program allows you to enter in values until zero ▫Program then continues ▫You can use it to verify data Scanner input = new Scanner(System.in); do //read in data until it’s 0 { System.out.println(“Enter an integer. Ends at 0: ”); data = input.nextInt(); } while(data!=0);

The for Loop The for loop has a detailed way of constructing a loop ▫That’s it. There’s nothing additional to the logic of a for loop Structure: ▫Keep in mind: there’s no difference in logic, just the structure of the for loop for(initial_action; loop_condition; action_after_iteration) { //Loop body //Statements; }

The for Loop forInitial actionLoop condition Action after iteration Loop Body ( ; ; ) for loop steps: Initial action (or initialization Check the loop condition Execute loop body Perform action after iteration Check loop condition again: If still true, execute loop body again and repeat { }

for Loop Examples Typical for Loop Structure: ▫We are using i as a loop counter. However, we now initialize i in the initial action, increment i in the iteration action, and limit a value on i in the loop condition for(i = initialValue; i<endValue; i++) { //Loop body }

for Loop Examples (2) Ex:Let’s print “Welcome to Java!” 100 times! Ans: ▫This is a simplified way of performing the earlier loop  What’s our initial action?  Loop condition?  Action after initialization? int i; for(i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); }

for Loop Examples (3) You can declare a new variable in the initial action: ▫Compare: int i; for(i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); } for(int i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); }

for Loop Examples (4) The initial action, and the action after iteration can both include a list of zero or more comma- separated statements ▫Initial action: Zero or more variable declaration statements or assignment expressions for(int i = 0, j = 0; i + j<10; i++, j++) { //Something }

for Loop Examples (5) Action after iteration: Zero or more comma- separated statements: Note: Don’t do this too much, or else your program will be unreadable for(int i = 1; i<100; System.out.println(i), i++);

For loop Weirdness Speaking of, what are the results of these for loops: ▫for(;;) ▫for(; true;) ▫while(true); People will ask for this on a job interview! ▫Xerox

For Loop Weirdness (2) Keep in mind, any legal assignment statement, conditional, and statement can be placed in a for loop. Is this legal? for(variable declaration or assignment; conditional; statement); for(int x = 5;”Test”.equals(“Test”); System.out.println(“Hello”)); for(String z=“Hello”;true; number = input.next());

Which loop to use? While, for loops called pretest loops ▫Loop condition is checked before loop body is executed Do-while loop called posttest loop ▫Loop condition is checked after loop body is executed While, d0-while, and for loops are expressively equivalent ▫You can write a loop is any of these forms ▫You can always convert a while loop to a for loop

Which loop to use? (2) Use the loop structure that’s best for you! ▫Nothing requires a specific type of loop ▫It only depends on your preference  Or ease!

Nested Loops You can have nested loops! ▫Loops within loops How does it work! ▫Think in terms of outer / inner ▫For each iteration of the outer loop, the inner loop runs fully

Nested Loops (2) for(int x=0; x<3; ++x) { for(int y=0; y<100; ++y); } for(int y=0; y<100; ++y); //Runs 100 times for(int y=0; y<100; ++y); //Runs 100 times for(int y=0; y<100; ++y); //Runs 100 times Iteration: x=0 Iteration: x=1 Iteration: x=2 How many times does the whole thing run?

Nested Loops (3) The last loop ran the inner loop every time per iteration of the outer. ▫N outer iterations x N inner iterations ▫Multiply each total inner by each outer How many times does this loop run? for (int x=0; x<10000; ++x) for(int y=0; y<10000; ++y) for(int z=0; z<10000;++z) System.out.println(x+y+z);

Minimizing Numeric Errors There are many many potential errors when it comes to using floating-point numbers in loop conditions ▫We can minimize errors, but will never be free of them Look at this code snippet: ▫What is the result? for(float i = 0.01; i<= 1.0f; i=i+0.01f) sum +=i; System.out.println(“Sum = “+sum);

Minimizing Numeric Errors (2) The sum should be 50.50, but is actually ▫Why? Precision errors. Change the type to double: ▫What is the result? for(float i = 0.01f; i<= 1.0f; i=i+0.01f) sum +=i; System.out.println(“Sum = “+sum); for(double i = 0.0; i<= 1.0; i=i+0.01) sum +=i; System.out.println(“Sum = “+sum);

Minimizing Numeric Errors (3) ▫Result is: ! What’s going on? ▫Floating-point numbers are approximations! Stick to integers when using loop counters for(double i = 0.0; i<= 1.0; i=i+0.01) sum +=i; System.out.println(“Sum = “+sum);

Break and continue You can use break and continue to provide additional controls ▫Break  Completely ends the loop  We used this in a switch statement (remember!!!) ▫Continue  Ends the current iteration of the loop  Goes to the next iteration

Break and continue (2) Look at TestContinue.java ▫p Ex: (p185) Find the smallest factor other than 1 for an integer n ▫You can use break for this: int factor=2; while(factor <= n) { if(n%factor == 0) break; factor++; } System.out.println(“The smallest factor other than 1 for “+n+” is “+factor);

Loops are important! Loops are used almost everywhere in programming! They are very important! I will give you tons of loop work in this class! ▫They will be used continuously afterward! Good luck!