1 / 30

CMP-MX21: Lecture 5 Repetitions

CMP-MX21: Lecture 5 Repetitions. Steve Hordley. Overview. 1. Repetition using the do-while construct. 2. Repetition using the while construct. 3. Repetition using the for construct. A problem.

petula
Download Presentation

CMP-MX21: Lecture 5 Repetitions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CMP-MX21: Lecture 5Repetitions Steve Hordley

  2. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition using the for construct

  3. A problem The calculator program we developed in the previous lectures allows us to perform a single operation on two numbers. We would like to extend the program so that we can repeatedly perform operations on different numbers until the user decides to exit the program. Here, the problem we must address is how we can repeat a set of instructions two or more times. In this lecture we will look at three different JAVA constructs which help us solve this task.

  4. Designing a solution The basic elements of our program will not change very much: it is still performing the same basic operations, but multiple times. The modified program flow will be something like this: 1. Read two numbers from the keyboard 2. Read an “operation” from the keyboard 3. Apply the operation to the two numbers 4. Write out the result 5. Ask the user if they wish to continue 6. If answer is yes, goto step 1, otherwise stop

  5. Designing a solution The program flow can be visualised like this: ... statements; ... Evaluate expression expression false expression false statements;

  6. The do-while construct In JAVA, this program flow is achieved with the do-while construct: The do keyword denotes the start of a block of statements which might be repeated ... do{ statements; } while (expression); ... Statements after the do are performed When the while keyword is reached expression is evaluated If expression is true, the program returns to the first statement after the do Otherwise, execution continues after the while

  7. An example We can modify our calculator program to allow multiple operations using a do-while construct: ... do{ char theAnswer; // Read two numbers // Read an operator // Perform the operation and display the result System.out.println(“Another operation [y/n]?”); theAnswer = Keyboard.readChar(); } while (theAnswer == ‘y’); ...

  8. Some notes If we want to repeat only a single statement we don’t need the curly brackets: ... do statement; while (expression); ... Once we have more than a single statement between the do and the while, then curly brackets are required.

  9. Other repetition constructs The statements between the do and the while in the do-while construct are always executed at least once This is because the test for repetition (the while (expression)) comes after the block of statements Sometimes, we want to repeat a block of statements zero or more times depending on some condition. In this case we need the test before the statement block ...

  10. The while construct The while construct allows us to deal with this situation: When the while keyword is reached, expression is evaluated ... while (expression){ statements; } ... If expression is true, the statements between the curly brackets are executed and the program then returns to the while statement Otherwise, program execution continues after the closing bracket

  11. An example We can modify the calculator program so that it asks whether an operation is to be performed, each time, including the first: ... System.out.println(“Perform an operation [y/n]?”); theAnswer = Keyboard.readChar(); while (theAnswer == ‘y’) { // Read two numbers // Read an operator // Perform the operation and display the result } ...

  12. Some notes The while construct does not have a do associated with it The expression in both the while and the do-while construct must return a boolean value (true or false) In both constructs we should take care to choose the expression carefully (and write it correctly) otherwise problems may result

  13. Some common errors int i=1; while (i<4){ System.out.println(“i=1”+i); } The expression in this control loop will always evaluate to true. The result is that the program runs until the computer runs out of memory (or possibly forever): i = 1 i = 1 i = 1 … stack overflow…

  14. Some common errors int i=0; while (i>0){ System.out.println(“i=1”+i++); } The expression in this control loop will always evaluate to false so the statement in the loop will never be executed.

  15. The for construct The two loop constructs seen so far execute a set of statements some variable number of times. Sometimes we know in advance how many times we wish to execute a set of statements. JAVA provides a third construct: the for construct for these situations

  16. The for construct The for construct has the following general form: ... for (initialiser; condition; change){ statements; } ... An expression evaluated once, when the for is first encountered An expression evaluated before each cycle of the loop An expression evaluated at the end of each cycle of the loop

  17. The for construct initialiser The for has the following flow: Evaluate “condition” true execute loop statements false Evaluate “change” Next program statement

  18. An example ... for (int i=0; i<4; i++){ System.out.println(“i=“+i); } ... Outputs: i=0 i=1 i=2 i=3

  19. The for loop We can re-write any for loop as a while construct. E.g. the previous example: Initialisation is performed first int i=0; while (i<4){ System.out.println(“i=“+i); i++; } Condition is tested If condition is true, statements are performed Change expression is evaluated

  20. A second example Suppose we wish to calculate xn (x to the power of n). This can be done with the following for construct: for (r=1.0, i=1; i<=n; i++) r*=x; In this example, two initialisations are performed: r=1.0 and i=1. Multiple initialisations are separated by commas Any of the three parts of the for can have multiple expressions. These expressions must be separated by a comma.

  21. A second example The previous example could also be written like this: for (r=1.0, i=1; i<=n; i++, r*=x) ; In this case no statement is executed after the for. This is denoted by the semi-colon on its own.

  22. Some notes Any of the initialisation, condition, and change can be omitted from the for: r=1.0; i=1; for (; i<=n; i++, r*=x) ; Note that the semi-colon separating these three elements must remain: all for constructs have two semi-colons

  23. Some notes We can even leave all three elements out of the construct: for (;;) System.out.println(“This loops for ever”); Note, if there is no condition, it will be regarded as true So, if our for loop doesn’t contain a condition we need an alternative method to terminate the loop

  24. Terminating loops The break statement can be used to terminate a loop: for (i=1;;){ System.out.println(“i=”+i++); if (i==5) break; } The break statement causes program execution to jump to the first statement after the end of the loop The break statement can be used in a for, a do-while, or a while construct

  25. Terminating loops The continue statement causes program execution to jump to the beginning of the next loop: for (i=1;i<=5;i++){ if (i==3) continue; System.out.println(“i=”+i++); } i=1 i=2 i=4 i=5

  26. Some common errors for (i=1;i<=5;i++); System.out.println(“i=”+i++); i=6 Putting a semi-colon at the end of the for statement means that no statements are to be executed at each loop. The change expression and the condition are still evaluated until the condition becomes false Then the statements after the for will be executed

  27. Some common errors Like the do-while and while loops, we need to be careful with the condition statement in a for loop: for (i=10;i<=5;i--) System.out.println(“i=”+i++); Here the condition is false from the start so the loop never gets executed

  28. Some common errors for (i=10;i>5;i++) System.out.println(“i=”+i++); i=10 i=11 i=12 ... stack overflow error Here the condition is always true so the loop will continue until the system runs out of resources (or forever)

  29. A summary In this lecture we have introduced three JAVA constructs for repetition: the while, the do-while, and the for We have also seen how to exit from program loops using the break and continue statements

  30. A summary You should now be familiar with the meaning of the following words from the JAVA language: do, while, for, continue, break

More Related