44
CS110: PROGRAMMING LANGUAGE I Lectures 6 & 7: Loops Computer Science Department

CS110: PROGRAMMING LANGUAGE I#6+&+#7-+Loops.pdf... · Motivations 3 Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have

  • Upload
    dotruc

  • View
    216

  • Download
    2

Embed Size (px)

Citation preview

CS110: PROGRAMMING

LANGUAGE I

Lectures 6 & 7: Loops Computer Science

Department

while repetition statement

do…while repetition statement

for repetition statement

Which Loop to Use?

Nested loops

break and continue Statements

Sentinel-controlled loops

L. Shaykhah Aldosari,2014

Lecture Contents: 2

Motivations 3

Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times:

System.out.println("Welcome to Java!");

So, how do you solve this problem?

L. Shaykhah Aldosari,2014

Opening Problem 4

Problem: System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

… System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

System.out.println("Welcome to Java!");

100

times

L. Shaykhah Aldosari,2014

Essentials of Counter-Controlled

Repetition

Counter-controlled repetition requires

a control variable (or loop counter)

the initial value of the control variable

the increment (or decrement) by which the control

variable is modified each time through the loop (also

known as each iteration of the loop)

the loop-continuation condition that determines if

looping should continue.

L. Shaykhah Aldosari,2014

5

while Repetition Statement

Repetition statement—repeats an action while a condition remains true.

Pseudocode While there are more items on my shopping list Purchase next item and cross it off my list

The repetition statement’s body may be a single statement or a block.

Eventually, the condition will become false. At this point, the repetition terminates, and the first statement after the repetition statement executes.

L. Shaykhah Aldosari,2014

6

while Loop Flow Chart 7

while (loop-continuation-condition) {

// loop-body;

Statement(s);

}

int count = 0;

while (count < 100) {

System.out.println("Welcome to Java!");

count++;

}

Loop

Continuation

Condition?

true

Statement(s)

(loop body)

false

(count < 100)?

true

System.out.println("Welcome to Java!");

count++;

false

(A) (B)

count = 0;

L. Shaykhah Aldosari,2014

while Repetition Statement (Cont.)

Example of Java’s while repetition statement: find the first power of 3 larger than 100. Assume int variable product is initialized to 3.

while ( product <= 100 ) product = 3 * product;

Each iteration multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively.

When variable product becomes 243, the while-statement condition—product <= 100—becomes false.

Repetition terminates. The final value of product is 243.

Program execution continues with the next statement after the while statement.

L. Shaykhah Aldosari,2014

8

L. Shaykhah Aldosari,2014

9

Example

L. Shaykhah Aldosari,2014

10

Problem: Repeat Addition Until Correct 11

Recall that Listing 3.1 AdditionQuiz.java gives a

program that prompts the user to enter an answer for

a question on addition of two single digits. Using a

loop, you can now rewrite the program to let the user

enter a new answer until it is correct.

L. Shaykhah Aldosari,2014

The answer 12

L. Shaykhah Aldosari,2014

Output 13

L. Shaykhah Aldosari,2014

do…while Repetition Statement

L. Shaykhah Aldosari,2014

The do…while repetition statement is similar to the while statement.

In the while, the program tests the loop-continuation condition at the beginning of the loop, before executing the loop’s body; if the condition is false, the body never executes.

The do…while statement tests the loop-continuation condition after executing the loop’s body; therefore, the body always executes at least once.

When a do…while statement terminates, execution continues with the next statement in sequence.

14

do…while Loop Flow Chart 15

do {

// Loop body;

Statement(s);

} while (loop-continuation-condition);

Loop

Continuation

Condition?

true

Statement(s)

(loop body)

false

L. Shaykhah Aldosari,2014

Example

L. Shaykhah Aldosari,2014

16

do…while Repetition Statement

(Cont.)

L. Shaykhah Aldosari,2014

Braces are not required in the do…while repetition

statement if there’s only one statement in the body.

Most programmers include the braces, to avoid

confusion between the while and do…while

statements.

Thus, the do…while statement with one body

statement is usually written as follows:

do { statement } while ( condition );

17

for Repetition Statement

for repetition statement

Specifies the counter-controlled-repetition details in a

single line of code.

L. Shaykhah Aldosari,2014

18

for Loops Flow Chart 19

Loop

Continuation

Condition?

true

Statement(s)

(loop body)

false

(A)

Action-After-Each-Iteration

Initial-Action

(i < 100)?

true

System.out.println(

"Welcome to Java");

false

(B)

i++

i = 0

L. Shaykhah Aldosari,2014

for statements header components

L. Shaykhah Aldosari,2014

20

for Repetition Statement (Cont.)

L. Shaykhah Aldosari,2014

The general format of the for statement is for ( initialization; loopContinuationCondition;

increment ) statement

the initialization expression names the loop’s control variable and optionally provides its initial value

loopContinuationCondition determines whether the loop should continue executing

increment modifies the control variable’s value (possibly an increment or decrement), so that the loop-continuation condition eventually becomes false.

The two semicolons in the for header are required.

21

for Repetition Statement (Cont.)

L. Shaykhah Aldosari,2014

In most cases, the for statement can be represented with an equivalent while statement as follows:

initialization; while ( loopContinuationCondition ) { statement increment; }

Typically, for statements are used for counter-controlled repetition and while statements for sentinel-controlled repetition.

If the initialization expression in the for header declares the control variable, the control variable can be used only in that for statement.

22

Examples Using the for Statement

L. Shaykhah Aldosari,2014

Vary the control variable from 1 to 100 in increments

of 1. for ( int i = 1; i <= 100; i++ )

Vary the control variable from 100 to 1 in decrements

of 1. for ( int i = 100; i >= 1; i-- )

Vary the control variable from 7 to 77 in increments

of 7. for ( int i = 7; i <= 77; i += 7 )

23

Example

L. Shaykhah Aldosari,2014

24

Figure 5.2 replacements the application of Fig. 5.1 using for.

Example

L. Shaykhah Aldosari,2014

25

Examples Using the for Statement

(Cont.)

L. Shaykhah Aldosari,2014

Compound interest application

A person invests $1000 in a savings account yielding 5% interest. Assuming that all the interest is left on deposit, calculate and print the amount of money in the account at the end of each year for 10 years. Use the following formula to determine the amounts:

a = p (1 + r)n

where

p is the original amount invested (i.e., the principal) r is the annual interest rate (e.g., use 0.05 for 5%) n is the number of years a is the amount on deposit at the end of the nth year.

26

Examples Using the for Statement

(Cont.)

L. Shaykhah Aldosari,2014

The solution to this problem (Fig. 5.6) involves a

loop that performs the indicated calculation for each

of the 10 years the money remains on deposit.

Java treats floating-point constants like 1000.0 and

0.05 as type double.

Java treats whole-number constants like 7 and -22

as type int.

27

L. Shaykhah Aldosari,2014

28

L. Shaykhah Aldosari,2014

29

Caution 30

Adding a semicolon at the end of the for clause

before the loop body is a common mistake, as shown

below: Logic Error

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

{

System.out.println("i is " + i);

}

L. Shaykhah Aldosari,2014

Caution, cont. 31

Similarly, the following loop is also wrong: int i=0; while (i < 10); { System.out.println("i is " + i); i++; }

In the case of the do loop, the following semicolon is needed to end the loop. int i=0; do { System.out.println("i is " + i); i++; } while (i<10);

Logic Error

Correct

L. Shaykhah Aldosari,2014

Which Loop to Use? 32

The three forms of loop statements, while, do-while, and for, are

expressively equivalent; that is, you can write a loop in any of these

three forms. For example, a while loop in (a) in the following figure

can always be converted into the following for loop in (b):

while (loop-continuation-condition) { // Loop body

}

(a)

Equivalent

(b)

for ( ; loop-continuation-condition; ) {

// Loop body

}

L. Shaykhah Aldosari,2014

Which Loop to Use? (Cont.) 33

A for loop in (a) in the following figure can generally be converted

into the following while loop in (b) except in certain special cases (see

Review Question 3.19 for one of them):

for (initial-action; loop-continuation-condition;

action-after-each-iteration) {

// Loop body;

}

(a)

Equivalent

(b)

initial-action;

while (loop-continuation-condition) {

// Loop body;

action-after-each-iteration;

}

L. Shaykhah Aldosari,2014

Recommendations 34

Use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.

L. Shaykhah Aldosari,2014

Nested Loops 35

Problem: Write a program that uses nested

for loops to print a multiplication table.

L. Shaykhah Aldosari,2014

Output 36

L. Shaykhah Aldosari,2014

The answer 37

L. Shaykhah Aldosari,2014

break and continue Statements

L. Shaykhah Aldosari,2014

The continue statement, when executed in a

while, for or do…while, skips the remaining

statements in the loop body and proceeds with the next

iteration of the loop.

In while and do…while statements, the program

evaluates the loop-continuation test immediately after

the continue statement executes.

In a for statement, the increment expression executes,

then the program evaluates the loop-continuation test.

38

Examples for using the break keyword

L. Shaykhah Aldosari,2014

39

Example for using the continue keyword

L. Shaykhah Aldosari,2014

40

Sentinel-controlled loops 41

A Sentinel value is a value that is used to end the

iterations of a loop.

It can be impelmented in any kind of loops

L. Shaykhah Aldosari,2014

Example 42

Develop a java program to determine the gross pay for a number

of employees. The company pays “straight time” for the first 40

hours worked by each employee and pays “time-and-a-half” for all

hours worked in excess of 40 hours. Your program should input the

number of hours each employee worked last week and the hourly

rate of each employee. It then should determine and display the

employee's gross pay.

Hint:

Use -1 as a sentinel value

L. Shaykhah Aldosari,2014

Control structures in Java

Java

Control Structure

Sequence structure

Selection Structure

if If ….else Switch

Repetition structure

While do…while for

43

L. Shaykhah Aldosari,2014

Text Book:

Java : how to program , by P.J. Deitel, H.M. Deitel. -- 9th ed.

Sections:

4.7, 4.8, 4.9, 4.10, 5.3, 5.4, 5.5, 5.7.

That’s all for today !! 44

L. Shaykhah Aldosari,2014