Search code examples
c++loopsdo-whilebinomial-coefficients

C++ loop that run until i enter correct values


This is a program which calculates the binomial coefficient. No when i enter for k value that is > n the program crashеs.But I wonder how i can do so when I enter k> n the program to bring me back to enter new values that are correct(n>k). The program stops when I enter correct values (n>k).

#include<stdio.h>
#include <iostream>
using namespace std;
int binomialCoeff(int n, int k)
{
  // Base Cases
  if (k==0 || k==n)
    return 1;
 else
  return  binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
}
int main()
{
   int n,k;
   cin >>n;
   cin>>k;
    printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k));
    return 0;
}

Maybe with do while loop? Something like this:

do     {
       cin >>n;
       cin>>k;
       }while(n>k);

But this loop is not working.


Solution

  • Something like this?

    int main()
    {
        int n, k;
    
        do {
            printf("Enter n and k values: ");
            cin >> n >> k;
        } while (n < k);
    
        printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k));
        return 0;
    }
    

    However, shouldn't binomialCoeff() just return 0 if (n < k)?

    int binomialCoeff(int n, int k)
    {
        if (k == 0 || k == n)
            return 1;
        else if (n < k)
            return 0;
        else
            return  binomialCoeff(n - 1, k - 1) + binomialCoeff(n - 1, k);
    }
    

    If you want to catch inputs that are not integers try the following:

    #include <limits>
    ...
    
    int main()
    {
        int n, k;
    
        while (!(cin >> n) || !(cin >> k) || (n < k)) {
            cout << "inavlid input! try again" << endl;
            /* clear failbit */
            cin.clear();
            /* discard invalid input */
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    
        printf("Value of C(%d, %d) is %d\n", n, k, binomialCoeff(n, k));
        return 0;
    }