更新時間:2022-06-16 10:45:05 來源:動力節(jié)點 瀏覽1479次
如何用Java打印三角形圖案?動力節(jié)點小編告訴你。給定一個數(shù)字 N,任務(wù)是打印以下模式:
例子:
輸入:10
輸出 :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
輸入:5
輸出 :
*
* *
* * *
* * * *
* * * * *
打印上述模式需要一個嵌套循環(huán)。外部循環(huán)用于運行作為輸入給出的行數(shù)。外循環(huán)中的第一個循環(huán)用于打印每個星之前的空格。正如你所看到的,當我們向三角形的底部移動時,每一行的空格數(shù)都會減少,所以這個循環(huán)在每次迭代中運行的時間減少了一次。外循環(huán)中的第二個循環(huán)用于打印星星。正如你所看到的,隨著我們向三角形底部移動,每行中的星數(shù)增加,所以這個循環(huán)在每次迭代中多運行一次。如果該程序是空運行的,則可以實現(xiàn)清晰度。
// Java Program to print the given pattern
import java.util.*; // package to use Scanner class
class pattern {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows to be printed");
int rows = sc.nextInt();
// loop to iterate for the given number of rows
for (int i = 1; i <= rows; i++) {
// loop to print the number of spaces before the star
for (int j = rows; j >= i; j--) {
System.out.print(" ");
}
// loop to print the number of stars in each row
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
// for new line after printing each row
System.out.println();
}
}
}