I wrote code to calculate the minimum number of coins using the Greedy algorithm and a dynamic algorithm, but part of the dynamic algorithm does not work correctly. There is a Null value in the array, I can not find it. Please, help. I need an answer as soon as possible.
#include <stdio.h> int n; int denom[]={1,2,4,5,20,25}; int coinCounter(int n); int main(){ printf("Please Enter a Number : "); scanf("%d",&n); int coinmin,orin,i; orin=n; i=coinmin=0; for(i=(sizeof(denom)/4)-1;i>=0;i--){ coinmin =coinmin+n/denom[i]; n=n%denom[i]; } printf("Coin Min By Greedy Algorithm : %d\n",coinmin); printf("Dynamic Algorithm : %d\n",coinCounter(orin)); return 0; } int coinCounter(int n){ int opt[n]; int largest[n]; int i,j,a; i=j=0; for(j=1;j<=n;j++){ opt[j]=10000; //printf("xxn"); for(i=(sizeof(denom)/4)-1;i>=0;i--){ if(denom[i]==j){ opt[j]=1; largest[j]=j; } else if(denom[i]<j){ a=opt[j-denom[i]]+1; } if(a<opt[j]){ opt[j]=a; largest[j]=denom[i]; } } } return opt[n]; }
I edited the code as follows, but the answer does not come
int coinCounter(int n){ int opt[n]; int largest[n]; int i,j,a; i=j=0; for(j=1;j<n;j++){ opt[j]=10000; printf("xxn"); for(i=(sizeof(denom)/4)-1;i>=0;i--){ if(denom[i]==j){ opt[j]=1; largest[j]=j; } else if(denom[i]<j){ a=opt[j-denom[i]]+1; } if(a<opt[j]){ opt[j]=a; largest[j]=denom[i]; } } } return opt[n-1]; }
Hey these are the results i get
Please Enter a Number: 8
Coin Min By Greedy Algorithm: 3
Dynamic Algorithm: 1
The other answer that I get, I can not understand what I'm doing wrong
Please Enter a Number: 71
Coin Min By Greedy Algorithm: 4
Dynamic Algorithm: 3
source share