You said that you have problem with this code, but you didn't mentioned what is the problem, well looking at your code i find one problem, may be if that can help you.
Wrong Loop
for(d = MAX; d <= MIN; d++)
Right approach would be
for(d = MIN; d <= MAX; d++)
Hope this helps