Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
C program to calculates the number of ways to choose k objects from n distinct objects. 'k' and 'n' both are integers

I wrote a C program to calculate the number of ways to choose k objects from n distinct objects using functions.

    #include<stdio.h>
    long f(int a)
    {
     if(a==1||a==0)return(0);
     else return(a*f(a-1));
    }

    int combination(int N,int K)
    {
     long int NF,KF,NMKF;
     NF=f(N);
     KF=f(K);
     NMKF=f(N-K);
     return(NF/(KF*NMKF));

    }
    int main()
    {
     int n,k;
     scanf("%d%d",&n,&k);
     combination(n,k);
    }

But the compiler shows following error message

floating point exception (core dumped)

How to avoid it?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The problem is in this line

if(a==1||a==0)return(0);

It should be

if(a==1||a==0)return(1);

While calculating factorial, n*(n-1)*(n-2)...*(2)*(1). Notice in the end, we multiply by 1 and not zero. multiplying with 0 would make the factorial 0. And later when you are performing division, the 0 comes in the denominator, and floating point exception is occurring. That's why your program is giving error.

For cases when factorial of 0 is needed. Then also this would work, because factorial of 0 is 1 and not 0.. Check this out.

over 4 years ago · Santiago Trujillo Report

0

Two problems:

  1. if(a==1||a==0) you should return 1, not return 0. Because 1!=1, 0!=1.
  2. Your intention is choose k objects from n distinct objects. But You should add param checking in order to not occur the n<k. If we input n=2, k=3.The program will go to error. It is bad! I hope this can help you.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!