Download presentation
Presentation is loading. Please wait.
Published byAlaina Hicks Modified over 9 years ago
1
11 Chapter 4 LOOPS AND FILES
2
22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable means to decrease its value by one. To increment a variable a, we could write either of the following statements: a = a + 1; a += 1; We could decrement the variable b using one of the following statements: b = b – 1; b – = 1;
3
33 THE INCREMENT AND DECREMENT OPERATORS These operations are so common in computer applications that Java offers special operators that can be used to specify these operations more concisely. The increment operator is ++, read plus plus, and the decrement operator is – –, read minus minus. Both operators are unary operators used to increase/decrease the value of the variable that is their operand by one.
4
44 THE INCREMENT AND DECREMENT OPERATORS So, instead of writing either of the following to increment the value in the variable a: a = a + 1; a += 1; We could write: a++;
5
55 THE INCREMENT AND DECREMENT OPERATORS Instead of writing either of the following to decrement the value in the variable b: b = b – 1; b – = 1; We could write: b – – ;
6
66 THE INCREMENT AND DECREMENT OPERATORS The operand of the increment or decrement operator must have an lvalue - it must correspond to a location in memory whose contents may be changed.
7
77 THE INCREMENT AND DECREMENT OPERATORS Example: The second statement of the segment below increments the variable named a. After this statement is executed, a contains the value 5. int a = 4; a++; This statement increases the value in a by 1. It is equivalent to a = a + 1.
8
88 THE INCREMENT AND DECREMENT OPERATORS Example: The statement below is erroneous. 4 does not have an lvalue. We cannot write 4 = 4 + 1; 4++; This is an error! You cannot increment a literal. 4 does not correspond to a location in memory with contents that may be changed.
9
99 THE INCREMENT AND DECREMENT OPERATORS Example: The second statement of the segment below is erroneous. The expression, b * c, has a value, but it does not have an lvalue. We cannot write b * c = b * c – 1; int b = 3, c = 6; (b * c) – – ; This is an error! b * c, cannot be on the left side of an assignment operator. It does not correspond to a location in memory with contents that may be changed.
10
10 THE INCREMENT AND DECREMENT OPERATORS The increment and decrement operators can be used in the postfix mode, which means the operator appears after the variable. When the operator is used in the postfix mode it means that the variable is incremented/decremented after it is used in the expression. The increment and decrement operators can be used in the prefix mode, which means the operator appears before the variable. When the operator is used in the prefix mode it means that the variable is incremented/decremented before it is used in the expression.
11
11 THE INCREMENT AND DECREMENT OPERATORS If you use the increment and decrement operators in simple statements that perform only the increment and decrement operation it does not matter if you use the prefix or the postfix mode of the operators. Example: int x = 5, y = 5; x++;// All this statement does is increment x ++y;// All this statement does is increment y System.out.println(x);// 6 is displayed on a line on the computer screen System.out.println(y);// 6 is displayed on a line on the computer screen
12
12 THE INCREMENT AND DECREMENT OPERATORS If you use the increment and decrement operators in more complex expressions, the use of the prefix or postfix mode is significant.
13
13 THE INCREMENT AND DECREMENT OPERATORS Example: When the first println statement of the segment below is executed, x is incremented and then its value (6) is displayed. In the next statement y is displayed (5) and then incremented. When the assignment statement is executed both x and y have the value 6, so z is assigned 12. int x, y, z; x = y = 5; System.out.println(++x);// 6 is displayed System.out.println(y++);// 5 is displayed z = x + y; System.out.println(z); // 12 is displayed
14
14 THE INCREMENT AND DECREMENT OPERATORS Example: In the segment below, y (3) is multiplied by 10 to get the value 30, then y is decremented to 2, 30 is added to x (2) to get the value 32, which is assigned to z. int x = 2, y = 3, z = 4; z = x + y – – * 10; System.out.println(z);// 32 is displayed
15
15 THE INCREMENT AND DECREMENT OPERATORS Example: In the segment below, y is decremented to 2, this value is multiplied by 10 to get the value 20, 20 is added to x (2) to get the value 22, which is assigned to z. int x = 2, y = 3, z = 4; z = x + – – y * 10; System.out.println(z);// 22 is displayed
16
16 THE INCREMENT AND DECREMENT OPERATORS The statement: z = x + – – y * 10; Could be written more clearly as: – – y;// y – – could be used in this case equivalently z = x + y * 10;
17
17 LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds of loops: the while loop, the do - while loop, and the for loop.
18
18 THE while LOOP The while loop/statement has the form: while (Boolean expression) { statement(s); } The while(Boolean expression) is the loop header. It consists of the key word while and a parenthesized Boolean expression, often called the loop continuation expression. The body of the loop follows the header. The body of the loop is the statement or block of statements that are to be repeated.
19
19 THE while LOOP while (Boolean expression) { statement(s); } When execution reaches a while statement, the parenthesized loop continuation expression is evaluated, if the expression is true the statement(s) that make up the body are executed and then execution returns to the evaluation of the continuation expression. This process is repeated until the loop continuation expression is evaluated and has the value false. When this happens, execution continues with the statement following the while statement.
20
20 THE while LOOP while (Boolean expression) { statement(s); } One repetition of the body of a loop is called an iteration. The while loop is a pretest loop. The continuation expression is tested before the body of the loop is executed. If the continuation expression is false on the initial test, the body of the loop is never executed, i.e. it never iterates.
21
21 THE while LOOP Flowchart Representation of a while Loop
22
22 THE while LOOP The loop continuation expression must eventually become false or an infinite loop results. An infinite loop is a loop that does not have a way to terminate normally.
23
23 THE while LOOP while (Boolean expression) { statement(s); } The braces are not necessary if the body of the loop is a single statement. Notice that there is no semicolon after the loop continuation expression. A complete while statement includes a loop header and the loop body. Don’t put a semicolon here. The loop header is only the beginning of the while statement.
24
24 THE while LOOP while (Boolean expression) { statement(s); } It is considered good programming style to begin the body of the loop on the line below the continuation expression and indent the statement(s) that make up the body of the loop one level from the key word while.
25
25 THE while LOOP /** Code Listing 4-3 from the text. This program demonstrates the while loop. */ public class WhileLoop { public static void main(String [ ] args) { int number = 1; while (number <= 5) { System.out.println("Hello"); number++; } System.out.println("That's all!"); }
26
26 THE while LOOP ***See the program WhileLoop.java on the disk that came with the text
27
27 THE while LOOP The loop in WhileLoop.java is a particular kind of loop known as a count-controlled loop. A count-controlled loop is a loop that iterates a specific number of times. This type of loop uses a control variable, usually called a counter, to control the number of times the loop iterates. When you construct a count-controlled loop you must be sure to: 1. Give the counter a starting value. 2. Compare the counter to a maximum (or minimum) value in the loop continuation expression. When the counter reaches this value the loop terminates. 3. Update the value of counter.
28
28 THE while LOOP In the program WhileLoop.java the variable named number is the counter used to control the number of iterations of the loop. /** Code Listing 4-3 from the text. This program demonstrates the while loop. */ public class WhileLoop { public static void main(String [ ] args) { int number = 1; while (number <= 5) { System.out.println("Hello"); number++; } System.out.println("That's all!"); } 1.We are giving the counter, named number, a starting value, count, of 1. 2. We are comparing the value in the counter to the upperbound on the count, in this case it is 5. 3. Each iteration of the loop we are updating the value in the counter with this statement.
29
29 USING THE while LOOP FOR INPUT VALIDATION According to the text, "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, and not assume the user has followed these instructions." When the user enters invalid data the program should: 1. Display a descriptive error message 2. Ask for another input 3. Read the user's new input An input validation loop iterates until the user enters valid data.
30
30 USING THE while LOOP FOR INPUT VALIDATION The logic for the while loop version of an input validation loop is shown in Figure 4-4 of the text.
31
31 USING THE while LOOP FOR INPUT VALIDATION *** See the program GetValidHoursWorked.java on webct
32
32 USING THE while LOOP FOR INPUT VALIDATION The read operation that takes place just before the loop is called a priming read. It is used to get the first value from the user for the initial loop test. Since it is outside the loop, it is not repeated. If a valid value is entered the first time, the loop never iterates. Notice that there is another read operation inside the loop. As long as the user continues to enter invalid data we are displaying an error message and then reprompting and rereading.
33
33 USING THE while LOOP FOR INPUT VALIDATION The loop in our example GetValidHoursWorked.java is not a count-controlled loop. We don’t know home many times that the loop needs to iterate. This loop is in another category of loops known as a conditional loop. A conditional loop iterates as long as some condition exists. In our case, it iterates as long as the number of hours worked entered is outside the range 0 through 168 inclusive.
34
34 THE do-while LOOP The do - while loop/statement has the form: do { statement(s); } while (Boolean expression); The key word do is followed by the body of the loop, the key word while, the parenthesized loop continuation expression, and a semicolon.
35
35 THE do-while LOOP do { statement(s); } while (Boolean expression); When execution reaches a do - while statement, the statement or block of statements that make up the body of the loop are executed, and then the loop continuation expression is evaluated. If this expression evaluates to true, execution continues at the first statement of the loop body. This process is repeated until the loop continuation expression is evaluated and has the value false. When the continuation expression evaluates to false, execution continues with the first statement following the do - while statement.
36
36 THE do-while LOOP do { statement(s); } while (Boolean expression); The do - while loop is a posttest loop. The loop continuation expression is evaluated at the end of an iteration of the loop body. The do - while loop iterates at least once.
37
37 THE do-while LOOP Flowchart Representation of a do - while Loop
38
38 THE do-while LOOP do { statement(s); } while (Boolean expression); There must be a semicolon after the loop continuation expression of a do - while statement. The braces are not necessary if the body of the loop is a single statement. Notice there is a semicolon here, because this is the end of the do - while statement.
39
39 THE do-while LOOP do { statement(s); } while (Boolean expression); It is considered good programming style to begin the body of the loop on the line below the key word do and indent the statements that make up the loop body one level from the word do.
40
40 THE do-while LOOP *** See the program ReadIncreasing.java from webct The loop in ReadIncreasing.java is another conditional loop. It continues to iterate as long as the most recent number entered is larger than the previous number(s) entered.
41
41 THE do-while LOOP The do - while loop is ideal for situations where we want the body of the loop to iterate at least once.
42
42 THE for LOOP The for loop/statement has the form: for (initialization; Boolean expression; update) { statement(s); } The for(initialization; Boolean expression; update) is the loop header. It consists of the key word for followed by three parenthesized expressions separated by semicolons. Notice there is not a semicolon after the third expression, the update.
43
43 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } The first part is the initialization. It is typically used to initialize a counter, accumulator, or other variable that must be given a starting value. The initialization is only executed before the first iteration of the loop.
44
44 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } The second expression is the loop continuation expression. This is a Boolean expression that gets evaluated before every iteration of the loop to determine if the loop should iterate.
45
45 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } The third expression is the update. The update is executed at the end of each iteration before execution returns to the continuation expression. Typically, this is a statement that updates the value of a variable that is used to control the loop.
46
46 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } The body of the loop follows the header. The body of the loop is the statement or block of statements that are to be repeated. This is the body of the loop.
47
47 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } When execution reaches a for statement, the initialization is executed. The loop continuation expression is evaluated, if this expression is true, the statement(s) that make up the body of the loop are executed and then the update is executed before returning to the evaluation of the loop continuation expression. The process described in the previous bullet is repeated until the loop continuation expression is evaluated and has the value false. When this occurs, execution continues with the statement following the for statement.
48
48 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } The for loop is a pretest loop. If the continuation expression evaluates to false on the initial test, the body of the loop does not iterate (the statements in the loop body and the update are never executed).
49
49 THE for LOOP Flowchart Representation of a for Loop
50
50 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } Notice that there is no semicolon after the loop header. A complete for loop/statement includes the loop body. The braces are not necessary if the body of the loop is a single statement. Don’t put a semicolon here. The loop header is only the beginning of the for statement.
51
51 THE for LOOP for (initialization; Boolean expression; update) { statement(s); } It is considered good programming style to begin the body of the loop on the line below the parenthesized expressions and indent the statements that make up the body of the loop one level from the key word for.
52
52 THE for LOOP *** See the program DisplayEvens.java on webct
53
53 THE for LOOP Problem: Write the pseudocode for a program that gets 50 grades from the user and calculates and displays the average of the grades on the computer screen.
54
54 THE for LOOP *** See the program AvgOf50Grades.java on webct
55
55 THE for LOOP The program AvgOf50Grades.java uses another kind of variable called an accumulator.
56
56 THE for LOOP An accumulator is a variable that is used to store a running total that “accumulates” over the iterations of the loop. When you use an accumulator you must be sure to give it a starting value before the first iteration of the loop.
57
57 THE for LOOP In AvgOf50Grades.java the accumulator total is assigned the value 0 before the first iteration of the loop. During the first iteration of the loop, the first grade is received from the user and its value is stored in grade, this value is added to the current value of total (0). During the second iteration, the second grade is received from the user, its value is stored in grade, replacing the first grade. This grade is added to total before it is replaced by the third grade on the next iteration. After two iterations total contains the sum of the first two grades. After fifty iterations we will have accumulated the sum of the fifty grades in total.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.