Logic & Computation · Loops laboratory
One instruction. Many repetitions.
You have taught your programs to read, calculate, and make decisions. Now teach them to repeat. Start with ten small problems using familiar variables, conditionals, Scanner, and Random. Then tackle three extension problems that combine those skills and introduce a loop inside another loop.
Before you begin
- Create
LoopsLab.javafrom the starter below. Fill in your name and date. - Write each solution inside
main, below its matching problem label. Complete one problem, run it, and try its checks before moving on. - Use the loop type requested by each problem. Problems 1–6 use
for; Problems 7–9 usewhile; Problem 10 usesfor; Problems 11–12 usewhile; Problem 13 introduces nestedforloops. - Reuse the supplied
keyboardandrandomobjects. Keepkeyboard.close();after all solutions. - Use different names for variables declared directly inside
mainin different problems. A counter declared inside aforheader belongs to that loop. - Assume users enter the requested data type. For numeric inputs, you do not need to handle letters. Problems 8, 9, and 13 require retrying an unacceptable entry; follow each problem’s directions for any other repeated input.
- Use one loop at a time for Problems 1–12. In Problem 13, finish the input-validation loop first, then use one
forloop inside another. You do not need arrays, additional methods,break, orcontinue.
Remember: When you run the whole program, it will run earlier problems before the one you are testing. Type each requested answer in the terminal and press Enter. Example runs include the user’s typed responses; your code does not print those responses for them.
Part 1 notes · Read before Problems 1–6
Meet the for loop
A loop repeats a block of code. A for loop is convenient when you know how many repetitions you want, or which numbers you want to visit.
Read this example before beginning. Predict what it prints, then trace the changing value of round.
for (int round = 1; round <= 3; round++)
{
System.out.println("Practice round " + round);
}
| Part | What it does |
|---|---|
int round = 1 | Start the counter at 1. This happens once. |
round <= 3 | Check the condition before each repetition. If it is false, leave the loop. |
round++ | Add one after the body finishes, then check the condition again. |
The body prints rounds 1, 2, and 3. After the third repetition, the update makes round equal to 4. The condition is false, so there is no fourth repetition.
Keep track of what changes
| Code | Meaning |
|---|---|
count++; | Add one to count. This is the same as count = count + 1;. |
count--; | Subtract one from count. |
total = total + amount; | Add amount to the old total and store the new total. |
number % 2 == 0 | Check whether a number is even. |
Where does this line belong?: Initialize a running total or score before the loop, change it inside the loop, and print the finished result after the loop. A variable created inside the loop’s braces cannot be used outside those braces.
Braces and semicolons: Keep braces around the loop body and use Allman (ANSI) style, as shown above: the opening brace goes on the next line, and the closing brace lines up with it. The two semicolons belong inside a for header. Do not put a semicolon between the closing ) and the opening {.
Your familiar tools
| Expression | Use |
|---|---|
keyboard.nextInt() | Read an integer. |
keyboard.next() | Read one word. |
random.nextInt(6) + 1 | Generate an integer from 1 through 6. |
random.nextInt(10) + 1 | Generate an integer from 1 through 10. |
Need a refresher? Revisit the fundamentals lab’s Java cheat sheet.
Starter code
Copy this into LoopsLab.java. The filename must match public class LoopsLab. Replace each TODO comment with your solution; add lines as needed.
Already started? Keep your existing work. Add labels and solutions for Problems 11–13 after Problem 10 and before keyboard.close();. You do not need to copy the entire starter again.
/*
* Name:
* Project: The Computer Learns to Repeat!
* Date:
*/
import java.util.Scanner;
import java.util.Random;
public class LoopsLab
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
// START: Write each solution below its problem label.
System.out.println("Problem 1");
// TODO: The Computer Has Been Told Once
System.out.println("Problem 2");
// TODO: Counting Without Copy and Paste
System.out.println("Problem 3");
// TODO: You Decide When We Stop Counting
System.out.println("Problem 4");
// TODO: Even Steven and Odd Todd Take Attendance
System.out.println("Problem 5");
// TODO: The Computer Keeps a Running Total
System.out.println("Problem 6");
// TODO: A Die That Finally Rolls More Than Once
System.out.println("Problem 7");
// TODO: The Extremely Small Rocket Launch
System.out.println("Problem 8");
// TODO: The Computer Politely Insists
System.out.println("Problem 9");
// TODO: The Penguins Give You Another Chance
System.out.println("Problem 10");
// TODO: The Computer Gives You Three Homework Questions
System.out.println("Problem 11");
// TODO: The Computer Grades Until You Say Stop
System.out.println("Problem 12");
// TODO: The Secret Number Gives You Five Chances
System.out.println("Problem 13");
// TODO: The Penguins Build a Staircase
// END: Keep this line after all of your solutions.
keyboard.close();
}
}Keep the setup: The starter supplies the only Scanner and Random objects you need. Keep all your solutions above keyboard.close();.
Problems 1–6
Repeat a known number of times
Begin with small for loops, then reuse your familiar decisions, input, and random numbers.
1. The Computer Has Been Told Once
Use a for loop to print the sentence below exactly five times, with each repetition on its own line. Write the printing statement only once in your code. This problem does not need keyboard input.
Example output / run
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
I will save my Java file before running it.
Hint: Use a counter that starts at 1, continues through 5, and increases by one each time.
Check: Count the output lines. There should be five copies of the sentence, not four or six.
2. Counting Without Copy and Paste
Use a for loop to print the integers 1 through 10, inclusive, one per line. Your printing statement must use the loop’s counter variable. Write the printing statement only once.
Example output / run
1
2
3
4
5
6
7
8
9
10
Hint: In Problem 1 the message stayed the same. Here, print the variable that changes after each repetition.
Check: The first number should be 1, the last should be 10, and there should be ten numbers.
3. You Decide When We Stop Counting
Ask the user for an integer from 1 through 20. Store it, then use a for loop to print every integer from 1 through that number, inclusive.
Assume the input is in the requested range. You do not need a validation loop for this problem.
Example output / run
Enter a number from 1 through 20:
4
1
2
3
4
Hint: Read the endpoint once, before the loop, using keyboard.nextInt(). Use that stored value in the loop condition.
Check: Input 1 should print only 1. Input 4 should print four numbers. Input 20 should end at 20.
4. Even Steven and Odd Todd Take Attendance
Use a for loop to visit the integers 1 through 10. Inside the loop, use if / else to label each number as even or odd.
Print the number and its label together on one line. This problem does not need keyboard input.
Example output / run
1 is odd.
2 is even.
3 is odd.
4 is even.
5 is odd.
6 is even.
7 is odd.
8 is even.
9 is odd.
10 is even.
Hint: Reuse the % 2 test from the fundamentals lab. This time, test the loop counter. A remainder of 0 means the number is even.
Check: There should be ten labeled numbers: five even and five odd. The last line should be 10 is even.
5. The Computer Keeps a Running Total
Ask the user for an integer from 1 through 20. Use a for loop to add all integers from 1 through that number. Print the total after the loop finishes.
Assume the input is in the requested range. Use repeated addition in your loop rather than a sum formula. For input 4, the total is 1 + 2 + 3 + 4 = 10.
Example output / run
Enter a number from 1 through 20:
4
The total is 10.
Hint: Create an int total with the starting value 0 before the loop. Each repetition adds the current counter to the total. Do not reset the total inside the loop.
Check: Input 1 gives 1; input 5 gives 15; input 20 gives 210. Print the completed total once.
6. A Die That Finally Rolls More Than Once
Use a for loop to roll a six-sided die five times. On each repetition, generate a new value using random.nextInt(6) + 1, store it, and print it with the roll number.
This problem does not need keyboard input. Repeated results are normal.
One possible output
Roll 1: 4
Roll 2: 2
Roll 3: 2
Roll 4: 6
Roll 5: 1
Hint: Put the random-number generation inside the loop. Generating once before the loop and reusing that value would print the same stored roll five times.
Check: There should be five rolls labeled 1 through 5. Every die value must be between 1 and 6. Your results do not need to match the example.
Part 2 notes · Read before Problems 7–9
Meet the while loop
A while loop checks a condition before each repetition. It is useful when you want to keep going until something changes, such as a user finally entering an acceptable answer. It can also count, as in this example:
int round = 1;
while (round <= 3)
{
System.out.println("Practice round " + round);
round++;
}
This prints the same three practice rounds as the earlier for example. Here, the counter starts before the loop, and the update is written inside the body.
- Set up the value the condition will check.
- Check the condition. If it is false, skip the body and continue after the loop.
- If it is true, run the body. Change the counter or read a new input so the condition can eventually become false.
- Return to the condition and check again.
A loop can run zero times: If the first input is already acceptable, a retry loop should skip its body. There is no need to print an error or ask again.
Avoid an endless loop: If the value in the condition never changes, the loop may never stop. For a countdown, update the counter inside the loop. For a retry prompt, read the replacement answer inside the loop. If your program runs endlessly in the terminal, press Ctrl+C, then check the condition and update.
When you compare text
Use .equals() for String contents. The operator ! means “not.” For example, !word.equals("hello") is true when word is not "hello". Capitalization matters.
Before each problem, ask yourself: What repeats? What changes? What makes this loop stop?
Problems 7–9
Keep going while a condition is true
Practice a countdown, then teach your program to ask again when an answer is not accepted.
7. The Extremely Small Rocket Launch
Create an integer variable with the value 5. Use a while loop to print a countdown from 5 through 1, one number per line. After the loop, print Blast off!
This problem does not need keyboard input.
Example output / run
5
4
3
2
1
Blast off!
Hint: Decrease the countdown variable by one inside the loop. The condition should let the loop run while the number is greater than zero.
Check: Do not print 0. Print Blast off! exactly once, after the countdown. Be ready to explain why the loop stops.
8. The Computer Politely Insists
Ask the user to enter a positive integer. If they enter 0 or a negative integer, use a while loop to print an error message and ask again. Continue until the value is greater than zero.
After the loop, print the accepted number. Assume every entry is an integer; you do not need to handle letters or decimal entries.
Example output / run
Enter a positive integer:
0
That number must be greater than zero. Try again:
-3
That number must be greater than zero. Try again:
4
Accepted: 4
Hint: Read the first number before the loop. While it is invalid, print the retry prompt and read a replacement into the same variable. An unchanged invalid value would keep the loop running.
Check: Test 0, then -3, then 4 in one run. In a separate run, enter 4 first: accept it immediately without printing an error.
9. The Penguins Give You Another Chance
The secret-club password is still penguin, entirely in lowercase. Ask the user to enter a password, then use a while loop to keep asking until it is correct.
Print a rejection message and another prompt after each incorrect entry. After the loop, print Welcome to the secret club. once. All passwords are one word; there is no attempt limit.
Example output / run
Enter the password:
potato
The penguins do not recognize you. Try again:
Penguin
The penguins do not recognize you. Try again:
penguin
Welcome to the secret club.
Hint: Use keyboard.next() and .equals(). The operator ! means “not”: !password.equals("penguin") is true while the password is incorrect. Read a new password inside the loop.
Check: Test the correct password immediately, then test two incorrect entries followed by the correct one. Penguin is not accepted. The welcome message appears once.
Problem 10
Bring it all together
Build a short quiz from the tools you have practiced. Afterward, continue to the three extension problems.
10. The Computer Gives You Three Homework Questions
Turn the fundamentals lab’s addition question into a three-question quiz using a for loop.
- Generate two new random integers from 1 through 10 on each repetition.
- Display their addition question, including the question number.
- Read the user’s integer answer.
- Print whether it is correct. If it is wrong, show the correct answer.
- Add one to the score only when the answer is correct.
After all three questions, print the final score out of 3. Each question gets one answer; do not keep asking until the answer is correct. Repeated random questions are allowed.
One possible run
Question 1: What is 4 + 7?
11
Correct!
Question 2: What is 2 + 5?
6
Not quite! The correct answer is 7.
Question 3: What is 9 + 1?
10
Correct!
You answered 2 out of 3 correctly.
Hint: Set the score to zero before the loop. Generate and store both numbers inside the loop using random.nextInt(10) + 1. Reuse those stored numbers for the question and its answer. Print the final score after the loop.
Check: Try three correct answers for a score of 3, three deliberately incorrect answers for 0, and a mixed run. The program must ask exactly three questions.
Problems 11–13 · Extension challenges
Make your loops do more
These problems combine several familiar ideas. Build each solution in stages: get the loop working first, then add the decisions, calculations, and final output. Finish Problems 1–10 before beginning these extensions.
11. The Computer Grades Until You Say Stop
Your program does not know how many quiz scores the user wants to enter. Use a while loop to keep reading integer scores from 0 through 100. The user enters -1 to finish.
- Ask for the first score before the loop.
- For each score other than
-1, add it to a running total and increase the number of scores entered by one. - Ask for the next score inside the loop. Stop when the user enters
-1. - After the loop, print the number of scores and their total. If at least one score was entered, also print the average as a
double. Otherwise, printNo scores were entered.instead of calculating an average.
Assume each entry is either a score from 0 through 100 or -1; no range-validation loop is needed. A score of 0 counts as a score. The stopping value -1 does not count and must not be added to the total.
Example output / run
Enter a score from 0 through 100, or -1 to finish:
70
Enter a score from 0 through 100, or -1 to finish:
85
Enter a score from 0 through 100, or -1 to finish:
90
Enter a score from 0 through 100, or -1 to finish:
-1
Scores entered: 3
Total: 245
Average: 81.66666666666667
Two new details: A special value used to end input is called a sentinel. Also, dividing one int by another drops the fractional part. With integer variables named scoreTotal and scoreCount, use scoreTotal / (double) scoreCount to keep the decimal part. Only calculate this when scoreCount > 0. You do not need to round the average.
Build it in stages: First, make the input loop stop at -1. Next, add a total and a count that both start at zero before the loop. Finally, use if / else after the loop to handle the average or the no-scores message. Think carefully about where the next input belongs so that the sentinel is never processed as a score.
Check: Try 70, 85, 90, -1 for a count of 3 and a total of 245. Try 80, 81, -1 for an average of 80.5. Try 0, -1: one score, total 0, average 0.0. Finally, enter -1 first: count 0, total 0, and the no-scores message with no division.
12. The Secret Number Gives You Five Chances
The computer chooses one secret integer from 1 through 20. The user has at most five guesses to find it. Use a while loop for the guessing game.
- Generate the secret number once, before the loop, using
random.nextInt(20) + 1. Keep the same secret throughout the game. - Show the attempt number, then read one integer guess. Assume guesses are within 1 through 20; you do not need input validation.
- Count every guess, including a correct guess, as one attempt.
- For an incorrect guess, print
Too low!orToo high!. - Stop asking as soon as the user guesses correctly or uses all five attempts. Do not use
break. - After the loop, print a success message with the number of guesses used, or a game-over message revealing the secret number.
One possible run (the secret number happens to be 12)
I chose a number from 1 through 20. You have five guesses.
Guess 1:
8
Too low!
Guess 2:
16
Too high!
Guess 3:
12
You found it in 3 guess(es)!
Keep going only while both conditions are true: The secret has not been guessed and fewer than five attempts have been used. The operator && means “and.” The operator != means “not equal.” A correct answer on guess 5 still wins.
Build it in stages: Start an attempt counter at 0 and a guess variable at 0 before the loop. Zero cannot equal the secret, so the first guess can happen. Each repetition increases the attempt counter, prints that attempt number, and reads a new guess. Use the two conditions above to decide whether another repetition is allowed. After the loop, check whether the final guess equals the secret to choose the ending message.
Check: Temporarily use a fixed secret of 12 so you can test reliably. Try 12 first: win in one guess. Try 1, 2, 3, 4, 12: win on guess 5. Try 1, 2, 3, 4, 5: stop after five guesses and reveal 12. Try a value above 12 to check the “too high” message. There must never be a sixth prompt. Restore the random expression before submitting.
Part 4 notes · Read before Problem 13
A loop inside a loop
A nested loop is a loop inside another loop’s body. The inner loop runs all the way through for each repetition of the outer loop. Think of arranging seats: the outer loop chooses the row, and the inner loop visits the seats in that row.
Read this small example. It uses two rows and three seats per row:
for (int row = 1; row <= 2; row++)
{
for (int seat = 1; seat <= 3; seat++)
{
System.out.print("(" + row + "," + seat + ") ");
}
System.out.println();
}
Output
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
System.out.print(...)prints without moving to a new line. The space at the end separates the seats.System.out.println();moves to a new line without printing any text. Here, it belongs after the inner loop, but inside the outer loop.- The inner counter starts at
1again each time the outer loop begins a new row. For row 1, the seat values are 1, 2, 3; then row 2 gets its own seat values 1, 2, 3. - The inner printing statement runs
2 × 3 = 6times in total. The new-line statement runs twice.
Before you code: Trace the example on paper. What would happen if you moved System.out.println(); inside the inner loop? In the staircase below, each row needs a different number of symbols, so the inner loop’s endpoint will depend on the current row.
13. The Penguins Build a Staircase
The penguins want a staircase made of asterisks. Ask the user for an integer height from 1 through 8. Use a while loop to reject heights outside that range and ask again.
Once the height is accepted, use nested for loops to print a left-aligned staircase:
- The outer loop creates one row at a time, from row 1 through the chosen height.
- The inner loop prints one
*at a time. Row 1 has one star, row 2 has two, and so on. Do not put spaces between the stars. - Move to a new line only after a complete row has been printed.
- Count every star as it is printed. After the entire staircase, print the total number of stars.
Use a single System.out.print("*"); statement inside the inner loop. Do not write separate printing statements for each row, use String.repeat(), or use a formula to calculate the star total. Finish input validation before starting the two drawing loops.
Example output / run
Enter a staircase height from 1 through 8:
0
Height must be from 1 through 8. Try again:
4
*
**
***
****
Total stars: 10
Build it in stages: First, adapt Problem 8 to reject a value that is less than 1 or greater than 8; || means “or.” Then use the seat example to print a small rectangle. For the staircase, change the inner loop’s endpoint so it uses the current row number. Finally, set a star counter to zero before the outer loop and increase it inside the inner loop, alongside the printing statement.
Check: Height 1 produces one row and 1 star total. Height 4 produces four rows and 10 stars total. Height 8 produces eight rows and 36 stars total. In one run, enter -2, then 9, then 3: reject the first two entries, then print three rows with 6 stars total. Explain why the inner loop prints more stars on each new row.
Before submitting
- Fill in your name and date at the top of
LoopsLab.java. - Complete all thirteen problems using the requested loop types. Keep each problem’s output clearly labeled.
- Try every problem’s checks. Confirm that fixed loops run the correct number of times.
- For Problems 8 and 9, test both an immediately accepted answer and incorrect answers followed by a correct one.
- Initialize totals and counters before the loops that update them so they are not reset on every repetition. In Problem 13, the star total belongs before the outer loop.
- For Problem 11, test the stopping value as the very first entry and confirm that a score of zero still counts.
- For Problem 12, test a correct first guess, a correct fifth guess, and five incorrect guesses. Confirm that no sixth guess is requested.
- For Problem 13, test invalid heights and the smallest and largest valid heights. Check the row lengths and the total stars.
- Make sure random values are generated where the directions request them. Restore random expressions if you temporarily used fixed values for testing.
- Be ready to explain one
forloop and onewhileloop: what repeats, what changes, and why it stops. For Problem 13, also explain how the inner loop depends on the outer loop.
Submit your completed LoopsLab.java file to [email protected].