0

I'm trying to make program that will calculate Pascal's triangle and I was looking up some examples and I found this one. But I don't really understand how the pascal method works. But everything else makes sense.

import java.util.Scanner;
public class Pascal {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the number of rows to print: ");
    int rows = scanner.nextInt();
    System.out.println("Pascal Triangle:");
    print(rows);
    scanner.close();
  }

  public static void print(int n) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j <= i; j++) {
        System.out.print(pascal(i, j) + " ");
      }
      System.out.println();
    }
  }

  public static int pascal(int i, int j) {
    if (j == 0 || j == i) {
      return 1;
    } else {
      return pascal(i - 1, j - 1) + pascal(i - 1, j);
    }
  }
}
ss58
  • 1
  • 1
  • 2
  • Try following the execution pattern using pen and paper(e.g. i, j=3).Or read [this](https://medium.freecodecamp.org/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9) – jrook Oct 11 '18 at 18:34
  • This might help: https://stackoverflow.com/questions/11809502/which-is-better-way-to-calculate-ncr/11809815#11809815 – Sufian Latif Oct 11 '18 at 18:56
  • This question is too broad. To answer is, somebody would have to walk you through the code and explains what happens at each turn. It would be better if you could point to specific parts in the code that you cannot understand; such a question could be answered more easily. – Laurenz Albe Oct 11 '18 at 19:02

1 Answers1

0

See comments for some clarification:

  public static void print(int n) {

    for (int i = 0; i < n; i++) { //iterate over 0 - (n-1) rows 
      for (int j = 0; j <= i; j++) {  //iterate over 0 - i columns, so 1 line 
                                      //will have 1 columns second line 2 columns..

        System.out.print(pascal(i, j) + " "); //print column value and space 
      }
      System.out.println();
    }
  }

  //return the value of row i, col j 
  public static int pascal(int i, int j) {
    if ((j == 0) || (j == i)) { //value of first or last column is 1 
      return 1;
    } else {//value of other columns is the sum of two values of previous row 
      return pascal(i - 1, j - 1) + pascal(i - 1, j);
    }
  }
c0der
  • 18,467
  • 6
  • 33
  • 65