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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,023 questions

51,974 answers

573 users

How to find the total number of combinations of given coins to reach a specific amount in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
 
// Function to find the total number of combinations to make amount
long totalCombinations(int coins[], int num_coins, int amount) {
    long *arr = (long *)malloc((amount + 1) * sizeof(long));
    if (arr == NULL) {
        printf("Memory allocation failed.\n");
        return -1;
    }
 
    // Initialize the array to 0
    for (int i = 0; i <= amount; i++) {
        arr[i] = 0;
    }
 
    // Base case: There is one way to make an amount of 0 (using no coins)
    arr[0] = 1;
 
    // Iterate through all coins one by one
    for (int i = 0; i < num_coins; i++) {
        for (int j = coins[i]; j <= amount; j++) {
            arr[j] += arr[j - coins[i]];
        }
    }
 
    long result = arr[amount];
    free(arr); 
     
    return result;
}
 
int main() {
    int coins[] = {1, 2, 5}; 
    int num_coins = sizeof(coins) / sizeof(coins[0]);
    int amount = 6;
    
    // [1, 5], [1, 1, 1, 1, 1, 1], [2, 2, 2], [1, 1, 1, 1, 2], [2, 2, 1, 1]
    
    printf("For amount = %d and coins = {1, 2, 5}:\n", amount);
    printf("Total combinations: %ld\n\n", totalCombinations(coins, num_coins, amount));
 
    int coins2[] = {2, 5, 10};
    int num_coins2 = sizeof(coins2) / sizeof(coins2[0]);
    amount = 10;
    
    // [5, 5], [2, 2, 2, 2, 2], [10]
 
    printf("For amount = %d and coins = {2, 5, 10}:\n", amount);
    printf("Total combinations: %ld\n", totalCombinations(coins2, num_coins2, amount));
 
    return 0;
}
 
 
 
/*
run:
   
For amount = 6 and coins = {1, 2, 5}:
Total combinations: 5

For amount = 10 and coins = {2, 5, 10}:
Total combinations: 3
 
*/




answered Nov 5, 2025 by avibootz
edited Nov 6, 2025 by avibootz
...