4 LAB: Exact change Write a program with total change amount in pennies as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies.

The Correct Answer and Explanation is:
✅ Correct Java Code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int input = scnr.nextInt();
if (input <= 0) {
System.out.println("No change");
return;
}
int dollars = input / 100;
input %= 100;
int quarters = input / 25;
input %= 25;
int dimes = input / 10;
input %= 10;
int nickels = input / 5;
input %= 5;
int pennies = input;
if (dollars > 0) {
System.out.println(dollars + " " + (dollars == 1 ? "Dollar" : "Dollars"));
}
if (quarters > 0) {
System.out.println(quarters + " " + (quarters == 1 ? "Quarter" : "Quarters"));
}
if (dimes > 0) {
System.out.println(dimes + " " + (dimes == 1 ? "Dime" : "Dimes"));
}
if (nickels > 0) {
System.out.println(nickels + " " + (nickels == 1 ? "Nickel" : "Nickels"));
}
if (pennies > 0) {
System.out.println(pennies + " " + (pennies == 1 ? "Penny" : "Pennies"));
}
}
}
💡 300-
This Java program calculates the fewest number of coins needed to make up a given amount of pennies. The coin denominations used are Dollars (100¢), Quarters (25¢), Dimes (10¢), Nickels (5¢), and Pennies (1¢). The user inputs the total change in pennies, and the program outputs the count and name of each coin type, using singular or plural forms correctly.
The program begins by reading an integer input using a Scanner. If the input is 0 or less, it prints "No change" and ends early.
To compute the change:
- Dollars are calculated by dividing the input by 100.
- The remainder after removing dollars is used to calculate Quarters, and so on.
- The
%=operator is used to update the remaining cents after each coin type.
After computing the number of each coin, the program conditionally prints each coin only if its count is greater than 0. It uses a ternary operator to print the correct singular or plural form (e.g., "1 Penny" vs. "2 Pennies").
This approach ensures the user sees only the coin types that are needed and minimizes the number of coins used. The program also adheres to good programming practices by checking for edge cases (like zero input) and using clear, readable logic.
This lab strengthens skills in division, modulo operations, conditionals, and string formatting, which are key to solving real-world algorithmic problems.
