Search code examples
cfor-loopcodeblockscombinationsnested-loops

Printing only one combination using nested loops


I have to print combination of different currency notes a man should have to pay to the cashier. Program first ask total amount to be paid and then notes of different denominations that he possesses. The problem is, I have to print only one combination of currency notes, but I am getting all combinations (as usual) by the following code.

#include <stdio.h>
int main(void)
{
    int hundred,fifty,ten,total,hund,fif,t;
    printf ("Enter amount to be paid:");
    scanf ("%d",&total);
    printf ("\n\nHow many currency notes do you have?\nEnter 100,50 and 10 Rupee Notes Respectively:\n");
    scanf ("%d %d %d",&hund,&fif,&t);

    printf ("\t\t\tPossible combination for Rs=%d/- \n",total);

    for (hundred=0; hundred<=hund; hundred++)
    {
          for (fifty=0; fifty<=fif; fifty++)
        {
            for (ten=0; ten<=t; ten++)
            {
                if ((hundred*100+fifty*50+ten*10)==total)
                {
                    printf("\n\n Hundred rupees notes=%d, 50 rupees notes=%d, 10 rupees notes=%d",hundred,fifty,ten);
                }
            }
        }
    }
    getch();
    return 0;
}

Solution

  • Add a getch(); and return 0; just after the printf inside the nested loops.

    Another way is to use goto. Type

    goto exit;
    

    Just after the printf inside the nested loops and type

    exit:
    

    Just before the getch();.