Week04
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Week04

on

  • 381 views

 

Statistics

Views

Total Views
381
Views on SlideShare
185
Embed Views
196

Actions

Likes
0
Downloads
10
Comments
0

1 Embed 196

http://mycsa.edu.au 196

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Week04 Presentation Transcript

  • 1. Week 4Loops
  • 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNINGThis material has been copied and communicated to you by oron behalf of Bond University pursuant to Part VB of theCopyright Act 1968 (the Act).The material in this communication may be subject to copyrightunder the Act. Any further copying or communication of thismaterial by you may be the subject of copyright protectionunder the Act.
  • 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3Repetition Statements• Repetition statements allow us to execute astatement multiple times• Often they are referred to as loops• Like conditional statements, they are controlled byboolean expressions• Java has three kinds of repetition statements: the while loop the do loop the for loop• The programmer should choose the right kind ofloop for the situation
  • 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4The while Statement• A while statement has the following syntax:while ( condition )statement;• If the condition is true, the statement isexecuted• Then the condition is evaluated again, and if it isstill true, the statement is executed again until thecondition becomes false• We use while loops when we cannot predict thenumber of times the loop will execute, e.g.•testing for bad user input•processing input records from a database
  • 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5Logic of a while Loopstatementtruefalseconditionevaluated
  • 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6The while Statement• An example of a while statement:int count = 1;while (count <= 5){System.out.println (count);count++;}• If the condition of a while loop is false initially,the statement is never executed• Therefore, the body of a while loop will executezero or more times
  • 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7How Often is the Body Run?• If the condition of a while loop is false initially,the statement is never executed• Therefore, the body of a while loop will executezero or more times• Once inside the body of the while loop, if nothingis done to modify the loop condition, we get aninfinite loop
  • 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8Infinite Loops• The body of a while loop eventually must makethe condition false• If not, it is called an infinite loop, which willexecute until the user interrupts the program• This is a common logical error• You should always double check the logic of aprogram to ensure that your loops will terminatenormally
  • 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9Infinite Loops• An example of an infinite loop:int count = 1;while (count <= 25){System.out.println (count);count = count - 1;}• This loop will continue executing until interrupted(Control-C) or until an underflow error occurs
  • 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10Running Sum, Count, Max, Min• In the Average program from Week 3s lab, we sawhow to keep a running count of the numbersentered by the user• We also kept a running sum of the numbersentered. This allowed us to calculate the averageof the numbers entered• The same idea can be used to calculate themaximum and minimum of the numbers entered;see Average2 from Week 4s lab• We must start the running maximum small so thatthe first number entered overwrites it• The same thing goes for the running minimum• Can you think of numbers which will break it?
  • 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11Nested Loops• Similar to nested if statements, loops can benested as well• That is, the body of a loop can contain anotherloop• For each iteration of the outer loop, the inner loopiterates completely• See PalindromeTester.java (page 235)
  • 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12Nested Loops• How many times will the string "Here" be printed?count1 = 1;while (count1 <= 10){count2 = 1;while (count2 <= 20){System.out.println ("Here");count2++;}count1++;}10 * 20 = 200
  • 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13The do Statement• A do statement has the following syntax:do{statement;}while ( condition )• The statement is executed once initially, and thenthe condition is evaluated• The statement is executed repeatedly until thecondition becomes false
  • 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14Logic of a do Looptrueconditionevaluatedstatementfalse
  • 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15The do Statement• An example of a do loop:• The body of a do loop executes at least once• See ReverseNumber.java (page 244)int count = 0;do{count++;System.out.println (count);} while (count < 5);
  • 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16Comparing while and dostatementtruefalseconditionevaluatedThe while LooptrueconditionevaluatedstatementfalseThe do Loop
  • 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17When to Use Do or While?• Use a do loop when the loop body must beexecuted at least once, e.g• Get the users input before we can tell that it isinvalid• Use either of these two loop forms when thenumber of times the loop must execute isunknown• When the number of iterations through the loop isknown in advance, you should use a for loop
  • 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18Looping N times, or over a range• In many situations, you know in advance how many timesthat you want to loop, e.g.•Do something for every day in this month• Alternatively, you need to loop over a range of values, e.g.•Do some calculations for each possible age in the range 0to 100 years old• In these situations, we use the for loop.• The for loop:•has a loop counter, holding one value in the range eachtime through the loop, and•increments the loop counter for you
  • 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19The for Statement• A for statement has the following syntax:for ( initialization ; condition ; increment )statement;The initializationis executed oncebefore the loop beginsThe statement isexecuted until thecondition becomes falseThe increment portion isexecuted at the end of eachiteration
  • 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20Logic of a for loopstatementtrueconditionevaluatedfalseincrementinitialization
  • 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21The for Statement• A for loop is functionally equivalent to thefollowing while loop structure:initialization;while ( condition ){statement;increment;}
  • 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22The for Statement• An example of a for loop:for (int count=1; count <= 5; count++)System.out.println (count);• In this example, count goes from 1 to 5 in steps of 1,and the count value is printed out• The initialization section can be used to declare avariable• Like a while loop, the condition of a for loop is testedprior to executing the loop body• Therefore, the body of a for loop will execute zero ormore times
  • 23. © 2004 Pearson Addison-Wesley. All rights reserved 5-23The for Statement• The increment section can perform any calculation• What does the above loop print out?• A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance• See Multiples.java (page 248)• See Stars.java (page 250)for (int num=100; num > 0; num -= 5)System.out.println (num);
  • 24. © 2004 Pearson Addison-Wesley. All rights reserved 5-24Nested For Loops• Just like other control structures in Java, for loopscan be nested inside other loops or if statements• What does this code do?for (rows=1; rows<=10; rows++){for (cols=1; cols<=20; cols++)System.out.print(“*”);System.out.println;}• Try it in the Java debugger and see
  • 25. © 2004 Pearson Addison-Wesley. All rights reserved 5-25Nested For Loops• Its important here to remember to treat the outsideloop counter as constant• Watch what happens when we use the outsideloop counter as a constant in the inner loop:• What does this code do?for (rows=1; rows<=10; rows++){for (cols=1; cols<=rows; cols++)System.out.print(“*”);System.out.println;}• Try it in the Java debugger and see
  • 26. © 2004 Pearson Addison-Wesley. All rights reserved 5-26Nested For Loopsfor (rows=1; rows<=10; rows++){for (cols=1; cols<=rows; cols++)System.out.print(“*”);System.out.println;}• Note that the inner loop uses the value of the rowsvariable to determine the number of stars to print
  • 27. © 2004 Pearson Addison-Wesley. All rights reserved 5-27Class Exercise• Write a program to print out a multiplication table,with columns 1 2 3 4 5 6 7 8 9 10, and rows 1 .. 10, e.g.x 1 2 3 4 5 6 7 81 1 2 3 4 5 6 7 82 2 4 6 8 10 12 14 163 3 6 9 12 15 18 21 24• Hint: we need 2 variables to multiply together. Whatcan we name them?• Hint: do we need loops? How many loops?• Hint: when do we print a newline?• Suggestion: dont print the blue numbers to start with
  • 28. © 2004 Pearson Addison-Wesley. All rights reserved 5-28Class Exercise• Modify the program to print out the row andcolumn labels. Include horizontal and vertical barsif possible.• Modify the program to ask the user for the upperbound for the table size, instead of using 10.• Modify the program to ensure that the users inputis between 5 and 15.
  • 29. © 2004 Pearson Addison-Wesley. All rights reserved 5-29Program Development Tips• Think about the problem BEFORE you start writingcode!!• What variables will be needed, how will theychange over time?• What control structures do you think youll need:IF, WHILE, DO, FOR, and where?• Develop your program one bit at a time. Test whatyou have written before adding new stuff.• Use the debugger to show you what the code isactually doing. Remember: a computer DWIS notDWIW.
  • 30. © 2004 Pearson Addison-Wesley. All rights reserved 5-30Program Development Tips• Use a top-down approach, e.g. Get the input from the user, make sure its between 5 and10 Print out the heading (need a loop here, probably a FORloop as we know the table size) We need a loop for each line, again a FOR loop FOR each line• We need another variable to be the column variable, andwere going to need an inner loop now• Do the multiplication inside the inner loop and print out theresult• At the end of the line, i.e. when the inner loop has finished,print out the newline• Alternatively, if you know the code to write to do aspecific thing, then do it (bottom-up).• You will usually do a bit top-down and a bitbottom-up.
  • 31. © 2004 Pearson Addison-Wesley. All rights reserved 5-31Break and Continue• Inside a loop body, the break command instantlyexits the loop and starts the code following theloop.• Inside a loop body, the continue commandinstantly takes you to the top of the loop. Anycondition at the top of the loop is evaluated.• The textbook suggests you should avoid these twocommands. I disagree.• Example: ask user for number between 1 and 100.If they enter something else, tell them that they arestupid and ask again.
  • 32. © 2004 Pearson Addison-Wesley. All rights reserved 5-32The Break Commandint value;while (true){System.out.print(“Enter num 1-100: “);value=scan.nextInt();if ((value>=1) && (value<=100)break;System.out.println(“Idiot! Try again”);}• Note the loop looks like an infinite loop. But theloop breaks when the user gets it right.• Try doing the same with a normal WHILE or DOloop