-1

can anyone explain why first fact() function code doesn't give me correct output but second one does? what's wrong with the commented factorial function code???

#include <iostream>
using namespace std;
// int fact(int n){
//     for (int i = n-1; i > 0; i--){
//         n = n * i;
//     }
//     return n;
// }

int fact(int n){
    int temp=1;
    for (int i = 2; i <=n; i++){
        temp= temp * i;
    }
    return temp;
}

int nCr(int n, int r){
    int temp=(fact(n) / (fact(n - r) * fact(r)));
    return temp;
}
int main(){
    int n;
    cout << "enter no: ";
    cin >> n;
    for (int i = 0; i < n;i++){
        for (int k = 1; k < (n - i);k++)
            cout << " ";
        for (int j = 0; j <= i; j++)
        {
            cout << nCr(i, j) << " ";
        }
        cout << endl;
    }
    return 0;
} 
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • 2
    *what's wrong with the commented factorial function code???* -- [What is a debugger and how will it help me diagnose issues?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) and [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – PaulMcKenzie Jun 16 '21 at 14:30

1 Answers1

0

The second fact function correctly returns 1 when n = 0, but the first one wrongly returns 0 when n = 0.

Adding check for this case will make the first function work well.

int fact(int n){
    if (n == 0) return 1; // check for n = 0 case
    for (int i = n-1; i > 0; i--){
        n = n * i;
    }
    return n;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70