Combination

Please explain line by line how this program works

int userInput1,userInput2,nFact = 1,kFact = 1,n_k,nkFact = 1,combination;

//User input
do {
     printf("\nEnter a number between 1 and 10 for  (n\): ");
     scanf("%d", &userInput1);
        if ( userInput1 < 1 || userInput1 > 10 )
            printf("\n?Invalid input: Number must be between 1 and 10\n");

}
while ( userInput1 < 1 || userInput1 > 10 );

int n;
      for ( n = userInput1; n > 1; n--)
      {nFact = ( nFact * n );
}
   printf("n! = %d", nFact);
do {
          printf("\nEnter a  number for (k): ");
            scanf("%d", &userInput2);
      if ( userInput2 < 1 || userInput2 > 10 )
           printf("\n?Invalid input: Number must be between 1 and 10\n");
       else
         break;
}
    while ( userInput2 < 1 || userInput2 > 10 );
    int k;
       for ( k = userInput2; k > 1; k--)
        {
           kFact = ( kFact * k );
       }
         printf("k! = %d", kFact);
         printf("n = %d k = %d", userInput1, userInput2);
         n_k = userInput1 - userInput2;
     while (n_k>=1)
   {
     nkFact = ( nkFact * n_k );
        n_k = ( n_k - 1 );
    }
             printf("\n(n-k)! = %d", nkFact);
             combination = nFact / ( (nkFact) * kFact );
             printf("\nNumber of combinations: %d", combination);
            printf("\n");
exit;

    return 0;
}

Brother, you can refer : Skiz96 - Online IDE & Debugging Tool - Ideone.com

The program calculates total combinations possible when k items are selected out of n items.

As you’ve pasted, the variable names are quite meaningful & I’ve put comments wherever necessary otherwise it’s self-explanatory.

Furthermore, you may consult as follows:-

http://arantxa.ii.uam.es/~ssantini/writing/notes/s667_binomial.pdf

2 Likes

how do I view all answers?

You can view the answer(s) by clicking on the link(s). You can just go through them at your leisure. The main code which you require is in the ideone link. Other links will just add to your knowledge & it’s implementation in various programming languages. So cool bro.

1 Like