更新時間:2022-12-08 11:48:19 來源:動力節(jié)點 瀏覽1810次
給定一個N,任務(wù)是打印以下模式:-例子:
Input : 10
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Input :5
Output :
*
* *
* * *
* * * *
* * * * *
建議:請先試試你的方法{IDE},在繼續(xù)之前的解決方案。
上面有一個嵌套循環(huán)需要打印模式。外循環(huán)運行用于給定的行數(shù)作為輸入。第一個循環(huán)外回路中的每顆恒星之前用于印刷空間。正如你所看到的空間減少的數(shù)量與每一行當我們走向三角形的基地,這與每個迭代循環(huán)運行一次少。第二個循環(huán)在外層循環(huán)用于打印的星星。正如你所看到的星星數(shù)量的增加在每一行我們走向三角形的基地,所以這個循環(huán)運行一次,每一次迭代。可以實現(xiàn)清晰如果這節(jié)目排練。
// 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)
以上就是關(guān)于“Java循環(huán)打印三角形”的介紹,大家如果對此比較感興趣,想了解更多相關(guān)知識,不妨來關(guān)注一下本站的Java視頻教程,里面的課程內(nèi)容細致全面,通俗易懂,很適合沒有基礎(chǔ)的小伙伴學習,希望對大家能夠有所幫助哦。
相關(guān)閱讀