Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS"— Presentation transcript:

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

2 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

3 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

4 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

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

6 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

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

8 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

9 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

10 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

11 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);

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

13 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

14 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

15 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 { }

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

17 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!");

18 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

19 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

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

21 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

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

23 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

24 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();

25 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

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

27 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

28 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);

29 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

30 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);

31 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 <=

32


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

Similar presentations


Ads by Google