Solving the Making Change Problem in C: Greedy Approach

Discover how to tackle the making change problem using the greedy algorithm in C. Learn with clear code examples and detailed explanations.

The making change problem is a classic algorithmic challenge where the goal is to find the minimum number of coins needed to make a specific amount of change. The greedy approach is a straightforward and efficient method to solve this problem. In this blog, we will demonstrate how to implement the greedy algorithm for the making change problem in C.

Making Change with the Greedy Approach

The greedy approach involves selecting the largest possible denomination of coin at each step until the desired amount is achieved. This method ensures that the number of coins used is minimized.

Here’s the code snippet for solving the making change problem using the greedy approach in C:

#include <stdio.h>

int cn = 0;
int coins[10];

void findLess(int cost) {
int resultcoin[20] = { 0 }, i, k = 0, ncost, c = 0;
ncost = cost;

for (i = cn - 1; i >= 0; i--) {
while (cost >= coins[i]) {
cost -= coins[i];
resultcoin[k++] = coins[i];
}
}
for (i = 0; i < k; i++) {
printf("%d ", resultcoin[i]);
c++;
}

printf("\nTotal No. of Coins Required for Change of %d is: %d", ncost, c);
}

void main() {
int val, i;
printf("Greedy Approach: Making Change Problem >>\n\n");
printf("\nEnter Number of Coins: ");
scanf("%d", &cn);
printf("\nEnter Coins: \n");
for (i = 0; i < cn; i++)
scanf("%d", &coins[i]);

printf("\nEnter Value to get Change of: ");
scanf("%d", &val);

printf("\nLeast Coins Required to get The Change of %d is: ", val);
findLess(val);
}

Explanation:

1. Variable Initialization: Initialize the number of coins `cn` and an array `coins` to store the coin denominations.
2. Input Coin Denominations: Prompt the user to input the number of different coin denominations and their values.
3. Input the Value to Change: Get the amount of change needed from the user.
4. Greedy Algorithm: The function `findLess` implements the greedy algorithm:
— Iterate through the coin denominations starting from the largest.
— Subtract the coin value from the total amount until the amount is less than the coin value.
— Store each coin used in the `resultcoin` array and count the number of coins used.
5. Output Result: Print the coins used and the total number of coins required.

Conclusion

The greedy approach provides an efficient solution to the making change problem, particularly when the coin denominations are such that the greedy choice leads to an optimal solution. Understanding this method helps in grasping the fundamentals of greedy algorithms and their applications in various optimization problems. By practicing this algorithm in C, you can enhance your problem-solving skills and algorithmic thinking. Happy coding!

Comments

Popular posts from this blog

Vue.js