Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
June 10, 2015ICS102: while & do-while1 while and do-while Statements.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Loops –For For Reading for this Lecture, L&L, Part of 5.8.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Flow of Control Loops – Chapter 3.2. Java Loop Statements: Outline the while Statement the do-while Statement the for Statement.
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
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: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
CPS120 Introduction to Computer Science Iteration (Looping)
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
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,
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
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 Prepared by Gary Langner Types of Loops u for loop (entrance controlled) –do an action for a definite number of times u while loop (entrance controlled.
Programming with Loops. When to Use a Loop  Whenever you have a repeated set of actions, you should consider using a loop.  For example, if you have.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
CPS120 Introduction to Computer Science Iteration (Looping)
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Loops and Files. 5.1 The Increment and Decrement Operators.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
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 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
COMP Loop Statements Yi Hong May 21, 2015.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
1 Week 9 Loops. 2 Repetition: Loops l Structure: »Usually some initialization code »body of loop »loop termination condition l Several logical organizations.
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 5 Control Structures II: Repetition.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 4 Repetition Statements (loops)
Loops.
Chapter 5: Control Structures II
Loop Structures.
Chapter 5: Control Structures II
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 14, 2011
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Announcements Lab 3 was due today Assignment 2 due next Wednesday
Presentation transcript:

Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS

Repeating an Action Calculating student grades without loops read student name read number of correct answers of student calculate letter grade read student name read number of correct answers of student calculate letter grade read student name read number of correct answers of student calculate letter grade

Repeating an Action Calculating student grades with a loop read student name read number of correct answers of student calculate letter grade repeat until all students have been processed What do you need to determine when designing a loop? The actions the body of the loop will perform How/when will the loop stop

The while Statement SYNTAX while (Boolean_Expression) Body Body can consist of multiple statements enclosed in braces { } Start Evaluate expression Execute body End loop True False

Example: Calculating the Sum int howManyNumbers = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum); A good programmer would not assume that the input is well formed.

Using A Negative Number Terminate the Loop Add numbers till the user enters 0 or a smaller number int nextNumber = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); while (nextNumber >= 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum); What if I also wanted to allow zero to be a valid input? A while loop can perform zero iterations

Adding 0 to Termination Inputs Add numbers till the user enters a negative number Can you use a while loop to code an if statement? int nextNumber = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); while (nextNumber >= 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum); int sum = 0; int nextNumber = keyboard.nextInt(); while (nextNumber > 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum);

Terminating the Loop int howManyNumbers = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum); The condition of the while statement needs to at some point return false. Otherwise the loop will never terminate  Infinite loop

One Loop is Not Enough int sum = 0; int nextNumber = keyboard.nextInt(); while (nextNumber > 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum); The while loop is not robust enough for this example

The do-while Statement SYNTAX do Body while (Boolean_Expression); Body can consist of multiple statements enclosed in braces { } The body is always executed at least once Start Evaluate expression Execute body End loop True False Notice the semicolon

Revisiting the Previous Example Add numbers till the user enters a negative number int sum = 0; int nextNumber = 0; do { sum += nextNumber; nextNumber = keyboard.nextInt(); } while (nextNumber >= 0); System.out.println(“Sum: “ + sum);

Reasoning About Loops int n = 1; double x = 0, s = 0; do { s = 10 / n * n; x = x + s; n++; } while (s > 0.1); Transform it to a while loop How many times will this loop execute? int n = 1; double x = 0, s = 1.0; while (s > 0.1) { s = 10 / n * n; x = x + s; n++; }

Nested Loops int sum = 0, nextNumber = 0, noNumbers = 0; String answer; do { nextNumber = keyboard.nextInt(); while (nextNumber >= 0) { sum += nextNumber; noNumbers++; nextNumber = keyboard.nextInt(); } System.out.println(“Average: “ + (sum / noNumbers); System.out.println(“Do you want to go again (yes/no)?”); answer = keyboard.next(); } while (answer.equalsIgnoreCase(“yes”)); These numbers not initialized with the proper values after the first iteration of the outer loop

Nested Loops int sum, nextNumber, noNumbers; String answer; do { sum = NoNumbers = 0; nextNumber = keyboard.nextInt(); while (nextNumber >= 0) { sum += nextNumber; noNumbers++; nextNumber = keyboard.nextInt(); } System.out.println(“Average: “ + (sum / noNumbers); System.out.println(“Do you want to go again (yes/no)?”); answer = keyboard.next(); } while (answer.equalsIgnoreCase(“yes”)); Initialization should be in the loop

The for Statement All loops ◦…have an initialization/setup phase ◦…modify the condition that control when the looping ceases The for loop enables you to easily write a loop that clearly defines these steps ◦Such as loops controlled by a counter SYNTAX for (Initializing_Action; Boolean_Expression; Update_Action) Body Body can consist of multiple statements enclosed in braces { }

Start Evaluate expression Execute body End loop True False Execute Initializing_Actioin Execute Update_Action

Easy Counting With for Loops int count; for (count = 0; count < 3; count++) { System.out.println(“Counter: “ + count); } int countDown; for (countDown = 10; count > 0; count--) { System.out.println(count); System.out.println(“and counting”); } System.out.println("Blast off!");

for and while Loops Initializing_Action; while (Boolean_Expression) { Statements... Update_Action; } for (Initializing_Action; Boolean_Expression; Update_Action;) Statements... } For loops are essentially a specialization of while loops

Multiple Statements in for Loops int i, j; for (i = 0, j = 0; i < 10; i++, j += 2) { System.out.println(i * j); } Initialization can include multiple statements separated by commas Same stands for the update statements What can you do for multiple conditions

Declaring Variables in for Loops for (int i = 0, j = 0; i < 10; i++, j += 2) { System.out.println(i * j); }

Common Errors int product = 1, number; for (number = 1; number <= 10; number++); { product = product * number; } System.out.println("Product of the numbers 1 through " + "10 is " + product); A semicolon at the end means that the body of the for loop is empty

A Semicolon and a while Loop int product = 1, number = 1; while (number <= 10); { product = product * number; number++; } System.out.println("Product of the numbers 1 through " + "10 is " + product); What happens here?

Picking the Right Loop Use a do-while loop only when you are certain that the loop needs to execute exactly once If your loop has well-defined initialization and update statements use a for loop Otherwise use while These are general guidelines, the final decision depends on the problem

for-each Statement Can be applied on variables that can only have certain values ◦Example: enumerations ◦We will later see other data that can be used with for-each loops enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}; for (Suit nextSuit : Suit.values()) System.out.print(nextSuit + " "); System.out.println();

Programming with Loops 1. Display instructions to the user 2. Initialize variables 3. Read a number into the variable next. 4. sum = sum + next 5. Display the number and the sum so far. 6. Read another number into the variable next. 7. sum = sum + next 8. Display the number and the sum so far. 9. Read another number into the variable next. 10. sum = sum + next 11. Display the number and the sum so far. 12. Read another number into the variable next. Write out the sequence of actions that you need to accomplish Identify patterns 1. Display instructions to the user. 2. Initialize variables. 3. Repeat the following for the appropriate number of times. { Read a number into the variable next. sum = sum + next Display the number and the sum so far. } Write the sequence using a loop

Using Boolean Variables to End a Loop int next, sum = 0; boolean thereAreMoreNumbersToRead = true; while (thereAreMoreNumbersToRead) { next = keyboard.nextInt(); if (next < 0) thereAreMoreNumbersToRead = false; else sum = sum + next; }

The break Statement A break statement within a loop causes an immediate exit from the loop body Use them wisely ◦To handle errors ◦If they actually make your code more readable ◦To handle rare conditions occurring Using break frequently makes loops harder to reason with In nested loops break only stops the innermost loop

Example using break int howManyNumbers = 0; int sum = 0, nextNumber; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) { nextNumber = keyboard.nextInt(); if (nextNumber < 0) break; sum += nextNumber; } System.out.println(“Sum: “ + sum); int howManyNumbers = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum);

The continue Statement A continue statement within a loop ends the current iteration and begins the next one Use them wisely ◦If they actually make your code more readable ◦To handle rare conditions occurring Using continue frequently makes loops harder to reason with In nested loops continue corresponds to the innermost loop In for loops it also triggers the update actions

Example using continue int howManyNumbers = 0; int sum = 0, nextNumber; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) { nextNumber = keyboard.nextInt(); if (nextNumber < 0) continue; sum += nextNumber; } System.out.println(“Sum: “ + sum); int howManyNumbers = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers = keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum);

Loop Bugs Infinite loops Off-by-one errors ◦Executing one more or less iteration of a loop ◦Due to erroneous boolean expression ◦Example: Using < instead of a <=