Presentation is loading. Please wait.

Presentation is loading. Please wait.

By Chad Blankenbeker.  The for-loop is best used when you know how many times it is going to be looped  So if you know you want it to only loop 10 times,

Similar presentations


Presentation on theme: "By Chad Blankenbeker.  The for-loop is best used when you know how many times it is going to be looped  So if you know you want it to only loop 10 times,"— Presentation transcript:

1 By Chad Blankenbeker

2  The for-loop is best used when you know how many times it is going to be looped  So if you know you want it to only loop 10 times, a for-loop would be best. If you do not know how many times you want it looped, you should use one of the other loops discussed later in this powerpoint.

3  So right about know I bet you’re wondering how to set up a for-loop. It is relatively simple so here is an example: for(int i=1; i<11; i++) { System.out.println("Count is: " + i); }  Every time this loop loops, it adds one to the count (integer variable i ) and also prints what the count currently is.

4  Do-While loops are best used for when you don’t know how many times you want the loop to run, but you do know when you want it to stop.  So essentially if you know you want it to stop when the count gets to 20, you could do that and you would not have to know.  Note: the major difference between the do- while and the while loop discussed next is that the do-while evaluates its expression at the bottom of the loop instead of the top

5  Here is example coding of the Do-While loop: do { System.out.println("Count is: " + count); count++; } while (count <= 11);  This code prints loops while count is less than or equal to 11. If the count++ was placed before the print statement, the loops last print would print 12 because it had not gotten to the expression yet.

6  The While-Loop is also best for when you don’t know how many times you want to run it, you know when you want it to stop looping, and you want the expression at the beginning of the loop.  This loop is slightly more common than the do- while loop

7  Here is some sample code: while (count < 11) { System.out.println("Count is: " + count); count++; }  This is similar in the nature to the do-while, but its expression is at the beginning of the loop.

8  The three main types of loop have been covered, so let’s see how much you’ve learned (answers on next slide) 1. What does count equal after this executes? int count = 5; for (int i = 1; i<6; i++) { count++; }

9 2. Which loop is this? do { System.out.println(“The count is: “ + count); count++; } while count<5

10  The answer to question 1 is 10.  The answer to question 2 is a do-while loop.


Download ppt "By Chad Blankenbeker.  The for-loop is best used when you know how many times it is going to be looped  So if you know you want it to only loop 10 times,"

Similar presentations


Ads by Google