更新時間:2022-12-08 11:48:19 來源:動力節點 瀏覽1346次
給定一個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視頻教程,里面的課程內容細致全面,通俗易懂,很適合沒有基礎的小伙伴學習,希望對大家能夠有所幫助哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習