I am a beginner trying to write a program for my intro C class. I am trying to write a program that calculates the combination of numbers given a specific output by the user. The number has to be between 1-10 to be valid. I am not allowed to use the built in library that calculates a combination. I am getting stuck at the part where i need to calculate (n-k)! I see that my problem is after my loops the numbers the user inputs for n and k are now zero. I am not sure if I should have written this a different way or how I should go about getting the original entered digits back so that I can take and use them in calculating (n-k)! Any help would be very much appreciated.
int main() /* Main declaration with arguments */ { int n, nFact = 1, k, kFact = 1, n_k = ( n - k ), nkFact = 1, combination; do { printf("\nEnter the number of items in the list (n): "); scanf("%d", &n); if ( n < 1 || n > 10 ) /* is n between 1 - 10 */ printf("\n?Invalid input: Number must be between 1 and 10\n"); else break; } while ( n > 1 || n < 10 ); //the while test is goofed. If n < 1 || n > 10, THEN you want to loop back. /* As long as n>=1 program will loop the following n*n-1 */ while (n>=1) { nFact = ( nFact * n ); n = ( n - 1 ); } printf("n! = %d", nFact); do { printf("\nEnter the number of items to choose (k): "); scanf("%d", &k); if ( k < 1 || k > 10 ) /* is k between 1 - 10 */ printf("\n?Invalid input: Number must be between 1 and 10\n"); else break; } while ( k > 1 || n < 10 ); while (k>=1) { kFact = ( kFact * k ); k = ( k - 1 ); } printf("k! = %d", kFact); while (n_k>=1) { nkFact = ( nkFact * n_k ); n_k = ( n_k - 1 ); } printf("\n(n-k)! = %d", nkFact); printf("\n"); system("PAUSE"); return(0); }
It looks like you're solving for the number of permutations, rather than combinations (which are far fewer). Can you confirm which it is?
Giving your variables better names than: nfact, kfact, nkfact, k, etc., would be very helpful.
Always highlight your program, and click on the # symbol, so your code, is punctuated to look like code, on this (and any other code), forum.