SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Programming Projects
Question:7 | ISBN:9780136091813 | Edition: 2

Question

Write a program that displays Pascal’s triangle:

Use System.out.printf to format the output into fields of width 4.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package indefinite_loops;

import java.util.Scanner;


public class PascalTriangle {
    
    // below method takes number of rows as parameter
    public static void pascalTriangle(int rowsCount) {
        for (int i = 0; i < rowsCount; i++) {
            int number = 1;
            System.out.printf("%" + (rowsCount - i) * 2 + "s", "");
            for (int j = 0; j <= i; j++) {
                System.out.printf("%4d", number);
                number = number * (i - j) / (j + 1);
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        
        
        Scanner input = new Scanner(System.in);
        System.out.println("enter rows: ");
            int rows = input.nextInt();
            System.out.printf("Pascal's triangle with %d rows %n \n", rows);
            PascalTriangle.pascalTriangle(rows);
        
            input.close();
    }

    
}
Output:

enter rows: 
7
Pascal's triangle with 7 rows 
 
                 1
               1   1
             1   2   1
           1   3   3   1
         1   4   6   4   1
       1   5  10  10   5   1
     1   6  15  20  15   6   1

 

0 0

Discussions

Post the discussion to improve the above solution.