Java 程序:生成帕斯卡三角形
原文:https://www.studytonight.com/java-programs/java-program-to-generate-pascal-triangle
在本教程中,我们将学习如何在 1D 数组中生成帕斯卡三角形。但是在继续之前,如果您不熟悉数组的概念,那么请务必查看 Java 中的文章数组。例如,
输入:行数:5
输出:
one
1 1
1 2 1
1 3 3 1
1 4 6 4 1
程序 1:生成帕斯卡三角形
在这种方法中,我们将看到如何使用数组生成帕斯卡三角形。
算法
- 开始
- 为行数声明一个变量。
- 要求用户初始化行数。
- 声明一个 1D 数组。
- 使用三个 for 循环生成帕斯卡三角形。
- 使用第一个外部 for 循环遍历所有行。
- 使用第二个 for 循环打印空格。
- 将每行的第一个元素指定为 1。
- 使用第三个 for 循环打印元素。
- 显示帕斯卡三角形。
- 停止
下面是相同的代码。
下面的程序演示了如何生成帕斯卡三角形。
/*JAVA PROGRAM TO GENERATE PASCAL TRIANGLE IN 1D ARRAY */
import java.util.*;
public class PascalTriangle
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in); //Take input from the user
int i, j, k, l, r; //Declarig Variabless
int a[]=new int[30]; //Declare a 1d array
System.out.println("Enter the number of rows ");
r=sc.nextInt(); //Initialize the number of rows
//For Pascal Triangle
for(i=0;i<r;i++) //Iterate through all the rows
{
for(k=r; k>i; k--) //Print the number of spaces
{
System.out.print(" ");
}
a[i] = 1; //Initialize the first element of each row as 1
for(j=0;j<=i;j++) //To find the Pascal triangle element
{
System.out.print(a[i]+ " "); //Print the array elements
a[i] = a[i] * (i - j) / (j + 1); //Store the pascal triangle elements in an array
}
System.out.println(); //To move to the next line
}
}
}
输入行数 5 1 1 1 2 1 1 3 3 1 1 4 6 4 1
程序 2:生成帕斯卡三角形
在这种方法中,我们将看到如何使用两个数组生成帕斯卡三角形。
算法
- 开始
- 为行数声明一个变量。
- 要求用户初始化行数。
- 声明两个数组。
- 为第一行的第一个元素打印 1。
- 将两个数组的第一个元素初始化为 1。
- 相同的循环使用四个。
- 使用第一个 for 循环遍历所有行。
- 使用第二个 for 循环打印空格。
- 使用第三个 for 循环来初始化数字。
- 使用第四个 for 循环打印数字。
- 显示最终输出。
- 停止
下面是相同的代码。
/*JAVA PROGRAM TO GENERATE PASCAL TRIANGLE IN 1D ARRAY */
import java.util.*;
public class PascalTriangle
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in); //Take input from the user
int i, j, k, l; //Declarig Variabless
int array[]=new int[30]; //using 1d array
int temp[]=new int[30]; //using 1d array
int num; //Declaring variable for the number of rows
System.out.println("Enter the number of rows ");
num=sc.nextInt(); //Initialize the number of rows
temp[0] = 1; //Initializing first variable of the array as 1
array[0] = 1; //Initializing first variable of the array as 1
System.out.println("1"); //For first element
for (i = 1; i < num; i++) //To iterate through all the rows
{
for (j = 0; j < i; j++) //To print the space
System.out.print("");
for (k = 1; k < num; k++)
{
array[k] = temp[k - 1] + temp[k]; //Initialize the array to store the pascal triangle elements
}
array[i] = 1;
for (l = 0; l <= i; l++)
{
System.out.print(array[l]+" "); //Print the array elements
temp[l] = array[l]; //Copy the array elements to another array
}
System.out.println(""); //For next line
}
}
}
输入行数 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1