Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Introduction to Control Statements Fundamentals of Java.

Similar presentations


Presentation on theme: "Chapter 4 Introduction to Control Statements Fundamentals of Java."— Presentation transcript:

1 Chapter 4 Introduction to Control Statements Fundamentals of Java

2 Warm-up Write a for-loop that repeats 10 times and prints out every number from 1 to 10 Fundamentals of Java 2

3 3 Objectives Use the increment and decrement operators. Use standard math methods. Use if and if-else statements to make choices.

4 Fundamentals of Java 4 Objectives (cont.) Use while and for loops to repeat a process. Construct appropriate conditions for control statements using relational operators. Detect and correct common loop errors.

5 Fundamentals of Java 5 Vocabulary Control statements Counter Count-controlled loop Entry-controlled loop Flowchart Infinite loop

6 Fundamentals of Java 6 Vocabulary (cont.) Iteration Off-by-one error Overloading Sentinel Task-controlled loop

7 Fundamentals of Java 7 Additional Operators Extended assignment operators – Assignment operator combined with arithmetic and concatenation operators

8 Fundamentals of Java 8 Additional Operators (cont.) Increment operator: ++ – Increase value of operand by 1 Decrement operator: -- – Decrease value of operand by 1

9 Fundamentals of Java 9 Standard Classes and Methods: The Math Class Table 4-1: Seven methods in the Math class

10 Fundamentals of Java 10 Standard Classes and Methods: The Math Class (cont.) The two abs() methods are overloaded. – Overloaded: Multiple methods in the same class with the same name Using sqrt() method example:

11 Fundamentals of Java 11 Standard Classes and Methods: The Math Class (cont.) Math class methods example:

12 Fundamentals of Java 12 Standard Classes and Methods: The Random Class Random number generator: Returns numbers chosen at random from a pre- designated interval Table 4-2: Methods in the Random class

13 Fundamentals of Java 13 A Visit to the Farm

14 Fundamentals of Java 14 The if and if-else Statements Principal forms:

15 Fundamentals of Java 15 The if and if-else Statements (cont.) Additional forms:

16 Fundamentals of Java 16 The if and if-else Statements (cont.) Better to over-use braces than under-use them – Can help to eliminate logic errors Condition of an if statement must be a Boolean expression – Evaluates to true or false A flowchart can be used to illustrate the behavior of if-else statements.

17 Fundamentals of Java 17 The if and if-else Statements (cont.) Figure 4-1: Flowcharts for the if and if-else statements

18 Fundamentals of Java 18 The if and if-else Statements (cont.) Examples of if statements:

19 Fundamentals of Java 19 The if and if-else Statements (cont.) Table 4-3: Relational operators

20 Fundamentals of Java 20 The if and if-else Statements (cont.): Checking Input for Validity Example 4.1: Computes the area of a circle if the radius >= 0 or otherwise displays an error message

21 Fundamentals of Java 21 The while Statement Provides a looping mechanism – Executes statements repeatedly for as long as some condition remains true

22 Fundamentals of Java 22 The while Statement (cont.) Figure 4-2: Flowchart for a while statement

23 Fundamentals of Java 23 The while Statement (cont.) Example: Counter-controlled loop: – cntr is the counter – Loop repeats a determined number of times

24 Fundamentals of Java 24 The while Statement (cont.) Tracing: Track value of variables through each iteration of the loop Table 4-4: Trace of how variables change on each iteration through a loop

25 Fundamentals of Java 25 The while Statement (cont.) Counting backward:

26 Fundamentals of Java 26 The while Statement (cont.) Task-controlled loop: Continues to execute until some task is accomplished

27 Fundamentals of Java 27 The while Statement (cont.) Common structure of a while loop:

28 Fundamentals of Java 28 The while Statement (cont.) Example 4.2: Compute and display the factorial of n

29 Fundamentals of Java 29 The for statement Combines counter initialization, condition test, and update into a single expression Easy to create count-controlled loops

30 Fundamentals of Java 30 The for statement (cont.) Example:

31 Fundamentals of Java 31 The for statement (cont.) Count-controlled input:

32 Fundamentals of Java 32 The for statement (cont.) Better to declare the loop control variable within the loop header – Only visible within the loop – Variable name can be reused later in other loops

33 Fundamentals of Java 33 The for statement (cont.) Both for loops and while loops are entry- controlled loops. – Condition tested at top of loop on each pass Choosing a for loop versus a while loop is often a matter of style. – for loop advantages: Can declare loop control variable in header Initialization, condition, and update in one line of code

34 Fundamentals of Java 34 Nested Control Statements and the break Statement Control statements may be nested.

35 Fundamentals of Java 35 Nested Control Statements and the break Statement (cont.) break statement: Prematurely end a loop

36 Fundamentals of Java 36 Nested Control Statements and the break Statement (cont.) Sentinel-controlled input: Continue a loop until a sentinel variable has a specific value

37 Fundamentals of Java 37 Using Loops with Text Files Advantages of using text files versus input from a human user: – Data sets can be much larger. – Data input quickly, with less chance of error. – Data can be used repeatedly. Data files can be created by hand in a text editor or generated by a program.

38 Fundamentals of Java 38 Using Loops with Text Files (cont.) Text file format: – If data is numerical, numbers must be separated by white space. – Must be an end-of-file character Used by program to determine whether it is done reading data When an error occurs at run-time, the JVM throws an exception. – IOException thrown if error occurs during file operations

39 Fundamentals of Java 39 Using Loops with Text Files (cont.) Example 4.3: Computes and displays the average of a file of floating-point numbers

40 Fundamentals of Java 40 Using Loops with Text Files (cont.) Example 4.4: Inputs a text file of integers and writes these to an output file without the zeroes

41 Fundamentals of Java 41 Errors in Loops May occur in initializing statements, terminating conditions, body statements, or update statements Initialization error: Failure to initialize or initializes to incorrect value Off-by-one error: Loop iterates one too many or one too few times

42 Fundamentals of Java 42 Errors in Loops (cont.) Infinite loop: Error in the terminating condition – Loop never terminates Errors in loop body affect whether the loop completes its task correctly or at all. Update error: Update statements in wrong place may affect calculations – Failing to update at all results in an infinite loop.

43 Fundamentals of Java 43 Errors in Loops (cont.) Effects of limited floating-point precision: When using floating-point variables as loop control variables, you must understand that not all values can be represented. – Better not to use == or != in condition statement under these conditions

44 Fundamentals of Java 44 Errors in Loops (cont.) Debugging loops: – If an error is suspected, make sure that: Variables are initialized before entering the loop The terminating condition stops the iterations when the test variables have reached the intended limit The statements in the body are correct

45 Fundamentals of Java 45 Errors in Loops (cont.) Debugging loops (cont.): – If an error is suspected, make sure that: The update statements are positioned correctly and modify the test variables so that they eventually pass the limits tested in the terminating condition

46 Fundamentals of Java 46 Design, Testing, and Debugging Hints Most errors involving selection statements and loops are not syntax errors. The presence or absence of the {} symbols can seriously affect the logic of a selection statement or loop. When testing programs that use if or if- else statements, use test data that forces the program to exercise all logical branches.

47 Fundamentals of Java 47 Design, Testing, and Debugging Hints (cont.) Use an if-else statement rather than two if statements when the alternative courses of action are mutually exclusive. When testing a loop, be sure to use limit values as well as typical values. Be sure to check entry conditions and exit conditions for each loop.

48 Fundamentals of Java 48 Design, Testing, and Debugging Hints (cont.) For a loop with errors, use debugging output statements to verify the values of the control variable on each pass through the loop. Text files are convenient to use when the data set is large, when the same data set must be used repeatedly with different programs, and when these data must be saved permanently.

49 Fundamentals of Java 49 Summary Java has operators for extended assignment and for increment and decrement. The Math class provides several useful methods, such as sqrt and abs. The Random class allows you to generate random integers and floating-point numbers. if and if-else statements are used to make one-way and two-way decisions.

50 Fundamentals of Java 50 Summary (cont.) The comparison operators, such as ==, =, return Boolean values that can serve as conditions for control statements. The while loop allows the program to run a set of statements repeatedly until a condition becomes false. The for loop is a more concise version of the while loop.

51 Fundamentals of Java 51 Summary (cont.) Other control statements, such as an if statement, can be nested within loops. A break statement can be used with an if statement to terminate a loop early. Many kinds of logic errors can occur in loops. – Off-by-one error – Infinite loop

52 While Loops Fundamentals of Java 52 A while loop has a boolean test and a body containing statements, like this: int count = 0; while (count < 100) { // test: boolean test within (..) System.out.println("count:" + count); // body: statements within {..} count = count + 1; } System.out.println("all done!");

53 While Loops An if-statement looks at the test one time and then maybe executes the body once. The while-loop extends this idea, executing the body again and again, checking the test each time. The while-loop follows these steps: 1. Check if the test is true or false. If false, the loop "exits" and does not execute the body. If the test is true, continue with step 2. 2. Execute the body statements, starting at the top and proceeding down through them all. 3. Go back to step 1 and check the test again. If it is true, run the body again. Each time the body finishes, "loop around" and check the test again. Each run of the body is called an "iteration" of the loop. Eventually the test is false, the loop exits, and the program continues with the line after the while-loop Fundamentals of Java 53

54 How To Write a While Loop To write a while-loop, we think about three parts... 1. Test 2. Work 3. increment Fundamentals of Java 54

55 TEST test -- a boolean test of what should be true before each iteration. Or put another way, the test is the "green light" condition that says that each iteration can go ahead. Eventually, the test should become false and the loop can exit. Think about the precondition that describes the state before each iteration runs -- how are things arranged, what is true? Fundamentals of Java 55

56 WORK work -- code in the body that does something for each iteration such as printing or drawing something. Some loops do not have any identifiable work in the body. In the above example, the work is the println() that prints something out for each iteration. Fundamentals of Java 56

57 Increment increment -- code in the body that advances things so we are closer to making the test false. At the end of the body, the code will loop around to the top of the body. Sometimes, some cleanup is required at the end of the body to set things up for the next iteration. In the above example, the line "count = count + 1;" accomplishes the increment. That can also be written as "count++;". Fundamentals of Java 57

58 While Loop Example Here's a while loop example that uses a loop to see how man times you can divide a number by 2: // Given a num, returns how many times can we divide it by 2 to get down to 1. int count2Div(int num) { int count = 0; // count how many divisions we've done while (num >= 1) { num = num / 2; count++; } return count; } Fundamentals of Java 58

59 Zero Loop Iterations Since the while-loop checks the test before every iteration, it is possible for the body to not run even once: int count = 100; while (count < 100) { // the test is false the very first time count = count + 1 // this line never runs } Fundamentals of Java 59

60 Infinite Loop The most famous sort of bug you can get with loops is an "infinite loop", where through some mis-arrangement, running the loop body fails to get any closer to making the test false. Typically, this comes down to some sort of logical disconnect between the body and the test. For example, suppose the body fails to make the count bigger by accident: int count = 0; while (count < 100) { System.out.println("count:" + count); count = count * 1; // OOPS, does not change count } Fundamentals of Java 60

61 Infinite Loops Suppose we forget to put in the count line entirely, so the loop just spins in place with count stuck at zero: int count = 0; while (count < 100) { System.out.println("count:" + count); // OOPS, forget to put in a line that changes count at all } Fundamentals of Java 61

62 Inifinite Loops In some cases, we want the code to run on and on without stopping. In that case, we might write an infinite loop on purpose by giving true as the test: while (true) { // deliberate infinite loop...... } Fundamentals of Java 62

63 While-break With the while-break, we have the power of a while loop, but now we can position the test anywhere we want instead of just at the top. In fact, a standard while loop of this form: while (test) { body } Is equivalent to a while-break loop where the break is positioned at the very top: while (true) { if (!(test)) { break; } body } Fundamentals of Java 63

64 For Loops The for-loop is a variant of the while-loop, specialized to deal with a particular looping problem. The for-loop is specialized for the case where we want to step a variable through a series of values. For example, the following for-loop steps the variable "i" through the values 0, 1, 2,... 99: for (int i=0; i<100; i++) { System.out.println("i:" + i); } Fundamentals of Java 64

65 For Loop Header The for-loop has four parts -- init, test, increment, and body -- separated by semi- colons (;) for ( init ; test ; increment ) { body } Fundamentals of Java 65

66 Init The init code runs once to set things up at the very start of the loop. Typically, this looks like "int i = 0", declaring a variable to use for the counting, and setting its start value. The variable exists only within the loop (down through the } of the body). Although we avoid single-letter variable names for general purpose storage, this use of "i" is standard in a for-loop like this. Indeed, this pattern is so standard that other programmers would likely be a little confused if you used a variable name other than "i" in a for-loop. The convention extends to using the names "j", and "k" for loop variables if "i" is already in use. Never use lowercase L "l", since it looks just like the digit one "1" in many fonts. Fundamentals of Java 66

67 2. Test The boolean test is evaluated. If it is true the loop body will execute (green light, just like a while-loop). Typically, the test is a boolean expression such as "i<100", showing what should be true for the loop to continue. Fundamentals of Java 67

68 3. Loop-body If the test was true, the body runs once. The body is a series of statements, just like in a while-loop. The loop body will very often make some use of the loop variable, such as "i" in this example. Fundamentals of Java 68

69 4. Increment Finally, the increment code executes just after the body, and then the program loops back to the test, (step 2). The increment advances the state of things in preparation for the next iteration. The increment code advances the state, and then the test (2) looks at the state. Eventually, we advance the state so far that the test is false and the loop exits. This is analogous to the "increment" idea in the while- loop. In the while-loop, the increment is just a conceptual goal, but in the for-loop, the increment has its own slot in the syntax. When writing a for-loop, we are less likely to forget to do the increment, since the syntax has an explicit slot for it. Fundamentals of Java 69

70 For Loop Examples /*Classic for-loop counting up from 0 to 99 0, 1, 2, 3,... 99 -init int i = 0 -test i<100 -increment i++ */ for (int i=0; i<100; i++) { System.out.println(i); } Fundamentals of Java 70

71 For Loop Examples /* For-loop to print the values 0, 2, 4, 6,.. 98 -increment by i+=2, instead of i++ (same as i = i + 2) */ for (int i=0; i<100; i+=2) { System.out.println(i); } Fundamentals of Java 71

72 For Loop Examples /* For-loop from 99 down to 0 99, 98, 97,... 0 -init i=99 - test i>=0 -increment i-- */ for (int i=99; i>=0; i--) { System.out.println(i); } Fundamentals of Java 72

73 For Loop Examples /* For-loop from 0 to 100 by 5's 0, 5, 10, 15,.. 100 -test i<=100 -increment i+=5 */ for (int i=0; i<=100; i+=5) { System.out.println(i); } Fundamentals of Java 73

74 For vs. While Loops The for-loop can actually be understood as equivalent to a while-loop version, like this: init while (test) { body increment } So for example, we could write the standard 0..99 loop like this, although for real code we would prefer the for-loop in this problem: int i = 0; while (i<100) { System.out.println(i); i++; } Fundamentals of Java 74

75 For vs. While Loops As a matter of style, if we are solving a series-of-values 0, 1, 2, 3,... 100 type problem, then the for-loop is preferable. If the looping problem does not fit into the series-of-values pattern, then the standard while-loop is best. Fundamentals of Java 75


Download ppt "Chapter 4 Introduction to Control Statements Fundamentals of Java."

Similar presentations


Ads by Google