DEV Community

Abhilash Nambiar
Abhilash Nambiar

Posted on

SICP 1.12 - Pascal Triangle using Recursion [C++]

Hello Devs!

Recently I started reading the programming wizard book - Structure and Interpretation of Computer Programs, solving through the exercises, thought I'll share them here.

The book uses scheme as the primary programming language. I used C++ but I still considered the limits of Scheme will writing the code in C++. For example, the absence of loops.

Here is the code to print the Pascal triangle only using a recursive method.

  1. First, a recursive method to print all the columns

void display_pascal_col(int n, int i) {
if (i == n) return;
display_pascal_row(i, 1);
display_pascal_col(n, i+1);
}

  1. Now, within that recursive method there is another method which will print the row for that column in that particular iteration.

void display_pascal_row(int row, int col) {
cout << pascal(row, col);
if (row == col) {
cout << endl;
return;
}
display_pascal_row(row, col+1);
}

  1. Every row value can be found using the classic Pascal Triangle recursive method. Concepts of dynamic programming can be applied with this method for optimization.

int pascal(int row, int col) {
if (row == 1 || col == 1 || row == col) return 1;
return pascal(row-1, col-1) + pascal(row-1, col);
}

  1. Find the entire C++ code below
#include <iostream>
using namespace std;

int pascal(int row, int col) {
    if (row == 1 || col == 1 || row == col) return 1;
    return pascal(row-1, col-1) + pascal(row-1, col);
}

void display_pascal_row(int row, int col) {
    cout << pascal(row, col) << " ";
    if (row == col) {
        cout << endl;
        return;
    }
    display_pascal_row(row, col+1);
}

void display_pascal_col(int n, int i) {
    if (i == n) return;
    display_pascal_row(i, 1);
    display_pascal_col(n, i+1);
}

void display_pascal(int n) {
    display_pascal_col(n, 1);
}

int main() {
    display_pascal(5);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

That was it!

I recently thought about writing as a part of self revision and to see how well I understand the concepts myself. So this is my first article or post out there. Thanks.

Top comments (0)