320 likes | 415 Views
Intro to CS – Honors I Control Flow: Loops. Georgios Portokalidis gportoka@stevens.edu. Repeating an Action. Calculating student grades without loops read student name read number of correct answers of student c alculate letter grade read student name
E N D
Intro to CS – Honors IControl Flow: Loops Georgios Portokalidis gportoka@stevens.edu
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 False True Execute body End loop
Example: Calculating the Sum inthowManyNumbers= 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 intnextNumber = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); while (nextNumber >= 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum); A while loop can perform zero iterations What if I also wanted to allow zero to be a valid input?
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 sum = 0; intnextNumber= keyboard.nextInt(); while (nextNumber> 0) { sum += nextNumber; nextNumber= keyboard.nextInt(); } System.out.println(“Sum: “ + sum); intnextNumber = 0; int sum = 0; Scanner keyboard = new Scanner(System.in); while (nextNumber >= 0) { sum += nextNumber; nextNumber = keyboard.nextInt(); } System.out.println(“Sum: “ + sum);
Terminating the Loop inthowManyNumbers= 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; intnextNumber= 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 Notice the semicolon Execute body Evaluate expression False True End loop
Revisiting the Previous Example • Add numbers till the user enters a negative number int sum = 0; intnextNumber = 0; do { sum += nextNumber; nextNumber= keyboard.nextInt(); } while (nextNumber >= 0); System.out.println(“Sum: “ + sum);
Reasoning About Loops How many times will this loop execute? int n = 1;double x = 0, s = 0; do {s = 10 / n * n;x = x + s;n++;} while (s > 0.1); int n = 1;double x = 0, s = 1.0; while (s > 0.1) {s = 10 / n * n;x = x + s;n++;} Transform it to a while loop
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 Execute Initializing_Actioin Evaluate expression False True End loop Execute body Execute Update_Action
Easy Counting With for Loops int count; for (count = 0; count < 3; count++) { System.out.println(“Counter: “ + count); } intcountDown; for (countDown = 10; count > 0; count--) { System.out.println(count); System.out.println(“and counting”); } System.out.println("Blast off!");
for and while Loops for (Initializing_Action; Boolean_Expression; Update_Action;) Statements . . . } Initializing_Action; while (Boolean_Expression) { Statements . . . Update_Action; } For loops are essentially a specialization of while loops
Multiple Statements in for Loops Initialization can include multiple statements separated by commas Same stands for the update statements inti, j; for (i = 0, j = 0; i < 10; i++, j += 2) { System.out.println(i* j); } What can you do for multiple conditions
Declaring Variables in for Loops for (inti= 0, j = 0; i < 10; i++, j += 2) { System.out.println(i* j); }
Common Errors A semicolon at the end means that the body of the for loop is empty 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 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. 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. } • 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 Write the sequence using a loop
Using Boolean Variables to End a Loop int next, sum = 0; booleanthereAreMoreNumbersToRead = 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 inthowManyNumbers= 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers= keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum); inthowManyNumbers= 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);
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 inthowManyNumbers= 0; int sum = 0; Scanner keyboard = new Scanner(System.in); howManyNumbers= keyboard.nextInt(); while (howManyNumbers-- > 0) sum += keyboard.nextInt(); System.out.println(“Sum: “ + sum); inthowManyNumbers= 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);
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 <=