Floyd的三角形是一個由自然數構成的流行的直角三角形陣列。其名稱來自於其創始人羅伯特·W·弗洛伊德,他是一位著名的電腦科學家。三角形的頂部是數字1,然後在每一行向下移動時,每個後續數字遞增1。
在本文中,我們將看到如何使用Java程式來顯示Floyd的三角形。
但在進行Java實作之前,讓我們更深入地了解一下佛洛伊德三角形。
第一行只包含一個數字,即1本身,每個後續行比前一行多一個數字。三角形有n行,其中n可以是任何正整數。
The total number of values in the triangle will be the sum of the 1st n natural numbers which is calculated using the formula S = n/2 * (2a (n-1) d) where S is the sum of the series , n is the number of terms in the series, a is the first term in the series, d is the common difference between the terms.
However, in a Floyd’s triangle, the 1st term is always 1 and the common difference is 1 so we can simplify this formula to:
S= n/2 * (2 + n – 1) = n/2 * (n+1)
因此,Floyd三角形中n行的總值數為n/2 * (n 1)。
如果有5行,即n=5,則三角形中的總值數量為:
5/2 * (5+1) = 15
Input: Number of rows n
1. Initialize a variable "number" to 1
2. For i from 1 to n, do the following −
a. 對於從1到i的j,執行以下操作 -
i. 印出"number"的值
#ii. Increment "number" 由 1
#b. 列印一個換行字元以移動到下一行
For loops are a type of control flow statement that executes a set of instructions repeatedly. It contains 3 parts which are an initialization statement, a Boolean condition, and an update upstatement. After loop body is and the condition is checked again until the Boolean condition becomes false.
The java implementation to display Floyd’s triangle using nested for loops is given below.
public class FloydTriangle { public static void main(String[] args) { // declare the number of rows int rows = 5; int num = 1; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= i; j++) { System.out.print(num + " "); num++; } System.out.println(); } } }
上述程式將產生以下輸出 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
While loops are another form of control flow statements which repeatedly execute based up on a pre-defined Boolean condition and terminates itself once the condition is false.
public class FloydTriangle { public static void main(String[] args) { int rows = 5; int number = 1; int i = 1; while (i <= rows) { int j = 1; while (j <= i) { System.out.print(number + " "); number++; j++; } System.out.println(); i++; } } }
上述程式將產生以下輸出 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do while迴圈與while迴圈非常相似,只是它至少執行一次,因為條件在每次迭代結束時被測試。如果條件為真,循環將繼續執行,並在條件為假時終止。這裡預定義了行數為10。
public class FloydTriangle { public static void main(String[] args) { int rows = 10; int number = 1; int i = 1; do { int j = 1; do { System.out.print(number + " "); number++; j++; } while (j <= i); System.out.println(); i++; } while (i <= rows); } }
上述程式將產生以下輸出 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
佛洛伊德三角形是一個簡單的例子,用於演示和練習基本概念,如循環和模式。它不僅限於Java實現,通常用於教授C ,Java,C#等許多程式語言。三角形由n行組成,其中n可以在編寫程式碼時預先定義並儲存在整數中。可以進一步最佳化,要求使用者輸入n的值或行數(使用Scanner類別或任何其他輸入方法的幫助),這將為學習者帶來更好的練習。總的來說,這個程式是在Java中產生弗洛伊德三角形的一種簡單而高效的方法。在定義循環的條件時要注意,以防止進入無限循環。
以上是Java程式顯示Floyd三角形的詳細內容。更多資訊請關注PHP中文網其他相關文章!