I am new to C++/C programming and i was doing a little practice with "for" loops.
The program asks the user to enter a sum of money and prints all possible ways to pay the sum with the following cents : 5, 10, 20, 50
for example if you enter a sum of 20, it says:
How many cents ? > 20
0 50-cent 1 20-cent 0 10-cent 0 5-cent
0 50-cent 0 20-cent 2 10-cent 0 5-cent
0 50-cent 0 20-cent 1 10-cent 2 5-cent
0 50-cent 0 20-cent 0 10-cent 4 5-cent
The problem:
How many cents ? > 30
0 50-cent 1 20-cent 1 10-cent -1 5-cent
0 50-cent 1 20-cent 0 10-cent 2 5-cent
0 50-cent 0 20-cent 3 10-cent -1 5-cent
0 50-cent 0 20-cent 2 10-cent 2 5-cent
0 50-cent 0 20-cent 1 10-cent 4 5-cent
0 50-cent 0 20-cent 0 10-cent 6 5-cent
So it sometimes prints -1 instead of 0 . Some help please.
The code:
Thanks in advanceCode:#include <stdio.h> #include <conio.h> int main(void) { int a=0, i=0, j=0, k=0, sum1=0, sum2=0, sum3=0, sum4=0; int cent, temp1, temp2, temp3, temp4; printf("How many cents ? >"); scanf("%d", ¢); temp1=((int)(cent/50+0.0001)); temp2=((int)(cent/20+0.0001)); temp3=((int)(cent/10+0.0001)); temp4=((int)(cent/5+0.0001)); for(a=temp1;a>=0;a--){ //50 - cent sum1=a*50; if(sum1==cent){printf("%d 50-cent, %d 20-cent, %d 10-cent, %d 5-cent \n",a, i, j, k);continue;} for(i=temp2;i>=0;i--){ // 20 - cent sum2=sum1+(i*20); if(sum2==cent){printf("%d 50-cent, %d 20-cent, %d 10-cent, %d 5-cent \n",a, i, j, k);continue;} for(j=temp3;j>=0;j--){ // 10 - cent sum3=sum2+(j*10); if(sum3==cent){printf("%d 50-cent, %d 20-cent, %d 10-cent, %d 5-cent \n",a, i, j, k);continue;} for(k=temp4;k>=0;k--){ // 5 - cent sum4=sum3+(k*5); if(sum4==cent){printf("%d 50-cent, %d 20-cent, %d 10-cent, %d 5-cent \n", a, i, j, k);continue;} } } } } printf("\nPress any key..."); getch(); return 0; }



LinkBack URL
About LinkBacks


