0

I wonder how to convert a recursive function/class to an iterative one. I have made a recursive Pascal's triangle, and now need to compare it to an iterative.

public class RecursivePascal extends ErrorPascal implements Pascal {
    private int n;
    RecursivePascal(int n) throws Exception {
        super(n);
        this.n = n;
    }
    public void printPascal() {
        printPascal(n, false);
    }
    public void printPascal(boolean upsideDown) {
        printPascal(n, upsideDown);
    }
    private void printPascal(int n, boolean upsideDown) {
        if (n == 0) {
            return;
        }
        if (!upsideDown) {
            printPascal(n - 1, upsideDown);
        }
        for (int i = 0; i < n; i++) {
            System.out.print(binom(n - 1, i) + (n == i + 1 ? "\n" : " "));
        }
        if (upsideDown) {
            printPascal(n - 1, upsideDown);
        }
    }
    public int binom(int n, int k) {
        if (k == 0 || n == k) {
            return 1;
        }
        return binom(n - 1, k - 1) + binom(n - 1, k);
    }
}

What do I need to change in order to make it iterative? I'm still a little unsure of how this works.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cesarion
  • 17
  • 4

2 Answers2

0

Plug these two functions below into a pascal class. I tested it and it works. That link that Prateek Darmwal posted is pretty much the same thing.

public void nonRecursivePrint() {
    nonRecursivePrint(n, true);
}

public void nonRecursivePrint(int n, boolean upsideDown) {
    if (!upsideDown) {
        for (int j = 0; j < (n + 1); j++) {
            for (int i = 0; i < (j); i++) {
                System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
            }
        }
    } else {
        for (int j = n; j > 0; j--) {
            for (int i = 0; i < (j); i++) {
                System.out.print(binom(j - 1, i) + (j == i + 1 ? "\n" : " "));
            }
        }
    }
}
Community
  • 1
  • 1
Zion
  • 1,562
  • 13
  • 32
  • So this is an iterative Pascal's triangle? – Cesarion Nov 03 '16 at 11:38
  • Yes. The functions loops (i.e. it iterates) and does not call itself like recursive functions do. See here for more detail on the difference between recursive and iterative: http://www.advanced-ict.info/programming/recursion.html – Zion Nov 03 '16 at 11:42
-1

Go through this link you will find your answer explained in detail http://www.geeksforgeeks.org/pascal-triangle/

Prateek Darmwal
  • 161
  • 1
  • 13