C Program Coin Change

In this problem, we are given a value n, and we want to make change of n rupees using a given set of coin denominations. We need to return the total number of ways to make the sum using these coins.

Syntax

int coinChange(int coins[], int numCoins, int amount);

Example Input/Output

Input: N = 6, coins = {1, 2, 4}
Output: 6
Explanation: The total combinations that make the sum of 6 are:
{1,1,1,1,1,1}, {1,1,1,1,2}, {1,1,2,2}, {1,1,4}, {2,2,2}, {2,4}

Method: Dynamic Programming

We use a 2D DP table where table[i][j] represents the number of ways to make amount i using the first j coin types −

#include <stdio.h>

int coinChange(int coins[], int m, int n) {
    int i, j, x, y;
    int table[n+1][m];
    
    /* Initialize base case: one way to make 0 amount */
    for (i = 0; i < m; i++)
        table[0][i] = 1;
    
    /* Fill the DP table */
    for (i = 1; i < n+1; i++) {
        for (j = 0; j < m; j++) {
            /* Include current coin if possible */
            x = (i - coins[j] >= 0) ? table[i - coins[j]][j] : 0;
            
            /* Exclude current coin */
            y = (j >= 1) ? table[i][j-1] : 0;
            
            table[i][j] = x + y;
        }
    }
    return table[n][m-1];
}

int main() {
    int coins[] = {1, 2, 3};
    int m = sizeof(coins) / sizeof(coins[0]);
    int amount = 4;
    
    int ways = coinChange(coins, m, amount);
    printf("Number of ways to make %d using given coins: %d<br>", amount, ways);
    
    return 0;
}
Number of ways to make 4 using given coins: 4

How It Works

  • We create a 2D table where table[i][j] stores ways to make amount i using first j coin types
  • Base case: There's exactly one way to make amount 0 (use no coins)
  • For each amount and coin combination, we either include the current coin or exclude it
  • Final answer is stored in table[n][m-1]

Key Points

  • Time Complexity: O(n × m) where n is the target amount and m is number of coin types
  • Space Complexity: O(n × m) for the DP table
  • This approach counts all possible combinations, not permutations

Conclusion

The coin change problem using dynamic programming efficiently counts all ways to make a target amount. The 2D DP approach systematically builds solutions for smaller amounts to solve the main problem.

Updated on: 2026-03-15T12:27:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements