Sei sulla pagina 1di 48

Chapter 4: Loops

Introduction to Java Programming, Daniel Liang, 8th Edition

Spring 2012 - 2013

Introduction

Loop: Powerful control structure that controls how many times an operation or a sequence of operations is performed in succession. Three types of loops:

while loop do-while loop for loop

Fatima Kanj, Spring 2012 - 2013

The while Loop


while (condition){ //Loop Body Statement(s); } Condition: Boolean Expression Iteration: A one time execution of the loop

Fatima Kanj, Spring 2012 - 2013

Example

Write a program that prints the message Welcome to Java! 100 times.

Remark: counter-controlled loop Trace it.


4 Fatima Kanj, Spring 2012 - 2013

Example

Trace the following:

(Infinite Loop)Trace the following

Fatima Kanj, Spring 2012 - 2013

Problem: Guessing Numbers

Check it out in section 4.2.1

Fatima Kanj, Spring 2012 - 2013

Loop Design Strategies

Consider three steps when writing a loop:


Step 1: Identify the statements that need to be repeated. Step 2: Wrap these statements in a loop like this:

Step 3: Code the loop-continuation-condition and add appropriate statements for controlling the loop.

Fatima Kanj, Spring 2012 - 2013

Remarks

Loop condition must be always inside parenthesis. Loop curly braces can be omitted if the loop body includes only one statement. Make sure that the condition will eventually become false, otherwise infinite loops occur.

You can halt the execution of a running program by pressing Ctrl + C

Fatima Kanj, Spring 2012 - 2013

Controlling a Loop with a Sentinel Value

Often the number of times a loop is executed is not predetermined. Sentinel Value: an input value to signify the end of the loop.

Using a while loop, write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

Solution: Next Slide

Fatima Kanj, Spring 2012 - 2013

10

Fatima Kanj, Spring 2012 - 2013

Caution

Do Not use floating-point values for equality checking in a loop control. Since floating point values are approximations for some values, using them could result in imprecise counter values and inaccurate results (remember rounding errors).

11

Fatima Kanj, Spring 2012 - 2013

The do-while Loop


do { // Loop body; Statement(s); } while (loop-continuation-condition); 1. Used when your loop body must be executed at least once.

12

Fatima Kanj, Spring 2012 - 2013

Example

Using a do-while loop, write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input.

Solution: Next Slide

13

Fatima Kanj, Spring 2012 - 2013

14

Fatima Kanj, Spring 2012 - 2013

For Loops
for (initial-action; Condition; Post-Iteration-Action) { // Loop body; Statement(s); }

15

Fatima Kanj, Spring 2012 - 2013

for Loop vs. while Loop


int i; for (i = 0; i < 100; i++) { System.out.println("Welcome to Java!"); } int i = 0; while (i < 100){ System.out.println("Welcome to Java!"); i++; }
16 Fatima Kanj, Spring 2012 - 2013

Remarks
If

i is declared in the for loop control structure, it cannot be referenced outside the loop. for (int i = 0; i < 100; i++) System.out.println(i);

17

Fatima Kanj, Spring 2012 - 2013

Which Loop to Use?

All are equivalent:

A for loop can generally be converted into a while loop.

18

Fatima Kanj, Spring 2012 - 2013

Which Loop to Use?

Use the loop statement that is most intuitive and comfortable for you. General Guidelines:

for loop: It may be used if the number of iterations is known. Example: when you need to print a message a hundred times. while loop: It may be used if the number of iterations is not known, as in the case of reading the numbers until the input is 0. do-while loop: It can be used to replace a while loop if the loop body has to be executed before the continuation condition is tested.
Fatima Kanj, Spring 2012 - 2013

19

Remarks

Do Not add a semi colon at the end of a for loop Unfortunately, no syntax error! The compiler interprets it as a loop with an empty body.

20

Fatima Kanj, Spring 2012 - 2013

For Loop: Example

Exercise 4.8 A program that prompts the user to enter the number of students and each student's name and score and displays the student with the highest score

21

Fatima Kanj, Spring 2012 - 2013

/** This program prompts the user to enter the number of students and each student's name and score, and finally displays the student with the highest score*/
import java.util.Scanner; public class Test { public static void main (String[]args) { //Variable Declaration int numOfStudents = 0; String studName = " "; int score = 0; Scanner scan = new Scanner (System.in); //Reading numOfStudents System.out.println("Enter the number of students: "); numOfStudents = scan.nextInt(); System.out.println("Enter the records of students and their scores in the format FirstName LastName score:"); String studName_1 = scan.next() + " " + scan.next(); int score_1 = scan.nextInt(); for(int i = 0; i < numOfStudents - 1; i++){ studName = scan.next()+ " " + scan.next(); //concatenating first and last name score = scan.nextInt(); if (score > score_1){ score_1 = score; studName_1 = studName; } }//End for System.out.println("Top Student is: " + studName_1 + " with score: " + score_1); }//End main }

22

Fatima Kanj, Spring 2012 - 2013

Nested Loops

Nested loops consist of an outer loop and one or more inner loops.

Each time the outer loop is repeated, the inner loops are reentered, and started anew.

Nested loops can make programs more elegant and more readable. Any loop can be nested within any other loops.

23

Fatima Kanj, Spring 2012 - 2013

Example

Write a program that displays the multiplication table from 1 to 9 in the following format:

24

Fatima Kanj, Spring 2012 - 2013

25

Fatima Kanj, Spring 2012 - 2013

Multiplication Table: JOptionPane

Expected output:

26

Fatima Kanj, Spring 2012 - 2013

27

Fatima Kanj, Spring 2012 - 2013

Exercise 4.18

(Printing four patterns using loops) Use nested loops that print the following patterns in four separate programs:

28

Fatima Kanj, Spring 2012 - 2013

Exercise 4.18: Pattern I


for (int i = 1; i <= 6; i++){ for (int j = 1; j <= i ; j++) System.out.print(j + " "); System.out.println(); } Output: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 1 2 3 4 5 6

29

Fatima Kanj, Spring 2012 - 2013

Exercise 4.18: Pattern II


for(int i = 1; i <= 6; i++){ for (int j = 1; j <= 6 - i + 1; j++) System.out.print(j + " "); System.out.println(); } Output: 1 2 3 4 5 6 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1

30

Fatima Kanj, Spring 2012 - 2013

Exercise 4.18: Pattern III


for (int i = 1; i <= 6; i++){ for (int j = 6; j >= 1 ; j--){ if(j <= i) System.out.print(" " + j); else System.out.print(" "); } System.out.println(); } Output:

3 4 3 5 4 3 6 5 4 3
31

2 2 2 2 2

1 1 1 1 1 1
Fatima Kanj, Spring 2012 - 2013

Exercise 4.18: Pattern IV


for (int i = 1; i <= 6; i++){ for (int j = 1; j <= 6 ; j++){ if(j >= i) System.out.print(j-i+1 + " "); else System.out.print(" "); } System.out.println(); } Output:

1 2 3 4 1 2 3 1 2 1

5 4 3 2 1

6 5 4 3 2 1

32

Fatima Kanj, Spring 2012 - 2013

Exercise 4.26

Compute e:

33

Fatima Kanj, Spring 2012 - 2013

Solution 4.26

34

Fatima Kanj, Spring 2012 - 2013

Exercise 4.33

(Perfect number) A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself.

For example, 6 is the first perfect number 6 = 3 + 2 + 1. The next is 28 = 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10000. Write a program to find all these four numbers.

35

Fatima Kanj, Spring 2012 - 2013

Solution 4.33

36

Fatima Kanj, Spring 2012 - 2013

Case Study: Finding GCD

Write a program that finds the Greatest Common Divisor GCD of two given numbers n1 and n2. Note that 1 is a common divisor of two numbers but it might not the greatest, so you need to check k = 2, 3, 4, . until k is greater than n1 or n2. Solution is in next slide.

37

Fatima Kanj, Spring 2012 - 2013

Solution: Finding GCD

38

Fatima Kanj, Spring 2012 - 2013

Exercise 4.15

(Computing the greatest common divisor) Another solution for Listing 4.8 to find the greatest common divisor of two integers n1 and n2 is as follows: First find d to be the minimum of n1 and n2, then check whether d, d-1, d-2, 2, or 1 is a divisor for both n1 and n2 in this order. The first such common divisor is the greatest common divisor for n1 and n2. Write a program that prompts the user to enter two positive integers and displays the gcd.

39

Fatima Kanj, Spring 2012 - 2013

Exercise 4.16

(Finding the factors of an integer) Write a program that reads an integer and displays all its smallest factors in increasing order. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5.

40

Fatima Kanj, Spring 2012 - 2013

Solution 4.16

41

Fatima Kanj, Spring 2012 - 2013

break and continue Keywords

These keywords are generally used with an if statement. break immediately ends the innermost loop that contains it. continue only ends the current iteration. Comparing the two: continue breaks out of an iteration while the break keyword breaks out of a loop.

42

Fatima Kanj, Spring 2012 - 2013

Example: break

Write a program that adds integers from 1 to 20 until the sum is greater or equal to 100.

43

Fatima Kanj, Spring 2012 - 2013

Example: continue

Write a program that adds integers from 1 to 20 except 10 and 11.

44

Fatima Kanj, Spring 2012 - 2013

Displaying Prime Numbers

Write a program that displays the first fifty prime numbers in five lines, each of which contains ten numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. The problem can be broken into the following tasks:

45

Determine whether a given number is prime. For number = 2, 3, 4, 5, 6, . . ., test whether it is prime. Count the prime numbers. Print each prime number, and print ten numbers per line.
Fatima Kanj, Spring 2012 - 2013

46

Fatima Kanj, Spring 2012 - 2013

Exercise 4.20

(Printing prime numbers between 2 and 1000) Modify Listing 4.14 to print all the prime numbers between 2 and 1000, inclusive. Display eight prime numbers per line.

47

Fatima Kanj, Spring 2012 - 2013

48

Fatima Kanj, Spring 2012 - 2013

Potrebbero piacerti anche