Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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:
Example
Write a program that prints the message Welcome to Java! 100 times.
Example
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.
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.
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.
10
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
12
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.
13
14
For Loops
for (initial-action; Condition; Post-Iteration-Action) { // Loop body; Statement(s); }
15
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
18
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
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
/** 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
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
Example
Write a program that displays the multiplication table from 1 to 9 in the following format:
24
25
Expected output:
26
27
Exercise 4.18
(Printing four patterns using loops) Use nested loops that print the following patterns in four separate programs:
28
29
30
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
1 2 3 4 1 2 3 1 2 1
5 4 3 2 1
6 5 4 3 2 1
32
Exercise 4.26
Compute e:
33
Solution 4.26
34
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
Solution 4.33
36
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
38
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
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
Solution 4.16
41
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
Example: break
Write a program that adds integers from 1 to 20 until the sum is greater or equal to 100.
43
Example: continue
44
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
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
48