Chapter 4 Loops and Files Contents 1. The Increment and Decrement Operators 2. The while Loop 3. Using the while Loop for Input Validation 4.
The do-while Loop 5. The for Loop 6. Running Totals and Sentinel Values 7. The break and continue Statements 2 Contents 9.
Deciding Which Loop to Use 10. Introduction to File Input and Output 11. The Random Class 3 1. The Increment and Decrement Operators Java provides a set of simple unary operators designed just for incrementing and decrementing variables.
Incrementing: increasing by one Decrementing: decreasing by one Increment operator ++ Decrement operator -- 4 1. The Increment and Decrement Operators Incrementing the variable number 1. ++number; Decrementing a variable 1. number--; Postfix and Prefix Modes Postfix mode The operator is placed after the variable.
number++; number--; Prefix mode The operator is placed before the variable. ++number; --number; 6 Postfix and Prefix Modes 7 The Difference between Postfix and Prefix Modes The difference is important if these operators ++ and -- are used in statements that do more than just increment or decrement. Example: number = 4; System.println(number++); This statement does two things: Calls println method to display But which the value of number happens first? 8 Increments number The Difference between Postfix and Prefix Modes Postfix mode causes the increment to happen after the value of the variable is used in the expression. The println method will display 4 and then 2.
number will be incremented to 5.println(number); 9 number = number + 1; The Difference between Postfix and Prefix Modes The prefix mode causes the increment to happen first.println(++number); number will be incremented to 5 and then The println method will display 5. number = 4; number = number + 1; System.println(number); 10 The Difference between Postfix and Prefix Modes int x = 1, y; y = x++; // Postfix increment 1.It assigns the value of x to the variable y 2.The variable x is incremented int x = 1, y; y = ++x; // Prefix increment 1.The variable x is incremented 11 2.It assigns the value of x to the variable y 2. The while Loop Problem: Write a program to ask a number n, and print “Hello” n times. Get n count = 1 count true <= n Print “Hello” Add 1 to count false 12 2.
The while Loop 13 2. The while Loop Test this boolean expression. If the boolean expression is true, while(count <= n) perform these statements.println(“Hello”); count++; } After executing the body of the loop, start over. The while Loop Logic of a while loop boolea n true Statement(s) Expressi on false 15 2.
The while Loop while(BooleanExpression) Loop header Statement; To repeat a block of statements while(BooleanExpression) Body of the loop { Statement1; Statement2; // Place as many statements here 16 // as necessary The while Loop Is a Pretest Loop The while loop is known as a pretest loop because it tests its expression before each iteration. int number = 10; The loop will never iterate if the boolean expression is false to start with.println(“Hello”); number++; } 17 Infinite Loops If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues to repeat until the program is interrupted. int number = 1; Each time the boolean expression is tested, while(number <= 5) number will contain the value 1.println(“Hello”); This is an infinite loop because it does not contain a } statement 18 that changes the value of the number variable.
Infinite Loops It's also possible to create an infinite loop by accidentally placing a semicolon after the first line of the while loop. int number = 1; This while loop will forever execute while(number <= 5); the null statement, which does nothing.println(“Hello”); number++; } 19 Don't Forget the Braces with a Block of Statements If you are using a block statement, don't forget to enclose all of the statements in a set of braces. If the braces are accidentally left out, the while statement executes only the very next statement. int number = 1; while(number <= 5) System.println(“Hello”); number++; The number++ statement is not in the body of the loop.
20 Programming Style and the while Loop Avoid this style of programming while(number <=5 ) { System.println(“Hello”); number++; } The programming style If there is only one statement repeated by the loop, it should appear on the line after the while statement and be indented one additional level. If the loop repeats a block, each line inside the braces should be indented. Using the while Loop for Input Validation The while loop can be used to create input routines that repeat until acceptable data is entered. Input validation is the process of inspecting data given to a program by the user and determining if it is valid.
A good program should give clear instructions about the kind of input that is acceptable. Do not assume that the user has followed those instructions. Using the while Loop for Input Validation The while loop is especially useful for validating input: If an invalid input is entered, a loop can require that the user re-enter it as many times as necessary. 23 Input Validation Logic Problem: Write a program to ask for a number in the range of 1 through 100.
Read the first value Is the true Display an Read another value error message. value invalid? false 24 Input Validation Logic input = JOptionPane.showInputDialog(“Enter a number “ + “ in the range of 1 through 100.parseInt(input); // Validate the input while(number < 1 || number > 100) { input=JoptionPane.showInputDialog(“Invalid input.“ + “Enter a number in the range of 1 through 100. The do-while Loop The do-while loop is a posttest loop, which means its boolean expression is tested after each iteration. The do-while loop's format do Statement; while(BooleanExpression); 26 4.
The do-while Loop The do-while loop's format do { Statement1; Statement2; // Place as many statements here as necessary }while(BooleanExpression); The do-while loop must be terminated with a semicolon. The do-while Loop The do-while loop is a posttest loop. The do-while loop always performs at least one iteration, even if the boolean expression is false to begin with. Statement(s) Boolea n true You should use the do-while expressi loop on when you want to make sure false the loop executes at least once.
The do-while Loop Problem: Write a program that averages a series of three test scores for a student. After the average is displayed, it asks the user if he or she wants to average another set of test scores. The program repeats as long as the user enter Y for yes. The programmer had no way of knowing the number of times the loop would iterate.
This is because the loop asks the user if he or she wants to repeat the process. 29 This type of loop is known as a user controlled 4. The do-while Loop Get three test scores Calculate and print the average test score Does the user true want to average another set ? false 30 4. The do-while Loop 31 4.
The do-while Loop 32 5. The for Loop In general, there are two categories of loops Conditional loops Executes as long as a particular condition exists. An input validation loop User controlled loop You have no way of knowing the number of times it will iterate. Count-controlled loops 33 Repeats a specific number of times 5.
The for Loop A count controlled loop must process three elements It must initialize a control variable to a starting value. It must test the control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates. It must update the control variable during each iteration.
This is usually done by incrementing the variable. 34 The Format of the for Loop for(Initialization; Test; Update) Statement; Loop header for(Initialization; Test; Update) { Loop body Statement1; Statement2; // Place as many statements here as necessary 35 } The Format of the for Loop ● A boolean expression that controls To initialize a control variable the execution of the loop ● to its starting value ● As long as this expression is true, ● The first action performed by the loop the body will repeat. ● It is only done once. ● The for loop is a pretest loop, so it evaluates the test expression before each iteration.
for(Initialization; Test; Update) { ● It executes at the end of each iteration. Statement1; ● Typically, this is a statement that increments the loop's control variable. Statement2; // Place as many statements here as necessary 36 } Logic of the for Loop Initialization Evaluate the true Loop body Update test expression false 37 Sequence of Events in the for Loop Here is an example of a simple for loop that prints “Hello” five times: int count; for(count = 1; count <= 5; count++) System.println(“Hello”); 38 Sequence of Events in the for Loop Step 1: Perform the initialization expression Step 2: Evaluation the test expression. If it is true, go to Step 3.
Otherwise, terminate the loop. Step 4: Perform the update expression, then go back to Step 2.println(“Hello”); Step 3: Execute the body of the loop. 39 Logic of the for Loop Assign 1 to count true println Increment count <= 5 statement count false 40 The Control Variable During the execution of the loop This variable takes on the values 1 through 5 When the test expression count <= 5 is false, the loop terminates. This variable keeps a count of the number of iterations, it is often called a counter variable.
The control variable can be used within the body of the loop. 41 The Control Variable Print the numbers 1 through 10: int number; for(number = 1; number <= 10; number++) System.print(number + “ “); This loop will produce the following output: 1 2 3 4 5 6 7 8 9 10 42 An Example Write a program to display a table showing the numbers 1 to 10 and their squares. 43 The for Loop Is a Pretest Loop The for loop tests its boolean expression before it performs an iteration pretest loop The following loop will never iterate int count; for(count = 11; count <= 10; count++) System.println(“Hello”); The control variable count is initialized to a value that makes the boolean expression false from the 44 Modifying the Control Variable in the Body of the for Loop Be careful not to place a statement that modifies the control variable in the body of the for loop. All modifications of the control variable should take place in the update expression.
int x; The output: for(x = 1; x < 10; x++) 1 3 { 5 7 System.println(number); 46 Declaring a Variable in the for Loop's Initialization Expression We can declare and initialize the control variable in the initialization expression of the for loop. int number; for(number = 1; number <= 10; number++) System.println(number); 47 Declaring a Variable in the for Loop's Initialization Expression When a variable is declared in the initialization expression of a for loop, the scope of the variable is limited to the loop. We can not access the variable outside the loop. 1 int number; 2 3 for(number = 1; number <= 5; number++) 4 5 System.println(number); number is now 6 System.println(number); ERROR ! Creating a User Controlled for Loop Sometimes we want the user to determine the maximum value of the control variable in a for loop.
The user determines the number of times the loop iterates. Write a program to display the numbers and their squares.