cs50 psets1 cash problem(2022)

The solution to CS50 psets 1 cash problem (2022)

Hello friends, In this post, I’m giving you my solution to the CS50 problem set 1 cash problem. So in this program, we have to implement a solution that prompts users for the number of cents that a customer is owed and prints the smallest number of coins with which that change can be made.

The main function is already implemented for us. The following code shows how I resolve this problem, Hope it helps you!

#include <cs50.h>
#include <stdio.h>

int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);

int main(void)
{
    // Ask how many cents the customer is owed
    int cents = get_cents();

    // Calculate the number of quarters to give the customer
    int quarters = calculate_quarters(cents);
    cents = cents - quarters * 25;

    // Calculate the number of dimes to give the customer
    int dimes = calculate_dimes(cents);
    cents = cents - dimes * 10;

    // Calculate the number of nickels to give the customer
    int nickels = calculate_nickels(cents);
    cents = cents - nickels * 5;

    // Calculate the number of pennies to give the customer
    int pennies = calculate_pennies(cents);
    cents = cents - pennies * 1;

    // Sum coins
    int coins = quarters + dimes + nickels + pennies;

    // Print total number of coins to give the customer
    printf("%i\n", coins);
}

int get_cents(void)
{
    int cents;

    do {
        cents = get_int("Change Owed: ");
    } while (cents < 0);

    return cents;
}

int calculate_quarters(int cents)
{
    int quarters = cents / 25;
    return quarters;
}

int calculate_dimes(int cents)
{
    int dimes = cents / 10;
    return dimes;
}

int calculate_nickels(int cents)
{
    int nickels = cents / 5;
    return nickels;
}

int calculate_pennies(int cents)
{
    int pennies = cents / 1;
    return pennies;
}

You may also like to read: The solution to CS50 Psets 2 Caesar Problem (2022)

(Visited 46 times, 1 visits today)

One comment

Leave a Reply