C program to find the value of ncr(combination) using function

C program to find ncr

code:

#include <stdio.h>
 
int fact(int);
 
void main()
{
 int n,r,ncr;
 
  printf("Enter a number n:");
  scanf("%d",&n);
    printf("Enter a number r:");
  scanf("%d",&r); ncr=fact(n)/(fact(r)*fact(n-r));
    printf("Value of %dC%d = %d\n",n,r,ncr);
}
int fact(int n)
{
    int i,f=1;
    for(i=1;i<=n;i++)
    {
        f=f*i;
    }
    return f;
}


Explanation:

  • In this program we are using "function" concept.
  • To find ncr we first declare the variables
  • We get the output from the user and store them.
  • ncr formula is "ncr=fact(n)/(fact(r)*fact(n-r))"
  • To print the result we are using printf statement.


Output 1:







Output 2:


Now if you see the second output , we get 0 as answer 




Explanation:

You can see "0" as answer because "n ≥ r ≥ 0"
"n" should be lesser than "r" and "r" should be  greater than "r".
If not we get "0" as output.


Comments

Popular posts from this blog

Use of Backslash "\n" in C language

COHESION AND COUPLING material

Coding and Testing in software engineering