repetition. control of flow sequence selection (if..else, switch…case) repetition

Click here to load reader

Post on 05-Jan-2016




0 download

Embed Size (px)


  • Repetition

  • Control of Flow


    SELECTION (if..else, switchcase)


  • Repetition- Used to repeat one or more programming statements.

    while Statementdo-while Statementfor Statement

  • The while StatementIn cooking, a recipe may tell us that, as there are lumps in a sauce we should stir it.

    In Java:While (there are lumps) give sauce a stir;

  • The while Statement

    Loop while loops continue to loop while some condition is true, and stops when the condition becomes falseThe condition is a Boolean expressionWill never execute if the condition is initially false

  • Syntax for the while Statementwhile ( ) { }

  • The while Statement

  • Control Flow of while

  • Infinite LoopsA loop that continues executing forever

    Can be caused by syntax or logic errors. For example: while (num < 0) //error--no braces System.out.print("Enter a value: "); num = input.nextInt();

    while (num < 0); //error-- semicolon System.out.print("Enter a value: "); num = input.nextInt();

    Causes an infinite loop.

  • while Loop Pitfall - 1Infinite Loops Both loops will not terminate because the boolean expressions will never become false.

  • while Loop Pitfall - 2Goal: Execute the loop body 10 times.

  • The do-while StatementAlternative form of the while statementExecutes at least onceIn do while loops the test condition comes at the end of the loop. So, the loop always iterates at least once.

    In Cooking Example:

    give sauce a stir;while (there are lumps)

  • Syntax for the do-while Statementdo {

    sum += number;number++;

    } while (sum

  • The do-while Statement

  • Control Flow of do-while

  • Pre-test vs. Post-test loopsUse a pre-test loop for something that may be done zero times

    Use a post-test for something that is always done at least once

  • Checklist for Repetition ControlWatch out for the off-by-one error (OBOE).Make sure the loop body contains a statement that will eventually cause the loop to terminate.Make sure the loop repeats exactly the correct number of times.

  • The for StatementReturning one last time to our cooking analogy, we might have instructions to eliminate lumpiness phrased in the formstir mixture for 100 strokesIn Java:int count;for (count = 0; count < 100; count++)give sauce a stir;

  • The for StatementLoop structure that executes a set of statements a fixed number of timesUses a loop control variable (lcv)The increment (++) or decrement (--) operators are used to change the value of the loop control variable

  • Syntax for the for Statementfor ( ; ; )

  • The for Statement

  • Control Flow of fortrue

  • The Nested-for StatementIf a first loop contains a second loop, we say the second is nested within the first.The first loop is often referred to as the outer loop and the second as the inner loop.Read page 152-153

  • Which Loop, When?for loop when you know how many times the loop will be executedwhile loop when you dont know how many times the loop will execute, including when the user is in controlwhile loop when you may not want the loop to execute even oncedo while when you want the loop to execute even once

  • Debugging TechniquesThe debugger included with many compilersVariable trace, which is a manual technique of list values of variables at the points of assignmentAdditional println() statements for displaying variable values at points of assignment"Commenting out" code to detect bugs through a process of elimination

  • Variable Traceint num1 = 0; int num2 = 0; while (num1 < 10) { if (num1 % 3 == 0) { num2 += num1; System.out.print(num2 + " "); } num1 += 1; }

  • Using println() to Debugint num1 = 0; int num2 = 0; System.out.println("num1 before while: " + num1);//debug while (num1 < 10) { System.out.println("num1 in while: " + num1);//debug if (num1 % 3 == 0) { num2 += num1; System.out.println("num2: " + num2);//debug System.out.print(num2 + " "); } num1 += 1; }

  • Using Comments to Debugint num1 = 0; int num2 = 0; while (num1 < 10) { //if (num1 % 3 == 0) { //num2 += num1; //System.out.print(num2 + " "); //} num1 += 1; }

  • HomeworkPage 138 # 1, 2, 3, 5Page 140 # 1Page 141 # 3, 4Page 143 # 1

    Refer to page 131 in the text.There are basically two types of terminating the loop:1. count-controlled and2. sentinel-controlled.Count-controlled loops terminate the execution of the loop after the loop body is executed for a fixed number of times.Sentinel-controlled loops terminate the execution of the loop after one of the designated values called a sentinel is encountered.Refer to page 132 in the text.An infinite loop can cause an application to stop responding or just "hang". Closing the application window (with JCreator Pro) will end the application so that the source of the infinite loop can be located and corrected.

    Errors that result in an overflow may generate unexpected results rather than "hanging" the application.Note: In theory, this while statement is an infinite loop, but in programming languages other than Java, this loop will eventually terminate because of an overflow error. An overflow error will occur if you attempt to assign a value larger than the maximum value the variable can hold. When an overflow error occurs, the execution of the program is terminated in almost all programming languages. With Java, however, an overflow will not cause the program termination. When an overflow occurs in Java, a value that represents infinity (IEEE 754 infinity, to be precise) is assigned to a variable and no abnormal termination of a program will happen. Also, in Java an overflow occurs only with float and double variables; no overflow will happen with int variables. When you try to assign a value larger than the maximum possible integer an int variable can hold, the value wraps around and becomes a negative value. Whether the loop terminates or not because of an overflow error, the logic of the loop is still an infinite loop, and we must watch out for it. When you write a loop, you must make sure that the boolean expression of the loop will eventually become false.Yes, you can write the desired loop as

    count = 1;while (count != 10 ) {...count++;}

    but this condition for stopping the count-controlled loop is dangerous. We already mentioned about the potential trap of an infinite loop.Refer to pages 131 and 132 in the text.The following is the routine presented earlier that inputs a persons age using the dowhile statement.

    do {age = inputBox.getInteger("Your Age (between 0 and 130):");if (age < 0 || age > 130) {"An invalid age was entered. " + "Please try again.");}} while (age < 0 || age > 130);

    This code is not as good as the version using the while statement it includes an if statement inside its loop body and the if test is repeating the same boolean expression of the dowhile. Since the loop body is executed repeatedly, it is important not to include any extraneous statements. Moreover, duplicating the testing conditions tends to make the loop statement harder to understand. For this example, we can avoid the extra test inside the loop body and implement the control flow a little more clearly by using a while statement. In general, the while statement is more frequently used than the dowhile statement.Refer to page 135 in the text.The component also can include a declaration of the control variable. We can do something like this:

    for (int i = 0; i < 10; i++)

    instead of

    int i;for (i = 0; i < 10; i++) Refer to pages 136 and 137 in the text.Refer to page 136 in the text.Refer to page 137 in the text.When using println() statements to debug a segment of code, it is usually most effective to place statements just after assignment changes the value of a variable.Refer to page 137 in the text.Comments can be used to comment out segments of code to determine through a process of elimination the location of any bugs.