You are on page 1of 53

Loop statements

Categories of loops
• definite loop: Executes a known number of times.
– The for loops we have seen are definite loops.

• Print "hello" 10 times.


• Find all the prime numbers up to an integer n.
• Print each odd number between 5 and 127.

• indefinite loop: One where the number of times its body


repeats is not known in advance.
• Prompt the user until they type a non-negative number.
• Print random numbers until a prime number is printed.
• Repeat until the user has types "q" to quit.

2
Definite Loops
The for loop

4
for loop syntax
for (initialization; test; update) {
header
statement;
statement;
... body
statement;
}

– Perform initialization once.


– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
5
Initialization
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tells Java what variable to use in the loop


– Performed once as the loop begins

– The variable is called a loop counter


• can use any name, not just i
• can start at any value, not just 1

6
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

• Tests the loop counter variable against a limit


– Uses comparison operators:
< less than
<= less than or equal to
> greater than
>= greater than or equal to

7
Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 1;

int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5

8
Modify-and-assign
shortcuts to modify a variable's value

Shorthand Equivalent longer version


variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % value;

x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;

9
Repetition over a range
System.out.println("1 squared = " + 1 * 1);
System.out.println("2 squared = " + 2 * 2);
System.out.println("3 squared = " + 3 * 3);
System.out.println("4 squared = " + 4 * 4);
System.out.println("5 squared = " + 5 * 5);
System.out.println("6 squared = " + 6 * 6);
– Intuition: "I want to print a line for each number from 1 to 6"

• The for loop does exactly that!


for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = " + (i * i));
}

– "For each integer i from 1 through 6, print ..."


10
Loop walkthrough
1 2 3
for (int i = 1; i <= 4; i++) {
4 System.out.println(i + " squared = " + (i * i));
}
5 System.out.println("Whoo!");

1
Output:
1 squared = 1 2
2 squared = 4
3 squared = 9 4
4 squared = 16
Whoo!
3

11
Multi-line loop body
System.out.println("+----+");
for (int i = 1; i <= 3; i++) {
System.out.println("\\ /");
System.out.println("/ \\");
}
System.out.println("+----+");

– Output:
+----+
\ /
/ \
\ /
/ \
\ /
/ \
+----+
12
Expressions for counter
int highTemp = 5;
for (int i = -3; i <= highTemp / 2; i++) {
System.out.println(i * 1.8 + 32);
}

– Output:
26.6
28.4
30.2
32.0
33.8
35.6

13
System.out.print
• Prints without moving to a new line
– allows you to print partial messages on the same line

int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
System.out.print((i * 1.8 + 32) + " ");
}

• Output:
26.6 28.4 30.2 32.0 33.8 35.6

• Concatenate " " to separate the numbers

14
Counting down
• The update can use -- to make the loop count down.
– The test must say > instead of <

System.out.print("T-minus ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + ", ");
}
System.out.println("blastoff!");
System.out.println("The end.");

– Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, blastoff!
The end.

15
Nested for loops

16
Nested loops
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println(); // to end the line
}

• Output:
**********
**********
**********
**********
**********

• The outer loop repeats 5 times; the inner one 10 times.


– "sets and reps" exercise analogy 17
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

• Output:
*
**
***
****
*****

18
Nested for loop exercise
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}

• Output:
1
22
333
4444
55555

19
Common errors
• Both of the following sets of code produce infinite loops:
for (int i = 1; i <= 5; i++) {
for (int j = 1; i <= 10; j++) {
System.out.print("*");
}
System.out.println();
}

for (int i = 1; i <= 5; i++) {


for (int j = 1; j <= 10; i++) {
System.out.print("*");
}
System.out.println();
}

20
Complex lines
• What nested for loops produce the following output?
inner loop (repeated characters on each line)

....1
...2
..3 outer loop (loops 5 times because there are 5 lines)
.4
5

• We must build multiple complex lines of output using:


– an outer "vertical" loop for each of the lines
– inner "horizontal" loop(s) for the patterns within each line

21
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}

• Now look at the line contents. Each line has a pattern:


– some dots (0 dots on the last line), then a number
....1
...2
..3
.4
5

– Observation: the number of dots is related to the line number. 22


Mapping loops to numbers
for (int count = 1; count <= 5; count++) {
System.out.print( ... );
}

– What statement in the body would cause the loop to print:


4 7 10 13 16

for (int count = 1; count <= 5; count++) {


System.out.print(3 * count + 1 + " ");
}

23
Loop tables
• What statement in the body would cause the loop to print:
2 7 12 17 22

• To see patterns, make a table of count and the numbers.


– Each time count goes up by 1, the number should go up by 5.
– But count * 5 is too great by 3, so we subtract 3.

count number to print 5 * count 5 * count - 3


1 2 5 2
2 7 10 7
3 12 15 12
4 17 20 17
5 22 25 22

24
Loop tables question
• What statement in the body would cause the loop to print:
17 13 9 5 1

• Let's create the loop table together.


– Each time count goes up 1, the number printed should ...
– But this multiple is off by a margin of ...
count number to print -4 * count -4 * count + 21
1 17 -4 17
2 13 -8 13
3 9 -12 9
4 5 -16 5
5 1 -20 1

25
Nested for loop exercise
• Make a table to represent any patterns on each line.
....1 line # of dots -1 * line -1 * line + 5
...2
1 4 -1 4
..3
2 3 -2 3
.4
3 2 -3 2
5
4 1 -4 1
5 0 -5 0

• To print a character multiple times, use a for loop.


for (int j = 1; j <= 4; j++) {
System.out.print("."); // 4 dots
}
26
Nested for loop solution
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.println(line);
}

• Output:
....1
...2
..3
.4
5

27
Nested for loop exercise
• What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
for (int k = 1; k <= line; k++) {
System.out.print(line);
}
System.out.println();
}
• Answer:
....1
...22
..333
.4444
55555 28
Cumulative algorithms
Adding many numbers
• How would you find the sum of all integers from 1-1000?

// This may require a lot of typing


int sum = 1 + 2 + 3 + 4 + ... ;
System.out.println("The sum is " + sum);

• What if we want the sum from 1 - 1,000,000?


Or the sum up to any maximum?
– How can we generalize the above code?

30
Cumulative sum loop
int sum = 0;
for (int i = 1; i <= 1000; i++) {
sum = sum + i;
}
System.out.println("The sum is " + sum);

• cumulative sum: A variable that keeps a sum in progress and


is updated repeatedly until summing is finished.

– The sum in the above code is an attempt at a cumulative sum.

– Cumulative sum variables must be declared outside the loops that


update them, so that they will still exist after the loop.

31
Cumulative product
• This cumulative idea can be used with other operators:
int product = 1;
for (int i = 1; i <= 20; i++) {
product = product * 2;
}
System.out.println("2 ^ 20 = " + product);

– How would we make the base and exponent adjustable?

32
Scanner and cumul. sum
• We can do a cumulative sum of user input:

Scanner console = new Scanner(System.in);


int sum = 0;
for (int i = 1; i <= 100; i++) {
System.out.print("Type a number: ");
sum = sum + console.nextInt();
}
System.out.println("The sum is " + sum);

33
Cumulative sum question
• Modify the Receipt program from Ch. 2.
– Prompt for how many people, and each person's dinner cost.
– Use static methods to structure the solution.

• Example log of execution:


How many people ate? 4
Person #1: How much did your dinner cost? 20.00
Person #2: How much did your dinner cost? 15
Person #3: How much did your dinner cost? 30.0
Person #4: How much did your dinner cost? 10.00

Subtotal: $75.0
Tax: $6.0
Tip: $11.25
Total: $92.25
34
Cumulative sum answer
// This program enhances our Receipt program using a cumulative sum.
import java.util.*;
public class Receipt2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double subtotal = meals(console);
results(subtotal);
}
// Prompts for number of people and returns total meal subtotal.
public static double meals(Scanner console) {
System.out.print("How many people ate? ");
int people = console.nextInt();
double subtotal = 0.0; // cumulative sum
for (int i = 1; i <= people; i++) {
System.out.print("Person #" + i +
": How much did your dinner cost? ");
double personCost = console.nextDouble();
subtotal = subtotal + personCost; // add to sum
}
return subtotal;
}
...
35
Cumulative answer, cont'd.
...

// Calculates total owed, assuming 8% tax and 15% tip


public static void results(double subtotal) {
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;
System.out.println("Subtotal: $" + subtotal);
System.out.println("Tax: $" + tax);
System.out.println("Tip: $" + tip);
System.out.println("Total: $" + total);
}
}

36
Indefinite Loops
Loop Problem...
• Write a method printNumbers that prints each number from
1 to a given maximum, separated by commas.

For example, the call:


printNumbers(5)

should print:
1, 2, 3, 4, 5

38
Flawed solutions
• public static void printNumbers(int max) {
for (int i = 1; i <= max; i++) {
System.out.print(i + ", ");
}
System.out.println(); // to end the line of output
}

– Output from printNumbers(5): 1, 2, 3, 4, 5,

• public static void printNumbers(int max) {


for (int i = 1; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line of output
}

– Output from printNumbers(5): , 1, 2, 3, 4, 5

39
solution
public static void printNumbers(int max) {
System.out.print(1);
for (int i = 2; i <= max; i++) {
System.out.print(", " + i);
}
System.out.println(); // to end the line
}

• Alternate solution: Either first or last "post" can be taken out:


public static void printNumbers(int max) {
for (int i = 1; i <= max - 1; i++) {
System.out.print(i + ", ");
}
System.out.println(max); // to end the line
}
40
Question
• Modify your method printNumbers into a new method
printPrimes that prints all prime numbers up to a max.
– Example: printPrimes(50) prints
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47

– If the maximum is less than 2, print no output.

• To help you, write a method countFactors which returns the


number of factors of a given integer.
– countFactors(20) returns 6 due to factors 1, 2, 4, 5, 10, 20.

41
Answer
// Prints all prime numbers up to the given max.
public static void printPrimes(int max) {
if (max >= 2) {
System.out.print("2");
for (int i = 3; i <= max; i++) {
if (countFactors(i) == 2) {
System.out.print(", " + i);
}
}
System.out.println();
}
}
// Returns how many factors the given number has.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of number
}
}
return count;
}

42
while loops

43
The while loop
• while loop: Repeatedly executes its
body as long as a logical test is true.
while (test) {
statement(s);
}

• Example:
int num = 1; // initialization
while (num <= 200) { // test
System.out.print(num + " ");
num = num * 2; // update
}
// output: 1 2 4 8 16 32 64 128
44
Example while loop
// finds the first factor of 91, other than 1
int n = 91;
int factor = 2;
while (n % factor != 0) {
factor++;
}
System.out.println("First factor is " + factor);
// output: First factor is 7

– while is better than for because we don't know how many


times we will need to increment to find the factor.

45
Sentinel values
• sentinel: A value that signals the end of user input.
– sentinel loop: Repeats until a sentinel value is seen.

• Example: Write a program that prompts the user for numbers


until the user types 0, then outputs their sum.
– (In this case, 0 is the sentinel value.)

Enter a number (0 to quit): 10


Enter a number (0 to quit): 20
Enter a number (0 to quit): 30
Enter a number (0 to quit): 0
The sum is 60

46
Flawed sentinel solution
• What's wrong with this solution?
Scanner console = new Scanner(System.in);
int sum = 0;
int number = 1; // "dummy value", anything but 0

while (number != 0) {
System.out.print("Enter a number (0 to quit): ");
number = console.nextInt();
sum = sum + number;
}

System.out.println("The total is " + sum);

47
Changing the sentinel value
• Modify your program to use a sentinel value of -1.
– Example log of execution:
Enter a number (-1 to quit): 15
Enter a number (-1 to quit): 25
Enter a number (-1 to quit): 10
Enter a number (-1 to quit): 30
Enter a number (-1 to quit): -1
The total is 80

48
Changing the sentinel value
• To see the problem, change the sentinel's value to -1:
Scanner console = new Scanner(System.in);
int sum = 0;
int number = 1; // "dummy value", anything but -1

while (number != -1) {


System.out.print("Enter a number (-1 to quit): ");
number = console.nextInt();
sum = sum + number;
}

System.out.println("The total is " + sum);

• Now the solution produces the wrong output. Why?


The total was 79

49
The problem with our code
• Our code uses a pattern like this:
sum = 0.
while (input is not the sentinel) {
prompt for input; read input.
add input to the sum.
}

• On the last pass, the sentinel -1 is added to the sum:


prompt for input; read input (-1).
add input (-1) to the sum.

• Problem.
– Must read N numbers, but only sum the first N-1 of them.
50
Correct sentinel code
Scanner console = new Scanner(System.in);
int sum = 0;

// pull one prompt/read ("post") out of the loop


System.out.print("Enter a number (-1 to quit): ");
int number = console.nextInt();

while (number != -1) {


sum = sum + number; // moved to top of loop
System.out.print("Enter a number (-1 to quit): ");
number = console.nextInt();
}

System.out.println("The total is " + sum);

51
Sentinel as a constant
public static final int SENTINEL = -1;
...
Scanner console = new Scanner(System.in);
int sum = 0;

// pull one prompt/read ("post") out of the loop


System.out.print("Enter a number (" + SENTINEL +
" to quit): ");
int number = console.nextInt();

while (number != SENTINEL) {


sum = sum + number; // moved to top of loop
System.out.print("Enter a number (" + SENTINEL +
" to quit): ");
number = console.nextInt();
}

System.out.println("The total is " + sum);


52
The do/while loop
• do/while loop: Performs its test at the end of each repetition.
– Guarantees that the loop's {} body will run at least once.

do {
statement(s);
} while (test);

// Example: prompt until correct password is typed


String phrase;
do {
System.out.print("Type your password: ");
phrase = console.next();
} while (!phrase.equals("abracadabra"));
53

You might also like