Created
February 21, 2016 17:51
-
-
Save gabhi/775acb896107de99f245 to your computer and use it in GitHub Desktop.
Generating Pascal's triangle using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class PascalTriangle { | |
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) { | |
return 1; | |
} else if (j == i) { | |
return 1; | |
} else { | |
return pascal(i - 1, j - 1) + pascal(i - 1, j); | |
} | |
} | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
System.out.print("Enter the row number upto which Pascal's triangle has to be printed: "); | |
int row = scanner.nextInt(); | |
print(row); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment