Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.

Similar presentations


Presentation on theme: "Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles."— Presentation transcript:

1 Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles

2 What we will cover… Intro to loops While loops Loop design Sentinels Input / Output Redirections The do-while Loop The for Loop Which Loop to use? Nested Loops break and continue

3 Introduction to Loops! Suppose you want to do something many different times ▫5 times – 5 lines of code ▫10 times – maybe 10 separate lines of code ▫100, 1000 times?  You can’t write the same lines of code so many times.  Instead, we use loops! Loops can be used to control how many times an operation (or sequence) is performed

4 Introduction to Loops (2) Ex: You want to print something out 100 times ▫Instead of copy/pasting the same line of code:  System.out.println(“Welcome to Java!”); ▫We say: int count=0; while (count < 100) { System.out.println(“Welcome to Java!”); count++; } ▫We are using what’s called a while loop

5 The while Loop while(loop_condition) { //Loop Body Statements; } The while loop continually executes the statements within the block so long as the loop condition is true ▫As soon as the condition turns false, the loop is stopped and the program continues

6 The while Loop (2) Terminology ▫Loop continuation condition  A condition that must be true in order for the loop to repeat  Boolean ▫Loop body  Part that contains statements to be repeated ▫Iteration  A Single execution of the loop  Also called a repetition while(loop_condition) { //Loop Body Statements; }

7 The while Loop (3) If the loop condition in the while loop is true, the loop will continue to iterate while(loop_condition) Loop Body Statements

8 The while Loop (4) Ex: Print out 100 numbers starting with zero. ▫How to code? ▫Write out all numbers ▫Use a loop! We are doing something 100 times, so let’s start with a counter ▫Call it count We will make the counter keep track of how many times the loop is running ▫Increment the counter during the loop We will stop after 100 times ▫Make the loop condition false after counter runs 100 times Start with zero ▫Make counter start with 0.

9 The while Loop (5) We have used count as output, but also to keep track of the loop ▫This is called a counter-controlled loop int count = 0; while(count < 100) { System.out.println(count); count++; }

10 The while Loop (6) What about these examples? int sum =0, i=1; while(i<10) { sum = sum + i; i++; } System.out.println(“Sum is “+sum); int sum =0, i=1; while(i<10) { sum = sum + i; } System.out.println(“Sum is “+sum);

11 The while Loop (7) The first example works how we want, but the second results in an infinite loop! ▫A loop that doesn’t stop ▫Your program runs forever! ▫Avoid! What happens here? ▫while(true);

12 Off by One Errors Any time you add/sum/multiply/account for a long interval of numbers, you run the risk of an “Off by one error” ▫You have run your loop one more or less time than expected Ex:Display “Welcome to Java” 100 times ▫(Incorrect) Answer:  Why? int count=0; while(count <= 100) { System.out.println(“Welcome to Java!”); count++; }

13 Off by One Errors Let’s look at this again: ▫Count starts with 0 ▫Loop ends with count less than or equal to 100  This includes 100 ▫Therefore the while loop executes from 0 to 100 times, including both 0 and 100  Loop actually executes 101 times int count=0; while(count <= 100) { System.out.println(“Welcome to Java!”); count++; }

14 Loop Design Strategies Loops can be hard if you don’t plan for them Strategies: ▫Identify the statements that need to be repeated ▫Wrap those statements in a loop block ▫Code the loop condition and add statements for controlling the loop  1  2  3 while(loop_condition) { // Loop body // Statements; }

15 Example Let’s look at the Guess Number example ▫p162

16 Controlling a Loop with a Sentinel Value So far, we’ve used a counter to control a loop Now we use sentinels ▫Sentinels are special variables that you designate to signal the end of a loop Use by creating a variable to designate as a sentinel ▫Select a value to represent the end of a loop Called a sentinel-controlled loop

17 Controlling a Loop with a Sentinel Value (2) Sentinels are easy to use ▫Create a variable;  int, boolean, fine ▫Give the sentinel an initial value ▫Make the loop true so long as the sentinel is that value ▫Change the sentinel value when you’re done. boolean sentinel=true; //sentinel while(sentinel) { //Statements; // When I’m done: sentinel = false; }

18 Controlling a Loop with a Sentinel Value (3) Let’s look at an example: ▫P166 ▫SentinelValue.java

19 Possible Errors Don’t use floating-point values for equality checking in a loop control! ▫Floating point values are approximations for some values ▫May not give correct results  Infinite loop!!!

20 Input/Output Redirections You can type in inputs from a file simulating console input. ▫Called input redirection ▫Use < to designate input from a file directly to your program (used like console input) Ex: ▫java SentinelValue < input.txt ▫Takes the values from input.txt and uses them like console input ▫Make sure you use spaces between values in your file!

21 Input/Output Redirections (2) You can automatically save the output of a program in a file using output redirection ▫Use > to put the results of a program directly into a file Ex: ▫java ClassName > output.txt Note: You can use both input and output redirection at the same time Ex:  java SentinelValue output.txt  java SentinelValue > output.txt < input.txt

22 The do-while Loop The do-while is the same as the while loop, but it executes it’s loop body first Use the same way as the while loop, but for when you need to execute the body at least once ▫Typically for checking bad input ▫Not used often ▫Don’t forget the semicolon(;) after the while portion!!! do { //Loop body //Statements; } while(loop_condition);

23 The do-while Loop (2) Typical use of a do-while loop: The program allows you to enter in values until zero ▫Program then continues ▫You can use it to verify data Scanner input = new Scanner(System.in); do //read in data until it’s 0 { System.out.println(“Enter an integer. Ends at 0: ”); data = input.nextInt(); } while(data!=0);

24 The for Loop The for loop has a detailed way of constructing a loop ▫That’s it. There’s nothing additional to the logic of a for loop Structure: ▫Keep in mind: there’s no difference in logic, just the structure of the for loop for(initial_action; loop_condition; action_after_iteration) { //Loop body //Statements; }

25 The for Loop forInitial actionLoop condition Action after iteration Loop Body ( ; ; ) for loop steps: Initial action (or initialization Check the loop condition Execute loop body Perform action after iteration Check loop condition again: If still true, execute loop body again and repeat { }

26 for Loop Examples Typical for Loop Structure: ▫We are using i as a loop counter. However, we now initialize i in the initial action, increment i in the iteration action, and limit a value on i in the loop condition for(i = initialValue; i<endValue; i++) { //Loop body }

27 for Loop Examples (2) Ex:Let’s print “Welcome to Java!” 100 times! Ans: ▫This is a simplified way of performing the earlier loop  What’s our initial action?  Loop condition?  Action after initialization? int i; for(i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); }

28 for Loop Examples (3) You can declare a new variable in the initial action: ▫Compare: int i; for(i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); } for(int i = 0; i<100; i++) { System.out.println(“Welcome to Java!”); }

29 for Loop Examples (4) The initial action, and the action after iteration can both include a list of zero or more comma- separated statements ▫Initial action: Zero or more variable declaration statements or assignment expressions for(int i = 0, j = 0; i + j<10; i++, j++) { //Something }

30 for Loop Examples (5) Action after iteration: Zero or more comma- separated statements: Note: Don’t do this too much, or else your program will be unreadable for(int i = 1; i<100; System.out.println(i), i++);

31 For loop Weirdness Speaking of, what are the results of these for loops: ▫for(;;) ▫for(; true;) ▫while(true); People will ask for this on a job interview! ▫Xerox

32 For Loop Weirdness (2) Keep in mind, any legal assignment statement, conditional, and statement can be placed in a for loop. Is this legal? for(variable declaration or assignment; conditional; statement); for(int x = 5;”Test”.equals(“Test”); System.out.println(“Hello”)); for(String z=“Hello”;true; number = input.next());

33 Which loop to use? While, for loops called pretest loops ▫Loop condition is checked before loop body is executed Do-while loop called posttest loop ▫Loop condition is checked after loop body is executed While, d0-while, and for loops are expressively equivalent ▫You can write a loop is any of these forms ▫You can always convert a while loop to a for loop

34 Which loop to use? (2) Use the loop structure that’s best for you! ▫Nothing requires a specific type of loop ▫It only depends on your preference  Or ease!

35 Nested Loops You can have nested loops! ▫Loops within loops How does it work! ▫Think in terms of outer / inner ▫For each iteration of the outer loop, the inner loop runs fully

36 Nested Loops (2) for(int x=0; x<3; ++x) { for(int y=0; y<100; ++y); } for(int y=0; y<100; ++y); //Runs 100 times for(int y=0; y<100; ++y); //Runs 100 times for(int y=0; y<100; ++y); //Runs 100 times Iteration: x=0 Iteration: x=1 Iteration: x=2 How many times does the whole thing run?

37 Nested Loops (3) The last loop ran the inner loop every time per iteration of the outer. ▫N outer iterations x N inner iterations ▫Multiply each total inner by each outer How many times does this loop run? for (int x=0; x<10000; ++x) for(int y=0; y<10000; ++y) for(int z=0; z<10000;++z) System.out.println(x+y+z);

38 Minimizing Numeric Errors There are many many potential errors when it comes to using floating-point numbers in loop conditions ▫We can minimize errors, but will never be free of them Look at this code snippet: ▫What is the result? for(float i = 0.01; i<= 1.0f; i=i+0.01f) sum +=i; System.out.println(“Sum = “+sum);

39 Minimizing Numeric Errors (2) The sum should be 50.50, but is actually 50.499985 ▫Why? Precision errors. Change the type to double: ▫What is the result? for(float i = 0.01f; i<= 1.0f; i=i+0.01f) sum +=i; System.out.println(“Sum = “+sum); for(double i = 0.0; i<= 1.0; i=i+0.01) sum +=i; System.out.println(“Sum = “+sum);

40 Minimizing Numeric Errors (3) ▫Result is: 49.50000000003! What’s going on? ▫Floating-point numbers are approximations! Stick to integers when using loop counters for(double i = 0.0; i<= 1.0; i=i+0.01) sum +=i; System.out.println(“Sum = “+sum);

41 Break and continue You can use break and continue to provide additional controls ▫Break  Completely ends the loop  We used this in a switch statement (remember!!!) ▫Continue  Ends the current iteration of the loop  Goes to the next iteration

42 Break and continue (2) Look at TestContinue.java ▫p184-185 Ex: (p185) Find the smallest factor other than 1 for an integer n ▫You can use break for this: int factor=2; while(factor <= n) { if(n%factor == 0) break; factor++; } System.out.println(“The smallest factor other than 1 for “+n+” is “+factor);

43 Loops are important! Loops are used almost everywhere in programming! They are very important! I will give you tons of loop work in this class! ▫They will be used continuously afterward! Good luck!


Download ppt "Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles."

Similar presentations


Ads by Google