如何实现用Java打印三角形图案(代码示例)

【如何实现用Java打印三角形图案(代码示例)】给定数字N, 任务是打印以下模式:
例子:

Input : 10 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input :5 Output : * * * * * * * * * * * * * * *

打印上述图案需要嵌套循环。外循环用于运行作为输入给出的行数。外循环中的第一个循环用于在每个星星之前打印空格。如你所见, 当我们向三角形的底部移动时, 每行的空格数减少, 因此此循环的每次迭代运行时间减少一倍。外循环中的第二个循环用于打印星星。如你所见, 随着我们向三角形的底边移动, 每行中的恒星数量都会增加, 因此此循环在每次迭代中运行的次数增加了一倍。如果此程序为空运行, 则可以实现清晰度。
// 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(); } } }

    推荐阅读