create a program to display the number of combinations where n and k are entered
ID: 3539629 • 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,combinations,i;
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>4)
printf(" Invalid input: Number must be between 1 and 4 ");
else
break;
}
combinations = 1;
for(i=k-1;i>=0;i--)
{
combinations = combinations*(n-i);
}
for(i=1;i<=k;i++)
{
combinations = combinations/i;
}
printf("Number of combinations:%d",combinations);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.