Monday, February 9, 2015

Currency Denomination

You will wonder once you realise how powerful this simple code is! Given an amount, this program will print the denomination for it. The reason this code became really compact is, it makes use of array.

Code

#include <stdio.h>

int main()
{
    int currencies[] = {1000, 500, 100, 50, 10, 5, 2, 1};
    long int amount;
    int buf, pos = 0;

    printf("Enter the amount: ");
    scanf("%ld", &amount);

    while(amount > 0)
    {
        buf = amount/currencies[pos];
        if(buf > 0)
            printf("%d X %d\n", currencies[pos], buf);
        amount -= currencies[pos]*buf;
        pos++;
    }

    return 0;
}

Output

Enter the amount: 2313
1000 X 2
100 X 3
10 X 1
2 X 1
1 X 1

No comments:

Post a Comment