Skip to main content

Section 2.32 Unit 2B Projects

These projects were created by Leigh Anne Fitz and Lisa Ferran to provide engaging, standards-aligned learning experiences for AP Computer Science A students.
Now that your programs can make decisions, it’s time to make them repeat those decisions efficiently. In these projects, you’ll explore how loops allow programs to execute instructions multiple times without writing the same code over and over. You’ll use iteration to solve problems, process data, and build algorithms that are both efficient and easy to maintain.
Each project is designed to reinforce these concepts through authentic programming tasks. As you complete them, focus on recognizing patterns, choosing the appropriate type of loop, and tracing your algorithms to ensure they repeat the correct number of times. Great programmers know that well-designed loops make programs more powerful, flexible, and efficient.

Subsection 2.32.1 Review: Using for Loops to Repeat Code

A for loop is used when you know how many times you want a section of code to repeat. The loop uses a counter variable that keeps track of the number of repetitions. The general structure of a for loop is:
for (initialization; condition; update) {
    // code that repeats
}
Example: Loop 5 times and print a message each time:
for (int i = 0; i < 5; i++) {
    System.out.println("Hello!");
}
How it works:
  • int i = 0 creates the counter and starts it at 0.
  • i < 5 keeps the loop running while i is less than 5.
  • i++ increases the counter by 1 after each repetition.
The loop above runs when i is 0, 1, 2, 3, and 4 - a total of 5 times.

Activity 2.32.1.

The variable num stores the number of times a loop should repeat. Which for loop header correctly repeats a block of code num times?
  • for (int i = 1; i < num; i++)
  • The counter starts at 1 instead of 0. How many values are there from 1 up to (but not including) num?
  • for (int i = 0; i <= num; i++)
  • The condition uses <=, which includes the value num. This causes the loop to run one extra time.
  • for (int i = 0; i < num; i++)
  • The loop starts with i = 0 and continues while i < num. The counter values are: 0, 1, 2, ..., num - 1. This produces exactly num repetitions.
  • for (int i = num; i >= 0; i--)
  • This loop starts at i = num and goes down to 0. Since 0 is included, how many times is it looping?

Subsection 2.32.2 Unit 2B Project 1 - Grades

Activity 2.32.2.

Write a program that allows the user to input the number of grades he or she wants to be averaged. Then use a for loop structure to have the user input all the test grades individually, calculating the sum of these grades as they are being entered. These amounts, including the sum, are to be all ints. After all the grades have been entered, the program will calculate the average (what data type should this variable be?). Print out the average for the number of grades entered.

Subsection 2.32.3 Review: Using while Loops

A while loop repeats a section of code as long as a condition is true. While loops are useful when you do not know exactly how many times a loop will repeat.
A sentinel value is a special value that tells a program when to stop repeating. The sentinel value is not usually processed as regular data.
Example: Continue entering names until the user enters "Q":
String name = input.nextLine();

while (!name.equals("Q"))
{
  System.out.println("Hello " + name);
  name = input.nextLine();
}
The loop continues until the user enters the sentinel value "Q".

Activity 2.32.3.

Which condition should be used to continue a loop that asks the user for numbers until they enter -1?
  • while (number == -1)
  • This condition only runs when the user enters the stopping value. The sentinel value should end the loop, not continue it.
  • while (number != -1)
  • The loop should continue while the user has not entered the sentinel value. Since -1 indicates that the user wants to stop, the condition should check: number != -1. The loop will repeat for all other numbers and stop when number becomes -1.
  • while (number < -1)
  • Consider whether all valid inputs will be less than -1. The loop should continue for most values except the sentinel.
  • while (number > -1)
  • This condition would prevent the loop from running for many possible valid inputs. Think about what value should cause the loop to stop.
A validation loop repeatedly asks for input until the user provides an acceptable value. This helps prevent invalid data from entering a program.
Example: Require a number between 1 and 100:
int score = input.nextInt();

while (score < 1 || score > 100)
{
  System.out.println("Invalid score. Try again.");
  score = input.nextInt();
}
The loop continues while the input is invalid and stops when the input is acceptable.

Activity 2.32.4.

A program requires the user to enter a positive number. Which loop correctly validates the input?
  • while (number > 0)
  • This condition is true for valid input. A validation loop should repeat when the input is incorrect.
  • while (number == 0)
  • This only catches one invalid value. What about negative numbers?
  • while (number <= 0)
  • The loop should continue while the input is invalid. A positive number must be greater than 0, so values that are invalid are: 0 and Negative numbers. The condition: while (number <= 0) keeps asking for input until the user enters a valid positive number.
  • while (number != 0)
  • This condition would reject all nonzero numbers, including valid positive numbers.
The String.format() method can be used to display a double value with a specific number of decimal places. To format a number to two decimal places, use: String.format("%.02f", number)
  • %f indicates that the value is a floating-point number (double).
  • .02 specifies that exactly two digits should appear after the decimal point.
Example:
double price = 12.5;

System.out.println(String.format("%.02f", price));

// Output:  12.50
The original value is not changed; String.format() only controls how the value is displayed.

Subsection 2.32.4 Unit 2B Project 2 - Concert Tickets (Loop)

Recall the Concert Tickets program from Unit 2A where the user chooses a seat based on the location with the costs listed below (remember that these values should be used as ints).
Seat location     Concert ticket price ($)
B (box)           $75
P (pavillion)     $30
L (lawn)          $21
This will be a similar situation where the user will enter an upper or lowercase B, P, or L to choose a seat. Include the following:
  • Allow the user to continue buying tickets (one at a time). At the end of the loop, ask the user if they would like to purchase another ticket. Y for yes, and N for No.
  • When prompting the user for a ticket type, if the user inputs an invalid type, use a loop to prompt the user to keep entering a seat type until a valid input is received.Β  This is to be done with a while data verification loop.
  • Keep a running total of the number of each type of ticket purchased and the subtotals for the costs of each type of ticket (these will need to be stored as ints)
  • Calculate a convenience fee of $1.50 per ticket (this will need to be a double).
  • Calculate the total cost of all tickets, including the convenience fee (this will need to be a double).
After all tickets have been purchased, display the quantity and type of each ticket bought with a subtotal, the total convenience fee, and a total price for all the tickets.
Example output:
2   box tickets         $150
4   pavillion tickets   $120
1   lawn tickets        $21
    Convenience fee     $10.50
    Total               $301.50
*Be sure to put a $ in front of all monetary amounts, and be sure to use String formatting on the convenience fee and total so that you will ensure two decimal places.

Activity 2.32.5.

Modify and expand the Unit 2A Concert Tickets program to process multiple ticket orders iteratively. Implement a loop allowing the user to purchase tickets one at a time until they choose to stop, enforce input validation for seat selections using a while loop, track counts and subtotals for each ticket type, apply a per-ticket convenience fee, and present an itemized final receipt with properly formatted currency values.
Please refer to the detailed requirements above for specific pricing, variable types, and formatting guidelines when writing your solution.
You have attempted of activities on this page.