给定数字N,任务是打印以下图案:-
null
例如:
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(); } } } |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END