Return to Java with the tools you used in Loops Lab. Start by reading input, keeping a total, and making a decision. Then use loops to test divisors, update sequences, and build rows of multiples.
Four class periods · Twelve required activities · Optional extensions
Before you begin
Open your Java project in VS Code. Save the starter in src as Assignment2.java, fill in your name and date, and run it once. You should see the twelve activity labels. If you started from the earlier version, keep your work and match it to the new labels by title.
Keep your solutions in main, below their matching labels. Use the supplied keyboard for input and leave keyboard.close(); at the end. Give variables declared directly in main distinct names across activities.
Assume input has the requested type. Read integers with keyboard.nextInt() and reject out-of-range values where an activity asks you to. Use variables, conditionals, and loops for the required activities.
Choose a for or while loop where you need repetition. Before you code, ask yourself what repeats, what changes, and what makes the loop stop.
Quick refresher: Revisit Loops Lab’s running total and input retry. Trace a total for input 4, then explain what happens if the first value entered is already valid. A counting loop has an endpoint. A retry loop checks the entry again after reading a replacement.
When you run the whole file, the activities run in order. In the example runs, the line immediately after each input prompt shows what you type. When testing a later activity, you may temporarily comment out earlier completed sections. Keep all your solutions in the submitted file.
Starter code
/*
* Name:
* Project: Assignment 2 - Loops
* Date:
*/
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Activity 1: Sum of odd numbers");
// TODO: Write Activity 1 here.
System.out.println("Activity 2: Leap year");
// TODO: Write Activity 2 here.
System.out.println("Activity 3: Score report");
// TODO: Write Activity 3 here.
System.out.println("Activity 4: Positive divisors");
// TODO: Write Activity 4 here.
System.out.println("Activity 5: Prime number");
// TODO: Write Activity 5 here.
System.out.println("Activity 6: Later multiples");
// TODO: Write Activity 6 here.
System.out.println("Activity 7: Fibonacci");
// TODO: Write Activity 7 here.
System.out.println("Activity 8: Digit sum");
// TODO: Write Activity 8 here.
System.out.println("Activity 9: Collatz");
// TODO: Write Activity 9 here.
System.out.println("Activity 10: Divide out one prime");
// TODO: Write Activity 10 here.
System.out.println("Activity 11: Multiplication grid");
// TODO: Write Activity 11 here.
System.out.println("Activity 12: Multiples by base");
// TODO: Write Activity 12 here.
// If you try an extension, label it and put it here.
keyboard.close();
}
}
Day 1
Review input, loops, and decisions
Start with the refresher above. Then work through a running total, a divisibility rule, and a score report.
Input validation · Running total
1. Sum of odd numbers
Ask for an integer n from 1 through 1000. If the entry is outside that range, print an error and ask again until it is valid. Then use a loop to add the odd numbers from 1 through 2 * n + 1, including both endpoints. Print the upper endpoint and the final sum.
Example run
Enter an integer from 1 through 1000:
0
That number is out of range. Try again:
3
The sum of the odd numbers from 1 through 7 is 16.
Build it in stages. First get the sum working with a valid entry. Start the total at zero and add each odd number inside the loop. Then add the retry loop before the summing loop.
Check. Try 1 for a sum of 4 and 1000 for 1002001. Try 0, then 1001, then 3 in one run. Only the last entry should be accepted.
Input validation · Divisibility · Boolean logic
2. Is it a leap year?
Ask for a positive integer year. If the entry is zero or negative, print an error and ask again until it is valid. A year divisible by 400 is a leap year. A year divisible by 100 but not 400 is not. For other years, divisibility by 4 decides. Print the year and whether it is a leap year.
Example run
Enter a positive integer year:
1900
The year 1900 is not a leap year.
Before you code. For each year below, decide which rule settles the question. You can express the rules with an if / else chain or a compound Boolean condition.
Check.2023 and 1900 are not leap years. 2024 and 2000 are. Try 0 followed by 2024 to check the retry.
Fixed repetitions · Counter · Maximum
3. Make a score report
Ask how many quiz scores will be entered, from 1 through 8. Read that many scores, each from 0 through 100. Assume all entries are in range. Print how many scores are at least 70 and print the highest score.
Example run
How many scores?
4
Enter score 1:
70
Enter score 2:
45
Enter score 3:
92
Enter score 4:
69
Scores at or above 70: 2
Highest score: 92
Plan the updates. Keep a count and a highest score. On each repetition, decide separately whether the score increases the count and whether it changes the highest score.
Check. A single score of 0 gives a count of 0 and a highest score of 0. Scores 69 and 70 give a count of 1 and a highest score of 70.
Day 2
Work with divisors and multiples
Compare two loop jobs. A divisor search checks candidates. A multiples loop can step directly from one result to the next.
Counting loop · Remainder · Inclusive endpoints
4. List the positive divisors
Ask for an integer from 1 through 100. Assume the entry is in range. Use a loop to test the integers from 1 through the input. Print each divisor on its own line in increasing order, then print the number of divisors.
Example run
Enter an integer from 1 through 100:
12
Divisors:
1
2
3
4
6
12
Divisor count: 6
Plan the test. What remainder tells you that a candidate divides the input evenly? Which candidates should increase the counter?
Check. Input 1 has just one divisor. Input 13 has two, 1 and 13. Input 16 has five, and 4 should appear once.
Divisibility · Loop bounds · Boolean state
5. Is it prime?
Read an integer and print whether it is prime. A prime is an integer greater than 1 whose only positive divisors are 1 and itself. Any input less than 2 is a valid entry and should be reported as not prime.
For numbers at least 2, use a loop to search for a divisor other than 1 or the number itself. A straightforward scan from 2 through the number minus 1 is enough. After the search, report the result once.
Example run
Enter an integer:
25
The number 25 is not prime.
Plan the search. What can you remember in a variable once you find a divisor? What should happen for 2, when the loop has no candidates to test?
Check.-3, 0, 1, and 25 are not prime. 2 and 29 are prime.
Counting loop · Starting value · Step size
6. Print the later multiples
Read a base from 2 through 10 and a limit from 2 through 100. Assume both entries are in range. Print each multiple of the base that is greater than the base and at most the limit. Start at twice the base and advance by the base each time. Print the number of multiples found, even if it is zero.
Example run
Enter a base from 2 through 10:
4
Enter a limit from 2 through 100:
16
Multiples after 4:
8
12
16
Count: 3
Trace the bounds. With base 4, write the first three values the loop would try. Which condition includes a multiple equal to the limit?
Check. Base 4 with limit 15 gives 8 and 12. Base 4 with limit 7 gives no multiples and a count of 0. Base 2 with limit 4 gives exactly one multiple, 4.
Day 3
Keep track of changing values
Trace the first few Fibonacci terms together. Then practice loops that update a number’s digits or its current value until a condition is met.
Input validation · Loop bounds · Updating two values
7. Find a Fibonacci term
Ask for a term number from 1 through 20. If the entry is outside that range, print an error and ask again. The first two terms are both 1. Each later term is the sum of the previous two, so the sequence begins 1, 1, 2, 3, 5, 8, 13, 21. Use a loop to compute the requested term and print its value.
Example run
Enter a term number from 1 through 20:
8
Term 8 is 21.
Trace it first. On paper, fill in the two previous terms and the new term for each row. When you update your variables, think about which old value you still need.
Fibonacci trace to complete before coding
Term to find
Older term
Newer term
New term
3
1
1
2
4
___
___
___
5
___
___
___
Check. Terms 1 and 2 are both 1. Term 8 is 21 and term 20 is 6765. Try 21 followed by 8 to check the retry.
While loop · Integer division · Running total
8. Add the digits
Read an integer from 0 through 100000. Assume it is in range. Use a loop to add its decimal digits. Work with a copy of the input so you can print the original number and the sum at the end.
Example run
Enter an integer from 0 through 100000:
5072
The digits of 5072 sum to 14.
Trace one update. For a nonnegative integer, % 10 gives the last digit and integer division by 10 removes it. Apply both operations to 5072 on paper before writing the loop condition.
Ask for a starting integer from 1 through 100. For this activity, assume it is in range. Print Sequence: and the starting value on separate lines, then keep updating the current value until it reaches 1.
If the current value is even, divide it by 2.
If the current value is odd, multiply it by 3 and add 1.
Print each new value on its own line. Count one step for each update and report the total after reaching 1. Printing the starting value takes zero steps.
Example run
Enter a starting integer from 1 through 100:
5
Sequence:
5
16
8
4
2
1
Steps: 5
Plan the loop. Decide what you will print before, during, and after the loop. Where will the program check whether the current value is even?
Check. Start at 1 for zero steps, 2 for one step, and 7 for sixteen steps. Each sequence should end with 1.
Day 4
Build rows with nested loops
Start with repeated division. For the last two activities, review the nested-loop example in Loops Lab. Trace the outer and inner counters for a two-row grid before you code.
While loop · Divisibility · Step counter
10. Divide out one prime
Read an integer from 1 through 10000 and choose 2, 3, 5, or 7 as the prime to test. Assume both entries meet these rules. As long as the current value is divisible by the chosen prime, divide by it and count the division. Print the number of divisions and the value left over.
Example run
Enter an integer from 1 through 10000:
72
Choose 2, 3, 5, or 7:
2
Divisions by 2: 3
Value left: 9
Trace the stopping test. Start with 72 and 2. After each successful division, test the new value for divisibility before dividing again.
Check. Try 81 with 3 for four divisions and a value of 1. Try 14 with 3 for zero divisions and a value of 14. Starting at 1 always takes zero divisions.
Nested loops · Row and column bounds
11. Print a multiplication grid
Read a row count and a column count, each from 1 through 6. Assume both entries are in range. Use nested loops to print a grid of products. Number the rows and columns starting at 1. Each entry is its row number times its column number. Put spaces between products and end the line after each row.
Example run
How many rows?
2
How many columns?
4
1 2 3 4
2 4 6 8
Plan one row. Decide which counter stays fixed while you print a row. After printing that row, the next row should start back at column 1.
Check. A 1-by-1 grid prints just 1. A 4-by-2 grid has four lines, with 4 8 on the last line.
Nested loops · Changing start and step
12. Put multiples on separate rows
Read a largest base from 2 through 6 and a limit from 2 through 30. Assume both entries are in range. Use nested loops to print one row for each base from 2 through the largest base. Start the row with its label, such as Base 2:. Then, on that same row, print its later multiples using Activity 6’s rule. Leave the label by itself if that base has no later multiples within the limit.
A number can appear in more than one row. For example, 12 is a later multiple of 2, 3, and 4.
Example run
Enter the largest base:
4
Enter the limit:
12
Base 2: 4 6 8 10 12
Base 3: 6 9 12
Base 4: 8 12
Build from Activity 6. Get one row working first. Then let an outer loop choose each base. When the base changes, what happens to the inner loop’s starting value and step size?
Check. With largest base 3 and limit 5, the first row is Base 2: 4 and the second is just Base 3:. With largest base 2 and limit 4, there is one row, Base 2: 4.
Optional
Extension challenges
Choose an extension after completing the required activities.
Check for primes with fewer tests
Try a smaller upper limit for your divisor search in Activity 5. Explain why you can stop there, and compare how many tests the two versions make for 29 and 49.
Compare the ends of a word
Read one lowercase word with keyboard.next() and use a loop to determine whether it reads the same forward and backward. Use length() to find the word’s length and charAt(i) to read a character. The first position is 0 and the last is length() - 1.
Check. Try level, noon, java, and a.
Find a GCD, then an LCM
Read two positive integers from 1 through 100. Assume both are in range. First, use a loop to find the greatest common divisor, the largest positive integer that divides both inputs evenly. Then find the least common multiple, the smallest positive number that is a multiple of both inputs. Start by checking multiples of one input, or investigate how the two answers are related.
Check.24 and 32 have GCD 8 and LCM 96. Also try equal inputs and two inputs that share no factor greater than 1.
Bonus challenge. After you have a working GCD solution, look up Euclid’s algorithm. Implement it and compare how many loop iterations the two approaches need for the same inputs.
Before submitting
Fill in your name and date. Keep all twelve required solutions in Assignment2.java.
Run each activity’s checks, including a rejected entry followed by a valid entry where validation is required.
Be ready to trace one of your loops and explain what changes and why it stops. For Activity 12, explain how the base controls the inner loop.