330 likes | 547 Views
Java Unit 7: Loops. While Loops and Do Loops. Why use Loops?. Suppose you wanted to repeat the same code over and over again? System.out.println (“text”); System.out.println (“text ”); System.out.println (“text ”); …
E N D
Java Unit 7: Loops While Loops and Do Loops
Why use Loops? • Suppose you wanted to repeat the same code over and over again? • System.out.println(“text”);System.out.println(“text”);System.out.println(“text”);… • It would be tiresome to write out this code over and over, and with enough ‘iterations’ of this code, it would soon be confusing what you’re trying to accomplish.
Why use Loops? • A loop is a kind of structure that can iterate over the same code multiple times. • There are several different loops that Java uses, like while loops, do loops, and for loops. • For all loops, there is typically a way to set when a loop stops. These are set differently for each one. • Typically, there will be a boolean expression somewhere that has the loop stop when that boolean expression results to false.
While loop • Scanner in = new Scanner(System.in)String answer = “yes”;while(!answer.equalsIgnoreCase(“no”)){ //code codecodecodeSystem.out.println(“Go again? Answer yes or no.”); answer = in.nextString();}
While loop • A while loop starts off with the ‘while’ keyword, followed by a boolean expression in parenthesis. The while loop also has a pair of brackets, just like an if statement. • while(myInt1 > myInt2) { … } • If the expression in the parenthesis results to true, the loop runs the code inside the brackets that follow. • The while loop will continue to run for as long as the running condition is true. • The running condition is checked at the beginning of the loop, and again after its code inside the body is executed. • Because we set our own conditions for looping, loops are especially great when we don’t know in advance how many times to repeat code.
While loop • To put it in a better way, using pseudocode: • 1. Check condition • 2. If condition = true, go to line 3, otherwise go to line 5. • 3. Run loop code • 4. Go to line 1 (this is the end of the loop body) • 5. Exit the loop
While loop • int i = 0;while(i < 4){System.out.print(“” + i); i++} • The results of this would be: 0123 • Once i equals 4 or higher, the loop exits because its running condition is no longer true.
While loop • int i = 4;while(i < 4){System.out.print(“” + i); i++} • The results of this would be: • Nothing • By the time the loop is reached, i = 4, so the running condition is false and the loop is entirely skipped.
While loop • Notice in the previous slide that inside the body of the while loop, we are altering a variable involved in the running condition. • If we had not altered ‘i‘, then the running condition would always hold true. Therefore, the loop would run infinitely. • Typically, to avoid accidental infinite loops, it is desirable to alter one of the variables of the condition every frame so that it will eventually become false and exit the loop.
Do Loops • Do loops work the same way as while loops, with one exception. • Instead of evaluating the looping condition at the beginning like a while loop does, it evaluates it at the end of the body. • As such, the loop starts with ‘do’, and ends with ‘while’ and the conditional statement, followed by a semicolon. • The program will go through the body of the loop once, and then check the condition to see if it should run again. • Therefore, do loops will always run at least once. • They are written like so: • do { // …code…} while(loopingCondition); //Don’t forget the semicolon!
Do Loops • int i = 0;do {System.out.println(“” + i); i++;} while(i < 0); • Result: 0 • Even though the do loop condition is false from the beginning, the body of the loop will run at least once because it only checks if its true at the end of the loop.
Loops and Overflows • Consider this piece of code • int i = 0;while (i < 4) {System.out.println(“” + i); i++;} • Obviously, this would stop at some point.
Loops and Overflows • Now, what would happen if, instead, ‘i‘ decremented every iteration? • I would never go up to 4, so the looping condition is always true? • However, recall that values have a certain amount of data set to them (say, 4 bytes, for ints) • As ‘I’ is constantly decremented, its magnitude (not the value) is getting bigger and bigger because the looping condition never stops. • Soon, it gets to a point where the number’s magnitude is so big, it can’t fit into four bytes.
Loops and Overflows • When a number gets to a value that is so big that it can’t fit into the data space it is given, an overflow occurs. • In some languages, this generates an error. • But it Java, IT DOES NOT. • What happens instead is that the number ‘rolls over’ from the largest negative number, over to the largest positive number. • This is an effect of how numbers are stored inside memory. • In our case, after ‘i‘ rolls over to a very large positive number, the loop condition (i < 4) finally becomes false, and the loop stops on that very large positive number. • This is especially important to us, because this does not produce an error, so it may be hard to spot and fix.
Loop conditions that are always true • It is also possible to write a loop such as: • while(true) { …code…} • Here, in the running condition, true = true. • But of course, we wouldn’t want that because the loop would run infinitely. • And just like with overflowing, this does not produce an error. The program would be stuck inside the body of the loop forever. Or until the user closes the application. • When you, as a developer, run in to this problem, there is a red square near the console window in Eclipse you could press to terminate your program.
Breaking from loops • There exists a way to prematurely exit the loop with the ‘break’ keyword. • while(true) { …code… break;} • The break keyword exits the loop it belongs to as soon as it is reached, regardless of the running condition. • However, this design is not recommended, because it doesn’t make it clear from the running condition when the loop is supposed to exit.
Loop Conditions and Inequalities • In general, loops based on numeric values are based on a test of inequality, where one value or another decreases or increases inside the body of the loop. • Consider this: • While(x < y) { …increase x by some amount…} • Once x goes over y, the loop exits. • But this: • while(x != y) { …increase x by some amount… } • This isn’t recommended to do, since we’re increasing x by ‘some’ amount, and it may completely skip over y.
Loop Conditions and Inequalities • This would also be unwise: • while(myFloat1 != myFloat2) { …increment myFloat1 by something…} • In the case of floats and other decimal values, binary representations of two floats may not be exact (even if they’re really close) • Recall the possibility of getting a value like 4.9999999 instead of 5.0 from doing floating-point arithmetic. • This is where using inequality operators like ‘<‘, ‘>’, ‘<=‘, and ‘>=‘ is desirable, because even if we aren’t sure whether two numbers are equal, we can be sure that one number is at least greater than or less than another number.
Loop Recommendations • Recommended guidelines for writing loops: • Always use a running condition that will eventually become false. • Inside the body of the loop, there should be something that affects one of the running condition variables. It should be incremented, decremented, or set in such a way that it will make the running condition false if it continues running. • Be wary of the possibility of overflowing. Overflowing won’t stop the code from running and won’t produce an error. • The ‘break’ keyword is there to prematurely exit loops. But this should be avoided for the sake of readability and testing. • Prefer using greater than, less than operators when dealing with numbers in the loop condition. Never test for equality.