Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //********************************************************************************/
- //File Name: PascalsTriangle.java Author: Justin Trubela /
- //Section: 03 /
- // /
- //Purpose: Write a program using recursion. The program asks the user to input /
- //an integer n and calculates n many rows of Pascals triangle /
- //********************************************************************************/
- import java.util.Scanner;
- public class PascalsTriangle {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- //not entirely n-th but its a start based on the string of spaces i'm breaking up soon
- System.out.println("Enter a number from 1 to 9: ");
- //scan in the n-th row from user
- int input = scan.nextInt();
- while(input<=0 || input>=10) {
- System.out.println("not in the assigned range");
- System.out.println("Enter a number from 1 to 9: ");
- input = scan.nextInt();
- }
- System.out.println("Pascals Triangle:");
- //Recursive function
- printTriangle(input);
- }
- public static void printTriangle(int n) {
- /*could probably put this is an array and have it iterate n/2 times each row to compensate printed number difference */
- String spaces = " "; // sets up the spaces on the left of triangle(32 spaces to be exact)
- int spacesLength = spaces.length();
- //iterate through for each row of the triangle
- for (int i = 0; i < n; i++) {
- for (int j = 0; j <= i; j++) {
- System.out.print(" " + pascalsTriangle(i, j) + " ");
- }
- System.out.println();
- System.out.print(spaces.substring(0, spacesLength/2));
- /*as it iterates chop off 4 more spaces from the string so that it becomes shorter*/
- spacesLength=spacesLength-4;
- }
- }
- public static int pascalsTriangle(int i, int j) {
- if (i==0) /*center the first 1*/{
- /*same thing here with utilizing n/2 spaces to compensate the difference*/
- System.out.print(" ");
- }
- //
- if (j == 0 || j == i) {
- return 1;
- }
- else {
- return pascalsTriangle(i - 1, j - 1) + pascalsTriangle(i - 1, j);
- }
- }
- }
Add Comment
Please, Sign In to add comment