410 likes | 621 Views
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.
E N D
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 • 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
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
Anatomy of a while loop while( condition ) { statement1; statement2; … statementn; } A whole bunch of statements
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;
Printing numbers • Let’s print the numbers from 1 to 100 inti = 1; while( i <= 100 ) { System.out.println(i); i++; }
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
Workings of a while loop //line A while( condition ) { //line B statement1; statement2; //line C … statementn; } //line D
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
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);
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));
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;
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
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!
Nested loops • Just as with if-statements, it’s possible to nest loops • A repetitive task can be done inside of another repetitive task
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 }
Badly-written loops int n = 40; inti = 1; while( i <= n ) { System.out.println(i); i--; //woops, should have been i++ }
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++; }
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++; }
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++; }
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
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
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
Anatomy of a for loop Starting Point Way to Progress for( init; condition; inc ) { statement1; statement2; … statementn; } Ending Point
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;
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++; }
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); }
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
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.”); } }
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; • }
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
Anatomy of a do-while loop do { statement1; statement2; … statementn; } while( condition );
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
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 );
Infinite for loops for( inti = 0; i < 10; i++ ) { System.out.println(i); //lots of other code i--; //woops }
Bad increment inti; for( i = 1; i <= 40; i-- ) • //woops, should have been i++ System.out.println(i);
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);
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);
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); }