In: Computer Science
For input you can either a console Scanner or a dialog box (a modal dialog) and the static method showInputDialog() of the JOptionPane class which is within the javax.swing package like this String name= newJOptionPane.showInputDialog(” Please enter your data:”). Then convert the String object to a number using Integer.parseInt() or Double.parseDouble()
-----
Write a Java program to calculate the first n ( the user enters the integer n) rows of the Pascal triangle. On demand display the first n rows of the Pascal triangle, a range of rows or an individual row n. Test by displaying the first 10 rows, the range 7:12 ( rows 7 through 12) or an individual row 15. The display of the first rows should looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
and having the property that each row begins and ends with ones and every element is the sum of the two entries just above it.
Please refer the following JAVA code:
We have used console scanner for input and printed pascals triangle till n th row.
import java.io.*;
import java.util.Scanner;
class Main {
public static void printPascal(int n)
{
int val=n;
for(int line = 1; line <= n; line++)
{
for(int k=0;k<val;k++){
System.out.print(" ");
}
val--;
int C=1;
for(int i = 1; i <= line; i++)
{
System.out.print(C+" ");
C = C * (line - i) / i;
}
System.out.println();
}
}
public static void main (String[] args) {
int n;
Scanner snr = new Scanner(System.in);
System.out.println("Enter the number of rows till which you want to print pascals Triangle");
n=snr.nextInt();
printPascal(n);
}
}
Output for test case n=10 as metioned in question: