专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java循环打印三角形

Java循环打印三角形

更新时间:2022-12-08 11:48:19 来源:星辉 浏览738次

给定一个N,任务是打印以下模式:-例子:

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

建议:请先试试你的方法{IDE},在继续之前的解决方案。

上面有一个嵌套循环需要打印模式。外循环运行用于给定的行数作为输入。第一个循环外回路中的每颗恒星之前用于印刷空间。正如你所看到的空间减少的数量与每一行当我们走向三角形的基地,这与每个迭代循环运行一次少。第二个循环在外层循环用于打印的星星。正如你所看到的星星数量的增加在每一行我们走向三角形的基地,所以这个循环运行一次,每一次迭代。可以实现清晰如果这节目排练。

// 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();
		}
	}
}

时间复杂度:O(行*行)

辅助空间:O (1)

方法2:使用递归

// Java code to demonstrate star pattern
import java.util.*;
class GFG {
	// function to print spaces
	static void printspace(int space)
	{
		// base case
		if (space == 0)
			return;
		System.out.print(" ");
		// recursively calling printspace()
		printspace(space - 1);
	}
	// function to print asterisks
	static void printstar(int asterisk)
	{
		// base case
		if (asterisk == 0)
			return;
		System.out.print("* ");
		// recursively calling printstar()
		printstar(asterisk - 1);
	}
	// function to print the pattern
	static void printrow(int n, int num)
	{
		// base case
		if (n == 0)
			return;
		printspace(n - 1);
		printstar(num - n + 1);
		System.out.println("");
		// recursively calling printrow()
		printrow(n - 1, num);
	}
	// Driver code
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int rows = 5;
		printrow(rows, rows);
	}
}
// this code is contributed by Shivesh Kumar Dwivedi

输出

    * 
   * * 
  * * * 
 * * * * 
* * * * * 

时间复杂度:O(行*行)

辅助空间:O (1)

以上就是关于“Java循环打印三角形”的介绍,大家如果对此比较感兴趣,想了解更多相关知识,不妨来关注一下本站的Java视频教程,里面的课程内容细致全面,通俗易懂,很适合没有基础的小伙伴学习,希望对大家能够有所帮助哦。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>