← All AP Java lessons

AP Java / J06

Loops

while, for, nested loops, break and continue, random numbers, assignments, and projects.

Intro CS - Ch.6 - Loops

Add break/continue to this chapter:

6. While Loops

6.1 Intro to Loops

6.2 For Loops

6.3 Nested Loops

6.4 Generating Random Numbers

6.4.1 Random Reals

6.4.2 Random Integers

Chapter 6: Assignments

A6.1 Count to 1000

A6.2 Count by 2’s

A6.3 Counting across and down

A6.4 Count to 50

A6.5 Count to 210

A6.6 Line of stars

A6.7 Counting in a range with a While Loop

A6.8 Nested Loop

A6.9 Nested Loop Stars

A6.10 Multiplication Tables

Projects

Project 6.1: Guessing Game

Project 6.2: Slot Machine

Project 6.3: Choice of Two Games

6. While Loops

6.1 Intro to Loops

EXAMPLE: Simple counter

int counter = 1

while (counter <= 10)

{

System.out.println(counter);

counter = counter + 1;

}

System.out.println(“All done counting!”);

OUTPUT:

1

2

3

4

5

6

7

8

9

10

All done counting!

6.2 For Loops

EXAMPLE: Counter up to 5

int limit = 5;

for(int i = 1; i <= limit; i++)

{

System.out.print(i + “ “);

}

System.out.println("Done");

OUTPUT: 1 2 3 4 5

SUMMARY:

  1. The counter is initialized, conditional is checked.
  2. If conditional is FALSE, continue beyond loop. If conditional is TRUE, execute loop.
  3. After completion of the loop, the increment is applied and the conditional is checked (go back to step #2)

6.3 Nested Loops

EXAMPLE: This program builds the numbers from 0 to 99 with i as the tens counter

and j as the ones counter.

for(int i = 0; i <= 9; i++) // Counts from 0 to 9

{

for(int j = 0; j <= 9; j++) // Counts from 0 to 9

{

System.out.println(“Counting: “ + i + j);

}

}

OUTPUT: 00

01

02

……

98

99

6.4 Generating Random Numbers

6.4.1 Random Reals

double r = Math.random();

This produces a random real number in the range 0.0 to 1.0, where 0.0 is included and

1.0 is not. This range (0.0 ≲ x < 1.0) can be scaled and shifted as seen in the following

examples:

Example 1: Produce a random real value x in the range 0.0 ≲ x < 6.0:

double x = 6 * Math.random(); // Stretched by a multiple of 6

Example 2: Produce a random real value x in the range 2.0 ≲ x < 3.0:

double x = Math.random() + 2; // Shifted by 2

Example 3: Produce a random real value x in the range 4.0 ≲ x < 6.0:

double x = 2 * Math.random() + 4; // Stretched by 2 and shifted by 4

In general, to produce a random real value in the range lowValue ≲ x < highValue:

double x = (highValue - lowValue) * Math.random() + lowValue;

Random Integers

Casting:

double x = 3.55;

System.out.print( (int)x ); // Will print 3, but x will remain a

double of 3.55

(Do the Casting worksheet)

6.4.2 Random Integers

Example 1: Produce a random integer from 0 to 99:

int num = (int)(Math.random() * 100); // This goes up to 99.

Before the (int) cast, Math.random() * 100 generates:

Example 2: Produce a random integer from 1 to 100:

int num = (int)(Math.random() * 100) + 1; // Shift up by 1

This is the same as Example 1, but shift the 0-99 to 1-100.

Example 3: Produce a random integer from 5 to 24:

int num = (int)(Math.random() * 20) + 5;

The multiple of 20 along with the cast produces a number from 0-19. The

shift of 5 moves the range from 5-24.

(Do the worksheet on random numbers)

Chapter 6: Assignments

A6.1 Count to 1000

Create a program that counts from 100 to 1000 by 100’s and says “Finished!!” at the end.

PROGRAM STRUCTURE:

// Declare and initialize a variable with a value of 100

//while (condition for variable being less than or equal to 1000)

{

// print value of variable

// increase value of variable by 100

}

// Print: Finished!

OUTPUT:

100

200

300

400

500

600

700

800

900

1000

Finished!

A6.2 Count by 2’s

Create a program that prints out all even numbers from 1 to 50.

PROGRAM STRUCTURE:

// Declare and initialize a variable with a value of 1

//while (condition for variable being less than or equal to 50)

{

// Create an if statement to test if the counter is even. If it is, print that

number.

// Outside of the if statement, increase the value of the variable by 1

}

// Print: There are your even numbers!

OUTPUT: (not entirely shown)

2

4

6

8

…….

46

48

50

There are your even numbers!

A6.3 Counting across and down

Write a program that counts to 100. The output should be in rows of 5 numbers as shown in the output.

PROGRAM STRUCTURE:

// Declare and initialize a variable with a value of 1

//while (condition for variable being less than or equal to 100)

{

// Work with tabs and new lines for proper formatting

// Hint: Use an if that checks for numbers that are divisible by 5. Modulus

is helpful here.

// Increment the value of the variable by 1.

}

OUTPUT: (not entirely shown)

1 2 3 4 5

6 7 8 9 10

11 12 13 14 15

……

96 97 98 99 100

A6.4 Count to 50

Use a for loop to count from 1 to 50 on the screen.

PROGRAM STRUCTURE:

(see example “Counter up to 5” above)

OUTPUT:

1

2

3

……

49

50

A6.5 Count to 210

Use a for loop to count from 3 to 210 by 3’s.

PROGRAM STRUCTURE:

(see example “Counter up to 5” above)

OUTPUT:

3

6

9

…..

207

210

A6.6 Line of stars

Ask the user for a number and then print that many stars on one line.

PROGRAM STRUCTURE:

(see example “Counter up to 5” above)

SAMPLE RUN #1:

How many stars would you like to print?

7

*******

SAMPLE RUN #2:

How many stars would you like to print?

20

********************

A6.7 Counting in a range with a While Loop

Ask the user for two numbers. Determine which is the higher and which is the lower number and count down from the higher number to the lower number using a while loop.

PROGRAM STRUCTURE:

// Declare five int variables: num1, num2, hiNum, lowNum and counter.

// Request two numbers from the user and assign them to num1 and num2.

// Determine which number is higher and assign it to hiNum. Assign the other one

// to lowNum. Assign counter to equal hiNum.

//while (condition for counter being higher or equal to lowNum)

{

// Print counter. Have the numbers print out with only a space between

// them.

// Increment counter by negative one

}

SAMPLE RUN #1:

Please give me a number between 1 and 100:

30

Please give me another number between 1 and 100:

41

41 40 39 38 37 36 35 34 33 32 31 30

SAMPLE RUN #2:

Please give me a number between 1 and 100:

50

Please give me another number between 1 and 100:

40

50 49 48 47 46 45 44 43 42 41 40

A6.8 Nested Loop

Create a program with nested loops that lists the value of the counter in each loop. i is the inner loop and j is the outer loop.

PROGRAM STRUCTURE:

for( ) // Create a counter “i” from 1 to 3 inclusive, counting by ones

{

for( ) // Create a counter “j” from 1 to 3 inclusive, counting by

ones

{

// Print to match the output

}

// Use layout properly here to match the desired output.

}

OUTPUT:

i = 1, j = 1

i = 1, j = 2

i = 1, j = 3

i = 2, j = 1

i = 2, j = 2

i = 2, j = 3

i = 3, j = 1

i = 3, j = 2

i = 3, j = 3

A6.9 Nested Loop Stars

Use nested loops to create the star pattern below. The outer loop counts the number of rows and the inner loop prints the stars in each row. (Hint: In row one, there is one star. In row two, there are two stars….)

PROGRAM STRUCTURE:

for(int row = 1; row <= 5; row++) // Keeps count of row number

{

for( ) // This is the tricky part

{

System.out.print("*");

}

// Something needs to go here for proper output

}

OUTPUT:

*

**

***

****

*****

A6.10 Multiplication Tables

Use a nested loop to create a multiplication table from 1 to 6.

OUTPUT:

1 2 3 4 5 6

2 4 6 8 10 12

3 6 9 12 15 18

4 8 12 16 20 24

5 10 15 20 25 30

6 12 18 24 30 36

Projects

Project 6.1: Guessing Game

Create a program that generates a random number from 1 to 100. It will then ask the player to guess the number. As the player guesses, they should be informed if they need to guess higher or lower. If they get the number, they should be told that they are correct and asked if they want to play the game again.

Sample output:

I have a number between 1 and 100. Please guess the number:

8

Guess higher:

45

Guess lower:

33

YOU GOT IT!

Would you like to play again? (1 - Yes, 2 - No)

1

I have a number between 1 and 100. Please guess the number:

…...

Would you like to play again? (1 - Yes, 2 - No)

2

Thanks for playing!

Project 6.2: Slot Machine

Create a program that acts like a slot machine. You start with $10 and each play is $1. The program should generate three random numbers from 1 through 9. If two of the numbers match, you get $3 back. If all three numbers match, you get $10 back. Be sure to give the player a running balance of how much money they have.

Sample run:

You have $10.

Press “p” to play the slots!

2 9 2

You won $3!

You now have $12.

Press “p” to play the slots!

1 8 3

You didn’t match any numbers.

You now have $11.

Press “p” to play the slots!

7 7 7

Woohoo! You won $10!

You now have $20.

Press “p” to play the slots!

……..

Project 6.3: Choice of Two Games

This assignment should not take too much work. If you don’t understand the simplicity of the project, see Mr. Finkel for a quick conceptual overview.

The goal is to combine the games from Project 6.1 and 6.2 into one program using methods. At the beginning of the program, the user will have the choice of which game to play. When one game is selected, a method that plays that game will be run. Once that game is finished, they will be sent back to the original menu with the offer to play either game.

SAMPLE RUN:

Would you like to play 1) Guess a number or 2) slots?

2

Welcome to SLOTS!!

You have $10.

Press “p” to play the slots, “q” to quit:

p

1 3 5

You didn’t match any numbers.

You now have $9.

Press “p” to play the slots, “q” to quit:

q

Would you like to play 1) Guess a number or 2) slots?

1

Welcome to GUESS A NUMBER!!

I have a number between 1 and 100. Please guess the number:

45

Guess higher:

91

Guess lower:

54

YOU GOT IT!

Would you like to play 1) Guess a number or 2) slots?

………….