📜  打印上星三角形图案的Java程序

📅  最后修改于: 2022-05-13 01:54:34.473000             🧑  作者: Mango

打印上星三角形图案的Java程序

上面的星形三角形图案意味着底座必须在底部,并且第一行中只会打印一个星形。这里将出现的问题是我们向前或向后遍历的方式我们不能忽略空格,因此我们无法仅使用两个嵌套的 for 循环在第一行打印星号。答案很简单,因为我们将这个问题分成两部分,我们将运行两个内部 for 循环,一个管理空白,另一个管理模式打印其余保持不变。

例子

Java
// Java Program to  Print Upper Star Triangle Pattern
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing variable representing
        // number of rows to be printed
        int k = 9;
 
        // Nested 2 for loops for iterating over the matrix
 
        // Outer for loop for iterating over rows
        for (int a = 0; a <= k; a++) {
 
            // Inner for loop for iterating over columns
            // where we are printing white spaces
            for (int b = 1; b <= k - a; b++) {
 
                // Print the white space
                System.out.print(" ");
            }
 
            // Inner for loop for iterating over columns
            // where we are printing white spaces
            for (int l = 0; l <= a; l++) {
 
                // Print the star pattern
                System.out.print("*");
            }
 
            // By now we are done with one row so
            // next line
            System.out.println("");
        }
    }
}


输出
*
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********