C program Null Parsing

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
+4
source share
2 answers
 int coinCounter(int n){ int opt[n]; int largest[n]; <---- Don't do this. This does not work like you expect it to. 

change to

 int coinCounter(int n){ int opt[n]; int *largest = malloc(sizeof(int)*n); 

Edit:

Another error with the algorithm

your variable "a" is not initialized, and you use it in an if state.

think about the case where denom[i]>j your variable “a” will not be initialized so depending on what value it has for garbage, the results will vary the error here, but it appears when you change the optional distribution, because this distribution changes the condition. What I want to say is if (X<Y) depends on both X and Y. The problem is X, but since you change Y, the condition changes, and you get a different result

+1
source

1

 int opt[n]; // not the right way to do dynamic allocation. Use malloc/calloc int largest[n]; 

2

 for(j=1;j<=n;j++){ ^ array is indexed from 0...n-1, index-n is outside array bounds 

Do not do that.

+4
source

Source: https://habr.com/ru/post/1444986/


All Articles