create a program to display the number of combinations where n and k are entered
ID: 3539624 • Letter: C
Question
create a program to display the number of combinations where n and k are entered by the user. Do not use the built-in C function to compute either combinations or factorials.
Reject any input greater than 10 or less than 1 by displaying an error message and then asking the user to re-enter the input. Do this as many times that they enter incorrect input. This applies both to n and k.
Additionally for k, there is an extra condition that k <= n
Assume that all of the internal calculations can be done using integers, i.e. don't worry about integer overflow.
Output should be formatted as shown in the sample.
Explanation / Answer
#include <stdio.h>
int main()
{
int n,k;
int factN=1,factK=1,factN_K=1;
while(1)
{
printf("Enter the number of items in the list (n):");
scanf("%d",&n);
if(n<1||n>10)
{
printf("?Invalid input: Number must be between 1 and 10 ");
}
else
{
break;
}
}
while(1)
{
printf("Enter the number of items to choose (k):");
scanf("%d",&k);
if(k<1||k>n)
{
printf("?Invalid input: Number must be between 1 and %d ",n);
}
else
{
break;
}
}
int i;
for(i=1;i<=n;i++)
{
factN = factN * i;
}
for(i=1;i<=k;i++)
{
factK = factK * i;
}
for(i=1;i<=n-k;i++)
{
factN_K = factN_K * i;
}
int nCk = factN/(factK*factN_K);
printf("Number of combinations:%d ",nCk);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.