Top Banner
Chapter 4 Introduction to Control Statements Fundamentals of Java
75

Chapter 4 Introduction to Control Statements Fundamentals of Java.

Jan 08, 2018

Download

Documents

Cameron Holland

3 Objectives Use the increment and decrement operators. Use standard math methods. Use if and if-else statements to make choices.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Chapter 4Introduction to Control

Statements

Fundamentals of Java

Page 2: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Warm-up

Write a for-loop that repeats 10 times and prints out every number from 1 to 10

Fundamentals of Java 2

Page 3: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 3

Objectives

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

choices.

Page 4: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 5: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 5

Vocabulary

Control statements Counter Count-controlled loop Entry-controlled loop Flowchart Infinite loop

Page 6: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 6

Vocabulary (cont.)

Iteration Off-by-one error Overloading Sentinel Task-controlled loop

Page 7: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 7

Additional Operators

Extended assignment operators– Assignment operator combined with

arithmetic and concatenation operators

Page 8: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 8

Additional Operators (cont.)

Increment operator: ++– Increase value of operand by 1

Decrement operator: --– Decrease value of operand by 1

Page 9: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 9

Standard Classes and Methods: The Math Class

Table 4-1: Seven methods in the Math class

Page 10: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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:

Page 11: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 11

Standard Classes and Methods: The Math Class (cont.)

Math class methods example:

Page 12: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 13: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 13

A Visit to the Farm

Page 14: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 14

The if and if-else Statements

Principal forms:

Page 15: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 15

The if and if-else Statements (cont.)

Additional forms:

Page 16: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 17: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 17

The if and if-else Statements (cont.)

Figure 4-1: Flowcharts for the if and if-else statements

Page 18: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 18

The if and if-else Statements (cont.)

Examples of if statements:

Page 19: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 19

The if and if-else Statements (cont.)

Table 4-3: Relational operators

Page 20: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 21: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 21

The while Statement

Provides a looping mechanism – Executes statements repeatedly for as long as

some condition remains true

Page 22: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 22

The while Statement (cont.)

Figure 4-2: Flowchart for a while statement

Page 23: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 23

The while Statement (cont.)

Example:

Counter-controlled loop: – cntr is the counter– Loop repeats a determined number of times

Page 24: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 25: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 25

The while Statement (cont.)

Counting backward:

Page 26: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 26

The while Statement (cont.)

Task-controlled loop: Continues to execute until some task is accomplished

Page 27: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 27

The while Statement (cont.)

Common structure of a while loop:

Page 28: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 28

The while Statement (cont.)

Example 4.2: Compute and display the factorial of n

Page 29: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 29

The for statement

Combines counter initialization, condition test, and update into a single expression

Easy to create count-controlled loops

Page 30: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 30

The for statement (cont.)

Example:

Page 31: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 31

The for statement (cont.)

Count-controlled input:

Page 32: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 33: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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 headerInitialization, condition, and update in one line of

code

Page 34: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 34

Nested Control Statements and the break Statement

Control statements may be nested.

Page 35: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 35

Nested Control Statements and the break Statement (cont.)

break statement: Prematurely end a loop

Page 36: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 37: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 38: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 39: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 40: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 41: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 42: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 43: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 44: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 44

Errors in Loops (cont.)

Debugging loops:– If an error is suspected, make sure that:

Variables are initialized before entering the loopThe terminating condition stops the iterations

when the test variables have reached the intended limit

The statements in the body are correct

Page 45: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 46: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 47: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 48: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 49: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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.

Page 50: Chapter 4 Introduction to Control Statements Fundamentals of Java.

Fundamentals of Java 50

Summary (cont.)

The comparison operators, such as ==, <=, and >=, 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.

Page 51: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 52: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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!");

Page 53: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 54: Chapter 4 Introduction to Control Statements Fundamentals of Java.

How To Write a While Loop

To write a while-loop, we think about three parts...1.Test2.Work3.increment

Fundamentals of Java 54

Page 55: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 56: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 57: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 58: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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 donewhile (num >= 1) {

num = num / 2; count++;

} return count;

} Fundamentals of Java 58

Page 59: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 60: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 61: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 62: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 63: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 64: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 65: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 66: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 67: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 68: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 69: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 70: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 71: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 72: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 73: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 74: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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

Page 75: Chapter 4 Introduction to Control Statements Fundamentals of Java.

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