-2

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.

Fingolfin
  • 17
  • 7
  • You also need to check the state of `std::cin`. If the read failed, say you entered something that isn't a number, you'll get stuck in an infinite loop. Just `while (std::cin && n>k)` – BoBTFish Apr 13 '16 at 07:10
  • 3
    ‘*Not working*’ is not a good enough description of a problem. *How* does it not work? Does it not compile? Does it crash? Does it loop forever? Did something catch fire? – Biffen Apr 13 '16 at 07:10
  • while(1) { cin >> n; cin >> k; if(n>k) break; } I think this will work for you. – Undefined Behaviour Apr 13 '16 at 07:17

1 Answers1

1

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;
}
sergej
  • 17,147
  • 6
  • 52
  • 89
  • This is definitely better because a user can do anything with a program, knowingly or unknowingly. Better safe than sorry! – Biruk Abebe Apr 13 '16 at 08:30
  • @sergej Thank you. Now i see how stupid is my question.I tried the same thing but the compiler gives me an error an i give up. I just don't understand why in this case you use std::numeric_limits::max(), '\n' in cin.ignore(); – Fingolfin Apr 13 '16 at 15:20
  • @Fingolfin You are welcome. Please see [this](http://en.cppreference.com/w/cpp/io/basic_istream/ignore). – sergej Apr 13 '16 at 15:41