Objective
Write a C# program to give change for a purchase, using the largest possible coins (or bills). Suppose we have an unlimited amount of coins (or bills) of 100, 50, 20, 10, 5, 2, and 1, and there are no decimals. Therefore, the execution could be something like this:
Price? 44
Paid? 100
Your change is 56: 50 5 1
Price? 1
Paid? 100
Your change is 99: 50 20 20 5 2 2
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace, which contains fundamental classes like Console
class Program // Define the Program class
{
static void Main() // The entry point of the program
{
// Ask the user for the price of the item
Console.Write("Price? ");
int price = int.Parse(Console.ReadLine()); // Read and convert the price to an integer
// Ask the user for the amount paid
Console.Write("Paid? ");
int paid = int.Parse(Console.ReadLine()); // Read and convert the paid amount to an integer
// Calculate the change to be returned
int change = paid - price; // Subtract the price from the paid amount to calculate the change
// Display the total change to be returned
Console.WriteLine($"Your change is {change}:");
// Define an array of available coin and bill denominations
int[] denominations = { 100, 50, 20, 10, 5, 2, 1 }; // Coins and bills in descending order
// Iterate through the denominations array
foreach (int denomination in denominations)
{
// Calculate how many coins/bills of this denomination can be given as change
while (change >= denomination)
{
Console.Write(denomination + " "); // Display the current denomination
change -= denomination; // Subtract the denomination from the remaining change
}
}
// Print a newline after displaying the change
Console.WriteLine();
}
}