邏輯

2016-04-21 78 views
-2

我有一個困難時期試圖瞭解背後產生這樣的輸出嵌套循環程序邏輯:邏輯

Pattern C 
        1 
       1 2 
       1 2 3 
      1 2 3 4 
      1 2 3 4 5 
     1 2 3 4 5 6 
     1 2 3 4 5 6 7 
    1 2 3 4 5 6 7 8 
    1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 

而這裏的代碼:

void patternC(){ 
    System.out.println("\nPattern C"); 
    for(int m = 1; m <= a; m++){ //<-- a is for the desired number of lines 

     //spasi 
     for(int n = m; n <= a-m+a ; n++){ 
      System.out.print(" "); 
     } 

     for(int o = 1; o <= m ; o++){ 
      System.out.print(o + " "); 
     } 

     System.out.println(); 
    } 
} 

我知道第一個for用於該行,而第三個for用於在每行中打印的數字。但我仍然沒有在第二個for(我知道這是間距)的邏輯,但你可以請示例解釋我?謝謝。

+0

明白嘗試打印出'm'' n'和'o'的值而不是 –

回答

0

理解嵌套循環基礎知識的最佳方法是在紙上執行代碼。只需按照每個步驟跟蹤每個變量,並且應該在紙面上輸出相同的輸出,並瞭解循環的功能。

+0

或者在調試器中執行代碼並觀察計數器和限制。 – Konrad

-1
void patter(){ 

    for(int m = 1; m <= a; m++) // a is desired no to be selected by user. 
    {   
    for(int n = 1; n <= a-m ; n++){ 
     System.out.print(" "); 
    } 

    for(int o = 1; o <= m ; o++){ 
     System.out.print(o); 
    } 

    System.out.println(); 
    } 
}