System.out.print(i +

Download Report

Transcript System.out.print(i +

Loop - CIS 1068
Program Design and Abstraction
Zhen Jiang
CIS Dept.
Temple University
SERC 347, Main Campus
Email: [email protected]
1
Table of Contents












Taste of Loop
While Loop
Do While Loop
For Loop
Variations
Controlling Number of Loop Iterations
Loop Development
Mapping Iterations to Counter Values
Controlling Event of Loop Iterations
Random number generator
Fencepost problem (an interesting scenario)
Summary of Learning Materials
2
Taste of Loop

Price is right.


Sample execution (click on this link to try)
Before you get the price right, the program
will REPEAT…
3
while loop


while loop: A control structure that repeatedly performs a test and
executes a group of statements if the test evaluates to true.
while loop, general syntax:
<initialization>;
while (<test>) {
<body, consisting of statement(s)>;
}

Example:
int number = 1;
while (number <= 200) {
System.out.print(number + " ");
number *= 2;
}
Output:
1 2 4 8 16 32 64 128
4




The <initialization> prepares the variable declarations and
their values that are used in the test, update, and body of the
loop.
The <test> checks whether the repetition of the loop body can
stop.
The statement or group of statements to be repeated is called
the <body> of the loop.
Each repetition of the loop body is called an <iteration> of the
loop.
5
<initialization>;
while (<test>) {
<body>;
}
6

Finds and prints a number's first factor other than 1:
Scanner console = new Scanner(System.in);
System.out.print("Type a number: ");
int number = console.nextInt();
int factor = 2;
while (number % factor != 0) {
factor++;
}
System.out.println("First factor: " + factor);
Sample run:
Type a number: 91
First factor: 7
7

Example, WhileDemo.java, P202
8
Variant 1: do/while


do/while loop: A control structure that executes statements
repeatedly while a condition is true, testing the condition at the end
of each repetition.
do/while loop, general syntax:
<initialization>;
do {
<statement(s)>;
} while (<test>);

Example:
// roll until we get a number other than 3
Random rand = new Random();
int die;
do {
die = rand.nextInt();
} while (die == 3);
9

How does this differ from
the while loop?
 The controlled
<statement(s)> will
always execute the first
time, regardless of
whether the <test> is
true or false.
10

Example, DoWhileDemo.java, P206
11
Variant 2: for


for loop: A block of Java code that executes a group of statements
repeatedly until a given test fails.
General syntax:
for (<initialization>; <test>; <update>) {
<statement>;
<statement>;
...
<statement>;
}

Example:
for (int i = 1; i <= 30; i++) {
System.out.println("I will not throw...");
}
12
for (<init>; <test>; <update>) {
<body>;
}
13

Example, ForDemo.java, P219
14

Summary
Body first, and then
event change/update
15
16
17
18


Initialization, test, and body, and
execution results of loop
Code:
for (int i = 1; i <= 4; i++) {
System.out.println(i + " squared is " + (i * i));
}
Output:
1
2
3
4
squared
squared
squared
squared
is
is
is
is
1
4
9
16
19
Variations

The initial and final values for the loop counter/event variable can be
arbitrary expressions:

Example:
for (int i = -3; i <= 2; i++) {
System.out.println(i);
}
Output:
-3
-2
-1
0
1
2

Example:
for (int i = 1 + 3 * 4; i <= 5248 % 100; i++) {
System.out.println(i + " squared is " + (i * i));
}
20

The update can be a -- (or any other operator).

Caution: This requires changing the test from <= to >= .
System.out.println("T-minus");
for (int i = 3; i >= 1; i--) {
System.out.println(i);
}
System.out.println("Blastoff!");
Output:
T-minus
3
2
1
Blastoff!
21

What if we wanted the output to be the following?
T-minus 3 2 1 Blastoff!

System.out.print prints the given output without
moving to the next line.
System.out.print("T-minus ");
for (int i = 3; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Blastoff!");
22

When controlling a single statement, the {} braces are optional.
for (int i = 1; i <= 6; i++)
System.out.println(i + " squared is " + (i * i));

This can lead to errors if a line is not properly indented.
for (int i = 1; i <= 3; i++)
System.out.println("This is printed 3 times");
System.out.println("So is this... or is it?");
Output:
This is printed 3 times
This is printed 3 times
This is printed 3 times
So is this... or is it?

Moral: Always use curly braces and always use proper indentation.
23

Extra semicolon in a loop (P218).
int i;
for (i = 1; i <= 6; i++);
System.out.println(i + " squared is " + (i * i));
Output:
7 squared is 49

Comman in a loop (P220).
int sum;
for (int i=0, sum; …
int i, sum;
for (i = 1, sum = 0; i <= 10; i++)
sum = sum + i * i;
System.out.println("Result is " + sum);
Output:
385
24

Invalidation: Loops that never execute.
for (int i = 10; i < 5; i++) {
System.out.println("How many times do I print?");
}

ERROR: Loop tests that never fail.

A loop that never terminates is called an infinite loop.
for (int i = 10; i >= 1; i++) {
System.out.println("Runaway Java program!!!");
}
25

Loops that go on… forever
while (true) {
<statement(s)>;
}

If it goes on forever, how do you stop?
26


break statement: Immediately exits a loop (for, while,
do/while).
Example:
while (true) {
<statement(s)>;
if (<test>) {
break;
}
<statement(s)>;
}

Why is the break statement in an if statement?
27

Sentinel loop using break:
Scanner console = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.print("Enter a number (-1 to quit): ");
int inputNumber = console.nextInt();
if (inputNumber == -1) { // don't add -1 to sum
break;
}
sum += inputNumber; // inputNumber != -1 here
}
System.out.println("The total was " + sum);
28

Special case: If a variable is declared in the
<initialization> part of a for loop, its scope is
the for loop.
public static void main(String [] args) {
int x = 3;
int i;
for (i = 1; i <= 10; i++) {
System.out.println(x); i’s scope x's scope
}
// i no longer exists here
} // x ceases to exist here
29

ERROR: Using a variable outside of its scope.
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
int y = 5;
System.out.println(y);
}
System.out.println(i); // illegal
System.out.println(y); // illegal
}
30

COMMON ERROR: Using the wrong loop counter variable.



But barely possible when you develop code with our process.
What is the output of the following piece of code?
for (int i = 1; i <= 10; i++) {
for (int j = 1; i <= 5; j++) {
System.out.print(j);
}
System.out.println();
}
What is the output of the following piece of code?
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; i++) {
System.out.print(j);
}
System.out.println();
}
31

Exercises

http://www.cis.temple.edu/~jiang/1068LoopExecution.pdf
3/26/2016
32
Loop Development
population
TV purchase
1+2+4+8+...
1+2+3+4+...+99

http://www.cis.temple.edu/~jiang/LoopDevelopment.htm
33
34
Controlling Number of
Loop Iterations

If the number of iterations is known before
the loop starts, the loop is called a count-
controlled loop.



Counter =0, counter++, counter
<number
Counter = 1, counter++, counter
<=number
Use for loop for an easy development.
35
36
37
Mapping iterations to counter values



Suppose that we have the following loop:
for (int count = 0; count < 49; count++) {
...
}
What statement could we write in the body of the loop that
would make the loop print the following output?
0 2 4 6 8 …
Answer:
for (int count = 0; count < 49; count++) {
System.out.print(2 * count + " ");
}
38



Now consider another loop of the same style:
for (int count = 0; count < 49; count++) {
...
}
What statement could we write in the body of the loop that
would make the loop print the following output?
3 5 7 9 11
Answer:
for (int count = 0; count < 49; count++) {
System.out.print(2 * count + 3 + " ");
}
39

What statement could we write in the body of the loop that would
make the loop print the following output?
2 7 12 17 22

To find the pattern, it can help to make a table.


Each time count goes up by 1, the number should go up by 5.
But count * 5 is too big by 3, so we must subtract 3.
count
number to print
count * 5
count * 5 - 3
1
2
5
2
2
7
10
7
3
12
15
12
4
17
20
17
5
22
25
22
40
25
20
15
10
5
count (x)
number to print (y)
1
2
2
7
3
12
4
17
5
22
0
-2
0
-5
-10
2
4
6
41




Caution: This is algebra, not assignment!
Recall: slope-intercept form (y = mx + b)
Slope is defined as “rise over run” (i.e. rise / run). Since the “run” is
always 1 (we increment along x by 1), we just need to look at the
“rise”. The rise is the difference between the y values. Thus, the slope
(m) is the difference between y values; in this case, it is +5.
To compute the y-intercept (b), plug in the value of y at x = 1 and
solve for b. In this case, y = 2.
y = m * x + b
2 = 5 * 1 + b
Then b = -3

So the equation is
y = m * x + b
y = 5 * x – 3
y = 5 * count - 3
count (x)
number to print (y)
1
2
2
7
3
12
4
17
5
22
42

Algebraically, if we always take the value of y at
x = 1, then we can solve for b as follows:
y = m * x + b
y1 = m * 1 + b
y1 = m + b
b = y1 – m

In other words, to get the y-intercept, just subtract the
slope from the first y value (b = 2 – 5 = -3)

This gets us the equation
y = m * x + b
y = 5 * x – 3
y = 5 * count – 3
(which is exactly the equation from the previous slides)
43

What statement could we write in the body of the loop that would
make the loop print the following output?
17 13 9 5 1

Let's create the loop table together.


Each time count goes up 1, the number should ...
But this multiple is off by a margin of ...
count
number to print
count * -4
count * -4 + 21
1
17
-4
17
2
13
-8
13
3
9
-12
9
4
5
-16
5
5
1
-20
1
44

Coding (different from execution check):
n=keyboard.nextInt(); // try 6!
for (int i = 1; i <= n; i++)
{
System.out.print("*");
}
System.out.println();
Output:
******
3/26/2016
45

More complicate case:
n=keyboard.nextInt(); // try 6!
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
System.out.print("*");
}
System.out.println();
}
Output:
******
******
******
******
******
******
3/26/2016
46

Code:
n=keyboard.nextInt(); // try 5!
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= 10; j++)
{
System.out.print(
(i * j) + " ");
}
System.out.println();
}
Output:
1
2
3
4
5
2 3 4 5 6 7 8 9 10
4 6 8 10 12 14 16 18 20
6 9 12 15 18 21 24 27 30
8 12 16 20 24 28 32 36 40
10 15 20 25 30 35 40 45 50
3/26/2016
47


How to confirm the initialization correct?
On preparing the 1st iteration …
How to ensure the detail of the body?
A consistent view of 1st, 2nd, 3rd iterations …
Map of the counter value to the iteration
expression …
48

Code:
n=keyboard.nextInt(); // try 6!
for (i = 1; i<=n; i++) System.out.print(“*”);
System.out.println(“”);
for (i = 1; i <= n-2; i++) {
System.out.print(“*”);
for (int j = 1; j <= n-2; j++)
System.out.print(“ ”);
System.out.println(“*”);
}
for (i = 1; i<=n; i++) System.out.print(“*”);
System.out.println(“”);
Output:
******
*
*
*
*
*
*
*
*
******
3/26/2016
49

Code:
n=keyboard.nextInt(); // try 6!
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
Output:
*
**
***
****
*****
******
3/26/2016
50

Code:
n=keyboard.nextInt(); // try 6!
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}
Output:
1
22
333
4444
55555
666666
3/26/2016
51

Code:
n=keyboard.nextInt(); // try 5!
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print(i);
}
System.out.println();
}
Output:
1
22
333
4444
55555
3/26/2016
52
Controlling Event of Loop
Iterations

Otherwise (unknown or unclear), the loop is
called a event-controlled loop.


Use a while loop or a do-while loop for an
easy checkpoint development.
Asking the user before each iteration if it is time to
end the loop is called the ask-before-iterating
technique.

3/26/2016
Appropriate status update (or event initializing) for
a sequence of iterations
53
3/26/2016
54

Finds and prints a number's first factor other than 1:
int n = keyboard.nextInt(); // try 91
int f = 2;
while (n % f != 0)
{
f++;
}
System.out.println("First factor:" + f);
Sample run:
First factor:7
3/26/2016
55

Write a program that will repeatedly prompt the user to
type a number until the user types a non-negative number,
then square it.
Example log:
Type a non-negative integer: -5
Invalid number, try
Invalid number, try
Invalid number, try
Invalid number, try
11 squared is 121
3/26/2016
again:
again:
again:
again:
-1
-235
-87
11
56
System.out.print("Type a non-negative integer: ");
int n = keyboard.nextInt();
while (n < 0) {
System.out.print("Invalid number, try again: ");
n = keyboard.nextInt();
}
int square = n * n;
System.out.println(n + " squared is " + square);

Notice that the number variable had to be declared outside
the while loop in order to remain in scope.
3/26/2016
57

Write a class named DigitSum that reads an integer from
the user and prints the sum of the digits of that number.
You may assume that the number is non-negative.
Example:
Enter a nonnegative number:
29107
prints out 19 (i.e.,2+9+1+0+7 )

Hint: Use the % operator to extract the last digit of a
number. If we do this repeatedly, when should we stop?
3/26/2016
58
import java.util.Scanner;
public class DigitSum {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
int sum = 0;
while (n > 0) {
sum += n % 10;
// add last digit to sum
n = n / 10;
// remove last digit
}
System.out.println(“sum = “ + sum);
}
}
3/26/2016
59

Write a program named CountFactors that reads in an
integer and displays its number of factors.

For example, if the user enters 60, CountFactors displays 12
because 1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, and 60 are all factors
of 60.
Scanner keyboard = new Scanner(System.in);
int n = keyboard.nextInt();
int sum = 0, k = ?;
while (
) {
}
System.out.println(“sum = “ + sum);
3/26/2016
60
Scanner keyboard =new Scanner(System.in);
int n = keyboard.nextInt();
int k = 1;
int sum = 0;
while (k<=n)
{
if(n%k==0)
sum ++;
k++;
}
System.out.print("sum = " + sum);
61

Exercises (Wednesday lab)
population
TV purchase
1+2+4+8+...
1+2+3+4+...+99
62
63
64

Complete a Loop program

http://www.cis.temple.edu/~jiang/1068LoopComplete.pdf
65
Random Number Generator

Objects of the Random class generate pseudo-random
numbers.


Class Random is found in the java.util package.
import java.util.*;
The methods of a Random object
Method name
Description
nextInt()
returns a random integer
nextInt(max)
returns a random integer in the range [0, max)
in other words, from 0 to one less than max
nextDouble() returns a random real number in the range [0.0, 1.0)
66
Random rand = new Random();
int randomNum = rand.nextInt(10);
// randomNum has a random value between 0 and 9

What if we wanted a number from 1 to 10?
int randomNum = rand.nextInt(10) + 1;

What if we wanted a number from min to max (i.e. an
arbitrary range)?
int randomNum = rand.nextInt(<size of the range>) +
<min>
where <size of the range> equals (<max> - <min> + 1)
67

Given the following declaration, how would you get:

A random number between 0 and 100 inclusive?

A random number between 1 and 100 inclusive?

A random number between 4 and 17 inclusive?
68

Given the following declaration, how would you get:



A random number between 0 and 100 inclusive?
int random1 = rand.nextInt(101);
A random number between 1 and 100 inclusive?
int random1 = rand.nextInt(100) + 1;
A random number between 4 and 17 inclusive?
int random1 = rand.nextInt(14) + 4;
69

Write a program that simulates the rolling of two six-sided
dice until their combined result comes up as 7.
Sample run:
Roll: 2
Roll: 3
Roll: 5
Roll: 1
Roll: 4
You won
+ 4 =
+ 5 =
+ 6 =
+ 1 =
+ 3 =
after
6
8
11
2
7
5 tries!
70
import java.util.*;
public class Roll {
public static void main(String[] args) {
Random rand = new Random();
int sum = 0;
int tries = 0;
while (sum != 7) {
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println("Roll: " + roll1 + " + " + roll2 + " = " + sum);
tries++;
}
System.out.println("You won after " + tries + " tries!");
}
}
71
Fencepost Problem


Fencepost Problem: Write a class named PrintNumbers
that reads in an integer called max and prints each number
from 1 to max, separated by commas.
Example:
java PrintNumbers
Please enter a maximum integer:
5
should print:
1, 2, 3, 4, 5
72


We want to print n numbers but need only n - 1 commas.
Similar to the task of building a fence


If we repeatedly place a post and wire, the last post has an
extra dangling wire.
A flawed algorithm:
for (length of fence) {
plant a post.
attach some wire.
}
73
import java.util.Scanner;
public class PrintNumbers {
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int max = keyboard.nextInt();
for (int i = 1; i <= max; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line
}
unnecessary
}

Output when user enters 5:
1, 2, 3, 4, 5,
// notice extra comma at end!
74
unnecessary

import java.util.Scanner;
public class PrintNumbers
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int max = keyboard.nextInt();
for (int i = 1; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}
}
Output when user enters 5:
, 1, 2, 3, 4, 5
// comma at beginning
75

The solution is to add an extra statement outside the loop
that places the initial "post."


This is called a fencepost loop.
The revised algorithm:
plant a post.
for (length of fence - 1) {
attach some wire.
plant a post.
}
76
import java.util.Scanner;
public class PrintNumbers
public static void main(String [] args) {
Scanner keyboard = new Scanner(System.in);
int max = keyboard.nextInt();
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}
}

Output when user enters 5:
1, 2, 3, 4, 5
// no extra comma!
77
Summary




WhileDemo.java, p202
DoWhileDemo.java, p206
ForDemo.java, p219
Exercises, slides 32, 45-52, 55-65, 70-71, 77
78












Test (controlling boolean expression, P201), body (P200), iteration
(P200), and initialization (P228)
While (P201-204), do-while (P204-9), and for loop (P217-221)
Counter-controlled (P229) and event controlled loop
Mapping iterations to counter values
Trace and development template
Random number generator
The omission of {} and its side effect (P218)
Extra semicolon (P222) and comma (P224)
Invalidation and infinite loop (P213)
The use of break and its function (P236-7)
Scope of loop variable (P223)
Fencepost problem and its solution
79