Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.

Similar presentations


Presentation on theme: "Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that."— Presentation transcript:

1 Week 5: Loops 1

2  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 2

3  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 3

4  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 4

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

6  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; 6

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

8  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 8

9 //line A while( condition ) { //line B statement1; statement2; //line C … statementn; } //line D LineCondition An B C D LineCondition AUnknown B C D LineCondition AUnknown BTrue C D LineCondition AUnknown BTrue CUnknown D LineCondition AUnknown BTrue CUnknown DFalse 9

10  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 10

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

12  We could also find the average: int i = 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)); 12

13  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; 13

14  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 14

15 1. Start with the minimum and maximum of the range 2. Find the midpoint 3. Ask the user if the midpoint is correct 4. If the answer is too high, go to Step 1 using the minimum and the midpoint as the new range 5. If the answer is too low, go to Step 1 using the midpoint and the maximum as the new range 6. If the midpoint is correct, you’re done! 15

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

17 17

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

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

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

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

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

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

24  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 24

25  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: 1. Initialization 2. Condition 3. Increment 25

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

27  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; 27

28  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++; } 28

29  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); } 29

30  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 30

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

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

33  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 33

34 do { statement1; statement2; … statementn; } while( condition ); 34

35  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 35

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

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

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

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

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

41  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( int i = 1; i <= 40; i++ ); //semicolon is wrong { System.out.println(i); } 41


Download ppt "Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that."

Similar presentations


Ads by Google