Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,943 questions

55,787 answers

573 users

How to divide a given amount into bills (banknotes) and coins in C#

1 Answer

0 votes
using System;
using System.Linq;

class Program
{
    /*
     * Function: DivideAmount
     * ----------------------
     *  Given an amount and a list of bills/coins, prints how many
     *  of each denomination are needed using a greedy algorithm.
     *
     *  The greedy method is optimal for standard currency systems.
     */
    static void DivideAmount(int amount, int[] denominations)
    {
        Console.WriteLine($"Dividing amount: {amount}\n");

        foreach (int d in denominations)
        {
            int count = amount / d;   // how many of this denomination
            if (count > 0)
            {
                Console.WriteLine($"{d}-unit: {count}");
                amount %= d;          // reduce remaining amount
            }
        }

        if (amount > 0)
        {
            Console.WriteLine($"\nWarning: leftover amount = {amount}");
        }
    }

    static void Main()
    {
        int[] bills_coins = { 500, 100, 200, 50, 20, 10, 5, 2, 1 };

        // C#: sort descending using LINQ
        int[] denominations = bills_coins
                                .OrderByDescending(x => x)
                                .ToArray();

        int amount = 9749;

        DivideAmount(amount, denominations);
    }
}


/*
run:

Dividing amount: 9749

500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2

*/

 



answered Jan 9, 2022 by avibootz
edited Jul 26 by avibootz
...