Search code examples
c++recursionusing

combinatorial function c++ using Recursion


Now this is the combinatorial function if you don't know it:

C(n,k)= { 1 if k=0 or k = n C(n−1,k−1)+C(n−1,k) otherwise

Now, What I really need is to use recursion to print a Pascal's triangle.

Ok,so what I've done so far is this simple recursion function:

#include   <iostream>
using namespace std;

int Pas(int r, int c) {
    if (c == 0 || c == r) {
        return 1;
    } else {
        return Pas(r - 1, c - 1) + Pas(r - 1, c);
    }
}

int main(){

    cout << Pas(4,2) << endl;

    return 0;
}

Now this function computes perfectly for example:

Pas(4,2) = 6

But I'm having problem using it to print the whole Pascal's triangle, because I'm new into C++ and especially recursion ..

I'd appreciate any feedback, and I hope that someone would help figure out this problem. But I'd appreciate it more if you guys don't just give me the whole answer (code) just like that; I want to learn.

Thanks!


Solution

  • Something similar to this might to the job

    void printTriangle(int printRows, int a = 1, int b = 0)
    {
        if (a > printRows) return;
        int val = Pas(a, b);
        cout << val << " ";
        if (a == b) {
            cout << endl;
            printTriangle(printRows, a + 1, 0);
        } else {
            printTriangle(printRows, a, b + 1);
        }
    }
    

    Running printTriangle(7) should print the first 7 rows.