C function to print maximum and minimum numbers - c

'm currently writing a C program that prompts a user to enter five numbers and to display the maximum number. So here's what i came up with
int max_num(float num_arr[])
// this is a number array
{
int max = 0;
for (int k = 0; k <= 4; k++)
{
max = num_arr[0];
if (max > num_arr[k])
{
max = num_arr[k];
printf("The maximum number is is %d\n", max);
}
}
}
Any help is appreciated.

Your function will not work for numbers entered less than 0, also int type is wrong for the fuunction since it's not returning anything. Here is a better version of the same:
void max_num(float num_arr[], int size)
{
if(size>0) float max = num_arr[0];
for (int k = 0; k <= size; k++) {
if (max < num_arr[k]) {
max = num_arr[k];
}
}
printf("The maximum number is %f\n", max);
}
And if you need to return max:
float max_num(float num_arr[], int size)
{
if(size>0) float max = num_arr[0];
for (int k = 0; k <= size; k++) {
if (max < num_arr[k]) {
max = num_arr[k];
}
}
return max;
}

You are setting
max = num_arr[0];
in every loop iteration, so you are losing the max value every time and set it
to the first value in the array.
The correct version is:
for(int k = 0;k<5;k++)
{
if(num_arr[k] > max)
max = num_arr[k];
}
printf("The maximum number is is %d\n", max);
Having a <= in the condition is not incorrect, but it's not very readable either,
it's hard to miss the = sign. It's always better to just use <, in this case
k<5.
Also it's better practice to pass the size of the array to the functions, so you
don't have to hard code the maximal number of items to loop through (like you
did in your code). Like this:
#include <stdio.h>
float max_num(float *array, size_t len)
{
if(array == NULL)
{
fprintf(stderr, "invalid argument, array == NULL\n");
return 0;
}
if(len == 0)
{
fprintf(stderr, "Invalid array size, cannot be 0\n");
return 0;
}
float max = array[0];
for(size_t i = 0; i < len; ++i)
{
if(array[i] > max)
max = array[i];
}
return max;
}
int main(void)
{
float nums[] = { 1.1, -2.2, 8, 6, 99 , -12 };
float max = max_num(nums, sizeof nums / sizeof *nums);
printf("The maximal number in the array is: %f\n", max);
return 0;
}

Rather than if(max > num_arr[k]) it should be if(num_arr[k] > max)

Related

Find the maximum, minimum, and average values in the array

In my code, the program will not allowed the negative number entered, the program will stop reading, then calculate the maximum value, minimum value and average value.
That is my code
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
int length = sizeof(age) / sizeof(age[0]);
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
Please enter ages: 5 -1
expected result: max:5;min:5,average:5;
actual result: max:5;min:-1,average: 0.4;
That was a question that I met, the code should not accept any negative value.
Thank you all.
but if I add age[i] = 0; then break;
The average value will equal to 0.5.
You don't need an array.
You don't need both a loop variable and a length.
It's more appropriate to use ? : for updating minimum/maximum.
You don't need two loops
You need to check the int return value of scanf(), which indicates the number of items successfully scanned, so it should be 1. I'll leave that for you/OP to add (hint: replace for-loop by while-loop to avoid having to add a separate length variable again).
int main(void)
{
printf("Please enter ages: \n");
int minimum = INT_MAX;
int maximum = 0;
int sum = 0;
int count = 0;
for (count = 0; count < 10; count++)
{
int age;
scanf("%d", &age);
if (age < 0)
{
break;
}
sum += age;
minimum = (age < minimum) ? age : minimum;
maximum = (age > maximum) ? age : maximum;
}
if (count > 0)
{
printf("Min: %d\n", minimum);
printf("Max: %d\n", maximum);
printf("Avg: %.1f\n", (float)sum / count);
}
else
{
printf("You didn't enter (valid) age(s).\n");
}
return 0;
}
Your approach is overly complicated and wrong.
You want this:
...
int length = 0; // declare length here and initialize to 0
for (int i = 0; i < sizeof(age) / sizeof(age[0]); i++) {
scanf("%d", &age[i]);
if (age[i] < 0) // if it is negative number, it is should stop reading
break;
length++; // one more valid number
}
// now length contains the number of numbers entered
// the rest of your code seems correct
You also might need to handle the special case where no numbers are entered, e.g: the only thing entered is -1. It doesn'make sense to calculate the average or the largest/smallest number when there are no numbers.
A possible solution could be:
(corrections are written in the commented code)
#include <stdio.h>
int main(void){
int arraySize = 10;
int age[arraySize]; //initialize not required
//the number of existing values inside the array (effective length)
int length = 0;
printf("Please enter ages: \n"); // allow user to enter numbers
for(int i=0; i<arraySize; i++){
scanf("%d",&age[i]);
// if it is negative number, it is should stop reading
if(age[i]<0){ break; }
//the else-if is not required
//but, if the compiler goes here,
//it means that the value is acceptable, so
length++;
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for(int j=0; j<length; j++){
if(maximum<age[j]){ maximum = age[j]; }
else if(minimum>age[j]) { minimum = age[j]; }
average += age[j];
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}
OP's primary problem is the 2nd loop iterates 10 times and not i times (the number of times a non-negative was entered.
For fun, let us try a non-floating point solution as it really is an integer problem.
An array to store values is not needed.
#include <limits.h>
#include <stdio.h>
int main(void) {
// Keep track of 4 things
int min = INT_MAX; // Set min to the max int value.
int max = INT_MIN;
long long sum = 0; // Use wide type to cope with sum of extreme ages.
int count = 0;
#define INPUT_N 10
printf("Please enter ages: \n");
for (count = 0; count < INPUT_N; count++) {
int age;
if (scanf("%d", &age) != 1) {
fprintf(stderr, "Missing numeric input.");
return EXIT_FAILURE;
}
if (age < 0) {
break;
}
if (age < min) min = age;
if (age > max) max = age;
sum += age;
}
if (count == 0) {
fprintf(stderr, "No input.");
return EXIT_FAILURE;
}
printf("Maximum: %d\n", max);
printf("Minimum: %d\n", min);
// Could use FP and
// printf("Average: %.1f\n", 1.0 *sum / count);
// But for fun, how about a non-FP approach?
#define SCALE 10
#define SCALE_LOG 1
sum *= SCALE; // Scale by 10 since we want 1 decimal place.
// Perform a rounded divide by `count`
long long average_scaled = (sum + count/2) / count;
// Print the whole and fraction parts
printf("Average: %lld.%.*lld\n",
average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);
return 0;
}
First of all, you must record how many positive numbers you enter. Then the value of length will be correct.
Second, for the second for loop, j must be smaller than the number of positive ages. Therefore, you won't add negative age[j] to average.
You can simply modify the second for loop.
#include <stdio.h>
int main(void) {
int age[10] = {0}; // initalized an array
printf("Please enter ages: \n"); // allow user to enter numbers
int length = 0;
for (int i = 0 ;i < 10; i++) {
scanf("%d",&age[i]);
if (age[i] < 0) { // if it is negative number, it is should stop reading
break;
}
else if (age[i] >= 0) {
length++;
continue;
}
}
int maximum = age[0];
int minimum = age[0];
float average = 0.0;
for (int j = 0; j < length; j++) {
if (maximum < age[j]) {
maximum = age[j];
}
else if (minimum > age[j]) {
minimum = age[j];
}
if ( age[j] > 0.0 )
{
average += age[j];
}
}
average = average / length;
printf("%d\n", maximum);
printf("%d\n", minimum);
printf("%.1f\n", average);
return 0;
}

Sorting integers by sum of their digits

I'm trying to write a program that will sort an array of 20 random numbers by the sums of their digits.
For example:
"5 > 11" because 5 > 1+1 (5 > 2).
I managed to sort the sums but is it possible to return to the original numbers or do it other way?
#include <stdio.h>
void sortujTab(int tab[], int size){
int sum,i;
for(int i=0;i<size;i++)
{
while(tab[i]>0){//sum as added digits of an integer
int p=tab[i]%10;
sum=sum+p;
tab[i]/=10;
}
tab[i]=sum;
sum=0;
}
for(int i=0;i<size;i++)//print of unsorted sums
{
printf("%d,",tab[i]);
}
printf("\n");
for(int i=0;i<size;i++)//sorting sums
for(int j=i+1;j<=size;j++)
{
if(tab[i]>tab[j]){
int temp=tab[j];
tab[j]=tab[i];
tab[i]=temp;
}
}
for(int i=0;i<20;i++)//print of sorted sums
{
printf("%d,",tab[i]);
}
}
int main()
{
int tab[20];
int size=sizeof(tab)/sizeof(*tab);
for(int i=0;i<=20;i++)
{
tab[i]=rand()%1000;// assamble the value
}
for(int i=0;i<20;i++)
{
printf("%d,",tab[i]);//print unsorted
}
printf("\n");
sortujTab(tab,size);
return 0;
}
There are two basic approach :
Create a function that return the sum for an integer, say sum(int a), then call it on comparison, so instead of tab[i] > tab [j] it becomes sum(tab[i]) > sum (tab[j])
Store the sum into a different array, compare with the new array, and on swapping, swap both the original and the new array
The first solution works well enough if the array is small and takes no extra memory, while the second solution didn't need to repeatedly calculate the sum. A caching approach is also possible with map but it's only worth it if there are enough identical numbers in the array.
Since your numbers are non-negative and less than 1000, you can encode the sum of the digits in the numbers itself. So, this formula will be true: encoded_number = original_number + 1000 * sum_of_the_digits. encoded_number/1000 will decode the sum of the digits, and encoded_number%1000 will decode the original number. Follow the modified code below. The numbers enclosed by parentheses in the output are original numbers. I've tried to modify minimally your code.
#include <stdio.h>
#include <stdlib.h>
void sortujTab(int tab[], int size)
{
for (int i = 0; i < size; i++) {
int sum = 0, n = tab[i];
while (n > 0) { //sum as added digits of an integer
int p = n % 10;
sum = sum + p;
n /= 10;
}
tab[i] += sum * 1000;
}
for (int i = 0; i < size; i++) { //print of unsorted sums
printf("%d%c", tab[i] / 1000, i < size - 1 ? ',' : '\n');
}
for (int i = 0; i < size; i++) { //sorting sums
for (int j = i + 1; j < size; j++) {
if (tab[i] / 1000 > tab[j] / 1000) {
int temp = tab[j];
tab[j] = tab[i];
tab[i] = temp;
}
}
}
for (int i = 0; i < size; i++) { //print of sorted sums
printf("%d(%d)%c", tab[i] / 1000, tab[i] % 1000, i < size - 1 ? ',' : '\n');
}
}
int main(void)
{
int tab[20];
int size = sizeof(tab) / sizeof(*tab);
for (int i = 0; i < size; i++) {
tab[i] = rand() % 1000; // assamble the value
}
for (int i = 0; i < size; i++) {
printf("%d%c", tab[i], i < size - 1 ? ',' : '\n'); //print unsorted
}
sortujTab(tab, size);
return 0;
}
If the range of numbers doesn't allow such an encoding, then you can declare a structure with two integer elements (one for the original number and one for the sum of its digits), allocate an array for size elements of this structure, and initialize and sort the array using the digit sums as the keys.
You can sort an array of indexes rather than the array with data.
#include <stdio.h>
//poor man's interpretation of sumofdigits() :-)
int sod(int n) {
switch (n) {
default: return 0;
case 5: return 5;
case 11: return 2;
case 1000: return 1;
case 9: return 9;
}
}
void sortbyindex(int *data, int *ndx, int size) {
//setup default indexes
for (int k = 0; k < size; k++) ndx[k] = k;
//sort the indexes
for (int lo = 0; lo < size; lo++) {
for (int hi = lo + 1; hi < size; hi++) {
if (sod(data[ndx[lo]]) > sod(data[ndx[hi]])) {
//swap indexes
int tmp = ndx[lo];
ndx[lo] = ndx[hi];
ndx[hi] = tmp;
}
}
}
}
int main(void) {
int data[4] = {5, 11, 1000, 9};
int ndx[sizeof data / sizeof *data];
sortbyindex(data, ndx, 4);
for (int k = 0; k < sizeof data / sizeof *data; k++) {
printf("%d\n", data[ndx[k]]);
}
return 0;
}

Finding the second largest element in array without sorting

I know about the single traversal method initialising two variables to INT_MIN. But my question is why do we initialise two variables to INT_MIN and also what is the purpose of INT_MIN here?
Why can't we initialise two variables to its first element like I have done in the code below? Because when I hand-checked the code manually, I found nothing wrong. So why doesn't the code run properly?
#include <stdio.h>
int main(void) {
int x[10];
int i, n;
int first = x[0];
int second = x[0];
printf("Input the size of array :");
scanf("%d", &n);
printf("Input %d elements in the array :\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
for (i = 0; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
There are several problems in your code:
the array x is defined with a length of 10, but uninitialized when you set first and second to the value of its first element.
you do not test the return value of scanf(), leading to undefined behavior in case of input failure.
you do not test of n is in less or equal to 10 before reading values into x.
you need to special case n <= 0 as no values will be read into x.
Here is a modified version:
#include <stdio.h>
int main(void) {
int x[10];
int i, n, first, second;
printf("Input the size of array :");
if (scanf("%d", &n) != 1 || n < 0 || n > 10) {
printf("invalid input\n");
return 1;
}
if (n <= 0) {
first = second = 0;
} else {
printf("Input %d elements in the array:\n", n);
for (i = 0; i < n; i++) {
printf("x[%d]: ", i);
if (scanf("%d", &x[i]) != 1) {
printf("invalid input\n");
return 1;
}
}
first = second = x[0];
for (i = 1; i < n; ++i) {
if (first < x[i]) {
second = first;
first = x[i];
} else
if (x[i] > second && x[i] != first) {
second = x[i];
}
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d\n", second);
return 0;
}
Regarding an alternative implementation where first and second are initialized to INT_MIN and the loop starts at i = 0, the trick is INT_MIN is the smallest possible int value, so first will compare <= to all values of the array and therefore will not shadow a smaller value. It is also a good default return value for a function that finds the maximum value in an array when passed an empty array.
For your case study, the INT_MIN approach is does not work and the algorithm would fail on an array with a single repeated value: at the end of the scan, first would be set to that value and second would still be INT_MIN.
testing first == second would yield a second largest value equal to INT_MIN, which is incorrect.
testing second == INT_MIN to determine if all values are identical would be incorrect too as an array with values { 1, INT_MIN } would indeed have a second largest value equal to INT_MIN.
Your approach works correctly and the alternative would need to be written differently, with an extra variable. Indeed the solution presented in this article is incorrect, and so is this one, this one, this one and countless more random code across the Internet.
I've added some comments where I saw some problems. Hopefully I caught all the problems. Code below.
#include <stdio.h>
int main(void) {
// int x[10]; I moved this to under where you ask the user for the array size.
int i, n;
// int first=x[0]; This should be written after the user has inputted their numbers. Because what is in x[0]? user hasn't entered anything yet
// int second=x[0]; Same reason as ^
printf("Input the size of array :");
scanf("%d",&n);
int x[n]; // This should be here because you asked the user what the size of the array is.
printf("Input %d elements in the array :\n",n);
for(i=0; i<n; i++)
{
printf("x[%d]: ", i);
scanf("%d", &x[i]);
}
// You should put your first and second int's here
int first=x[0];
int second=x[0];
for (i=0; i<n ; ++i)
{
if (first<x[i])
{
second = first;
first = x[i];
}
else if (x[i] > second && x[i] != first)
{
second = x[i];
}
}
if (second == first)
printf("There is no second largest element\n");
else
printf("\nThe Second largest element in the array is: %d", second);
return 0;
}
int first=x[0];
int second=x[0];
x isn't initialized yet.
Prints -1 if no second largest element is found.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int findNotSame(long long int a[],long int n)
{
long long int temp = a[0];
int flag = 0;
long int i;
for(i=0;i<n;i++)
{
if(a[i]!=temp)
return 1;
}
return 0;
}
long long int findMax(long long int a[],long int n)
{
long int i;
long long int max = a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
max = a[i];
}
return max;
}
int main() {
long int i,j,n;
scanf("%ld",&n);
long long int a[n];
if(n<2) //There cannot be scond largest if there;s only one(or less) element.
{
printf("-1");
return 0;
}
for(i=0;i<n;i++) //Read elements.
scanf("%lld",&a[i]);
if (!findNotSame(a,n)) //Check if all the elements in array are same if so, then -1.
{
printf("-1");
return 0;
}
long long int max = findMax(a,n); //Find maximum element(first).
long long int max2 = -999999999999999; //Initialize another max which will be the second maximum.
for(i=0;i<n;i++) //Find the second max. element.
{
if(a[i]>max2 && a[i] != max)
max2 = a[i];
}
if(max == max2) //Incase if second max(largest) is same as maximum
max2 = -1;
printf("%lld",max2);
return 0;
}
All solution is better, but some fail when the same items available in the array
like,
int arr[] = {56, 41, 19, 33, 13, 23, 25, 56};
56 available in two times,
so for this solution,
int arr[] = {56, 41, 19, 33, 13, 23, 25,56};
var max = arr[0];
var secMax=-1;
var size = arr.length;
for(var l = 1; l < size; l++) {
if (max < arr[l]) {
secMax = max;
max = arr[l];
} else if (secMax < arr[l] && arr[l] != max) {
secMax = arr[l];
}
}
System.out.println("Second largest number :-" + secMax);
import ast
input_str = input()
input_list = ast.literal_eval(input_str)
if len(input_list)<2:
print("not present")
else:
i=input_list[0]
j=i
for index_val in input_list[1:]:
if i<index_val:
j=i
i=index_val
elif index_val>j and index_val!=i:
j=index_val
elif i==j and index_val<j:j=index_val
if i==j:
print("not present")
else:
print(j)
This works,
val arr=Array(4,1,2,4,5,5,7,18,10,5,7)
var firstAndSecondIndex:(Int,Int)=null
for(indexVal <- 2 to (arr.size -1))
firstAndSecondIndex match {
case null =>
println("0,0")
firstAndSecondIndex=(0,1)
case value =>
value match {
case value if arr(indexVal) == arr(value._1) || arr(indexVal) == arr(value._2) =>
println("equals")
case value if arr(indexVal) > arr(value._1) =>
println("1,0")
value match {
case value if arr(indexVal) > arr(value._2) && arr(value._1) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) > arr(value._2) && arr(value._1) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
case value if arr(indexVal) < arr(value._2) =>
firstAndSecondIndex=(indexVal,value._2)
}
case value if arr(indexVal) < arr(value._1) =>
println("1,1")
value match {
case value if arr(indexVal) > arr(value._2) =>
firstAndSecondIndex=(indexVal,value._1)
case value if arr(indexVal) < arr(value._2) =>
println("not greater")
}
}
}
val secondLargest= arr(firstAndSecondIndex._1) < arr(firstAndSecondIndex._2) match {case true => arr(firstAndSecondIndex._1) case false => arr(firstAndSecondIndex._2)}
int arr[] = {56, 41, 19, 33, 13, 23, 25};
int max = 1;
int secondMax = 0;
for (int i = 0; i < arr.length; i++) {
int getValue = arr[i];
if (max == 1) {
max = getValue;
secondMax = arr[1];
} else {
if (max < getValue) {
secondMax = max;
max = getValue;
} else if (secondMax < getValue) {
secondMax = getValue;
} else {
// Nothing Do
}
}
}
System.out.println("" + secondMax);
Java code to find the largest and second largest number in an array without sorting and using a single loop:
package programs;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int largest = -1;
int secondlargest = -1;
int numberPos = -1;
int numberPos1 = -1;
int[] arr = {22, 33, 9000, 70, 9000, -1, -10, -3, 22, 99, 100, 10000};
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
numberPos = i;
largest = arr[i];
}
}
for (int i = 0; i < arr.length; i++) {
if (secondlargest < arr[i] && secondlargest < largest && arr[i] != largest) {
secondlargest = arr[i];
numberPos1 = i;
}
}
System.out.println("Largest number is "+largest+" with position "+numberPos);
System.out.println("Second largest is "+secondlargest+" with position "+numberPos1);
}
}

Fill a defined 2D Array with random numbers in C / Average / Max Value

I've created this 2D 21x21 array that has all it's values set to -1. I wrote it to print the address and value and somehow it only starts at [6][19] why?
What i want to do is to replace some of the -1 values with random numbers from 0 to 100 in the same array. I know i need to seed it with srand but i'm having problems connecting the functions since i'm a total beginner in C.
EDIT 1:
Now i can print the whole array and fill it with random numbers. For the -1 values i just assigned directly which for this case its fine.
What i'm trying now is finding the average of all the values and the maximum number, so what i have is:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[21][21], i , j;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("%3d" , a[i][j]);
}
printf("\n");
}
return 0;
}
// random seed
int GetRand(int min, int max);
int get() {
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
// average
int avg()
float sum=0.0;
for(i = 0; i <= 21; i = i + 1) {
for(j = 0; j <= 21; j = j + 1){
sum = sum + a[21][21];
}
printf("The the average number is %.2f\n", sum/21);
}
//find maximum of all values
int *pv = &a[0][0];
max = min = 0;
for (i = 1; i < i*j; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/j, max%j);
return 0;
}
For the average function the compiler tells me that expected a declaration before i, which is "float sum=0.0;" but i haven't been able to fix that yet.
For the finding the max function i'm not sure yet what i'm doing there, i just have a vague idea of how it's done...am i going in the right direction?
Thanks!
It's very simple: Just assign the result of your GetRand function to the matrix entry.

Coin Change :Dynamic Programming

The code I have written solves the basic coin change problem using dynamic programming and gives the minimum number of coins required to make the change. But I want to store the count of each coin playing part in the minimum number.
What I am trying to do is initializing an array count[] and just like hashing it increments the number of coin[j] whenever min is found, i.e count[coin[j]]++ .
But this is not working the way I wanted because it adds the coin every time it finds min corresponding to coin[j]. Hence the number is not the final count of coin in the final answer.
Here is the code:
void makeChange(int coin[], int n, int value)
{
int i, j;
int min_coin[MAX];
int min;
int count[MAX];
min_coin[0] = 0;
for (i=1; i <= value; i++)
{
min = 999;
for (j = 0; j<n; j++)
{
if (coin[j] <= i)
{
if (min > min_coin[i-coin[j]]+1)
{
min = min_coin[i-coin[j]]+1;
count[coin[j]]++;
}
}
}
min_coin[i] = min;
}
printf("minimum coins required %d \n", min_coin[value]);
}
You have to keep an extra, two-dinemsional array to store the coin count for each value and each coin denomination.
When you assign a new minimum in your inner loop, copy all coin counts from i - coin[j] to i and then increment min_count[i][j]. The number of coins needed is then in coin_count[value].
As you already noted, the bottom-up solution adds the coin every time, not only when i == value, but if you want to know the count of coins when i == value, it depends on the the counts of coins of sub-problems, so we need store previous computations with a 2-D array:
#include <stdio.h>
#define MAX 1000
#define COIN_ARRAY_SIZE 4
void makeChange(int coin[], int n, int value)
{
int i, j, k;
int min_coin[MAX];
int count[MAX + 1][COIN_ARRAY_SIZE] = {0}; // zeroing
int min;
//int count[MAX];
min_coin[0] = 0;
for (i=1; i <= value; i++)
{
min = 999;
for (j = 0; j<n; j++)
{
if (coin[j] <= i)
{
if (min > min_coin[i-coin[j]]+1)
{
min = min_coin[i-coin[j]]+1;
for(k = 0; k < n; ++k)
{
count[i][k] = count[i-coin[j]][k]; // copy coin counts when value=i-coin[j]
}
count[i][j]++; // use a coin[j], increase the count
}
}
}
min_coin[i] = min;
}
printf("minimum coins required %d \n", min_coin[value]);
for(int i = 0; i < COIN_ARRAY_SIZE; ++i)
printf("%d: %d\n", coin[i], count[value][i]);
}
Driver program to test above function:
int main()
{
int coin[COIN_ARRAY_SIZE] = {5,3,2,1};
makeChange(coin, 4, 8);
makeChange(coin, 4, 10);
};

Resources