1 / 41

CS 177

Week 5: Loops. CS 177. Repetition. Repetition is the ability to do something over and over again With repetition in the mix, we can solve practically any problem that can be solved with a computer Repetition leverages the most famous ability of the computer: speed. Mechanics.

muncel
Download Presentation

CS 177

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 5: Loops CS 177

  2. Repetition • Repetition is the ability to do something over and over again • With repetition in the mix, we can solve practically any problem that can be solved with a computer • Repetition leverages the most famous ability of the computer: speed

  3. Mechanics • The main way that repetition works in Java is through loops • A loop is a block of code that will be executed repeatedly some number of times (perhaps even zero times!) • As the statements are executed, variables may change • It isn’t just repeating the same thing over and over

  4. while loop • The simplest loop in Java is the while loop • It looks similar to an if statement • The difference is that, when you get to the end of the while loop, it jumps back to the top • If the condition in the while loop is still true, it executes the body of the loop again

  5. Anatomy of a while loop while( condition ) { statement1; statement2; … statementn; } A whole bunch of statements

  6. A while loop with only one statement • A while loop will usually have multiple statements in its body • However, it is possible to make a while loop with only a single statement • Then, like an if-statement, the braces are optional while( condition ) statement;

  7. Printing numbers • Let’s print the numbers from 1 to 100 inti = 1; while( i <= 100 ) { System.out.println(i); i++; }

  8. Rules for while • The while loop checks if the condition is true, and if so, executes each statement one by one • When execution gets to the bottom, it jumps back up to the top • If the condition is still true (i.e., i <= 100), it repeats the loop

  9. Workings of a while loop //line A while( condition ) { //line B statement1; statement2; //line C … statementn; } //line D

  10. Summing numbers • We can also use while loops to help us deal with input • What if we wanted to sum all of the numbers that a person entered? • How would we know when to stop? • One solution is to keep adding numbers until the person enters a negative number • This is called using a sentinel value

  11. Summing numbers • Solution: inti = 0; int sum = 0; while( i >= 0 ) { sum += i; System.out.print(“Enter number: “); i = StdIn.readInt(); } System.out.println(“Sum: “ + sum);

  12. Finding the average • We could also find the average: inti = 0; double sum = 0; int count = 0; while( i >= 0 ) { sum += i; count++; System.out.print(“Enter number: “); i = StdIn.readInt(); } count--; //fixes extra count for sentinel • System.out.println(“Average: “ + (sum / count));

  13. Tracking the biggest input • What if we wanted to find the biggest input? • Somehow we would have to check each input and see if it were larger than the current largest • Solution: use an if-statement inside of a while loop • if (i > iBig) iBig = i;

  14. Guessing game • Let’s say that you wanted to write a program to guess a number that a person had come up • The number is between 1 and 100 • Every time the computer guesses a number, the person enters: • H if the number is too high • L if the number is too low • F if the number was found

  15. Guessing game algorithm • Start with the minimum and maximum of the range • Find the midpoint • Ask the user if the midpoint is correct • If the answer is too high, go to Step 1 using the minimum and the midpoint as the new range • If the answer is too low, go to Step 1 using the midpoint and the maximum as the new range • If the midpoint is correct, you’re done!

  16. Nested loops • Just as with if-statements, it’s possible to nest loops • A repetitive task can be done inside of another repetitive task

  17. C0mmon Pitfalls with while Loops

  18. Infinite loops • Loops can go on forever if you aren’t careful int n = 40; inti = 1; while( i <= n ) { System.out.println(i); //supposed to print all the numbers //less than 40, but i never increases }

  19. Badly-written loops int n = 40; inti = 1; while( i <= n ) { System.out.println(i); i--; //woops, should have been i++ }

  20. Fencepost errors • Being off by one is a very common loop error int n = 40; inti = 1; while( i < n ) //won’t //reach n { System.out.println(i); i++; }

  21. Skipping loops entirely • If the condition isn’t true to begin with, the loop will just be skipped int n = 40; inti = 1; while( i >= n ) //oops, should be <= { System.out.println(i); i++; }

  22. Misplaced semicolon • A misplaced semicolon can cause an empty loop body to be executed (often infinitely) int n = 40; inti = 1; while( i <= n ); //semicolon is wrong { System.out.println(i); i++; }

  23. 3 loops in Java • while loops • Used when you don’t know how many times you are going to need to repeat • for loops • Used when you do know how many times you are going to repeat • do-while loops • Used almost never • Oh, okay, they are used whenever you need to be guaranteed the loop runs at least once

  24. Loops are interchangeable • Any problem that uses loops can use any kind of loop • The choice is supposed to make things easier on the programmer • Some loops are more convenient for certain kinds of problems

  25. forloops • for loops are great when you know how many times a loop will run • They are the most commonly used of all loops • They are perfect for any task that needs to run, say, 100 times • A for loop has 3 parts in its header: • Initialization • Condition • Increment

  26. Anatomy of a for loop Starting Point Way to Progress for( init; condition; inc ) { statement1; statement2; … statementn; } Ending Point

  27. A for loop with only one statement • A for loop will usually have multiple statements in its body • However, it is possible to make a for loop with only a single statement • Then, like if-statements and while-loops, the braces are optional for( init; condition; inc ) statement;

  28. for loop example • Let’s print the numbers from 1 to 100 (again) • Remember how this was done with while: i= 1; while( i <= 100 ) { System.out.println(i); i++; }

  29. for loop example • A for loop is specifically designed for this sort of thing: • The initialization and the increment are built-in for( i= 1; i <= 100; i++ ) { System.out.println(i); }

  30. Finding primes • To see if a number is prime, we can divide by all the numbers less than the number to see if it can be evenly divided • Sounds like a perfect opportunity for a for loop

  31. Testing for a prime • The following code will tell you if a number isn’t prime • What’s the problem? int number = StdIn.readInt(); for( inti = 2; i < number; i++) { if( number % i == 0 ) { System.out.println(number + “ is not prime.”); } }

  32. Better testing for a prime • By adding a boolean, we can keep track of whether or not the number is prime • int number = StdIn.readInt(); • boolean prime = true; • for( inti = 2; i < number && prime; i++) • { • if( number % i == 0 ) • prime = false; • }

  33. do-whileloops • They work just like while loops • The only difference is that they are guaranteed to execute at least once • Unlike a while loop, the condition isn’t checked the first time you go into the loop • Sometimes this is especially useful for getting input from the user • The syntax is a little bit different

  34. Anatomy of a do-while loop do { statement1; statement2; … statementn; } while( condition );

  35. Common pitfalls • Almost all of these are issues with while, for and do-while loops as well • Many of these errors have to do with incorrect starting or ending conditions for the loop

  36. Infinite loops • Loops can go on forever if you aren’t careful int n = 40; inti = 1; do { System.out.println(i); //supposed to print all the numbers //less than 40, but i never increases • } while( i <= n );

  37. Infinite for loops for( inti = 0; i < 10; i++ ) { System.out.println(i); //lots of other code i--; //woops }

  38. Bad increment inti; for( i = 1; i <= 40; i-- ) • //woops, should have been i++ System.out.println(i);

  39. Fencepost errors • Being off by one is a very common loop error inti; for( i = 1; i < 40; i++ ) //runs 39 times System.out.println(i);

  40. Skipping loops entirely • If the condition isn’t true to begin with, the loop will just be skipped for( inti = 1; i >= 40; i++ ) //oops, should be <= System.out.println(i);

  41. Misplaced semicolon • A misplaced semicolon can cause an empty loop body to be executed • Everything looks good, loop even terminates • But, only one number will be printed: 41 for( inti = 1; i <= 40; i++ ); //semicolon is wrong { System.out.println(i); }

More Related