java簡單算法循環

/*
 使用嵌套循環輸出
1 23 4 5 6 78 9
2 46 8 10 12 1416 18
3 69 12 15 18 2124 27
4 812 16 20 24 2832 36
5 1015 20 25 30 3540 45
6 1218 24 30 36 4248 54
7 1421 28 35 42 4956 63
8 1624 32 40 48 5664 72
9 1827 36 45 54 6372 81

*/


// 開始值
int x = 1;
// 循環次數
int y = 9;
// 第一個循環從1開始,循環9次,
for (int i = 1; i <= y; i++) {
/*  
  第二個內循環,
從x開始到x*y,
也就是循環次數*每次循環開始的值
*/
for (int j = x; j <= x * y; j += x) {
System.out.print(j + "\t");
}
// 每次循環以後開始的值要+1;
x += 1;
System.out.println();
}

------------------------------------------

while實現差不多照舊

int x = 1;
int y = 9;
while (x <= y) {
int j = x;
while (j <= x * y) {
System.out.print(j + "\t");
j += x;
}
x += 1;
System.out.println();
}


java楊輝三角代碼實現


package javaABC_123;


import java.util.Scanner;


public class YangHui_triangle {
public static void main(String[] args) {


System.out.println("請輸入楊輝三角的行數:");
Scanner ScRows = new Scanner(System.in);
final int Rows = ScRows.nextInt();
// 聲明二維數組,設置一維行數爲Rows+1
int array[][] = new int[Rows + 1][];
// 循環初始化數組
for (int i = 0; i <= Rows; i++)
{
// 設置數組的二位行數
array[i] = new int[i + 1];
}
System.out.println("楊輝三角爲:");
YhTriangle(array, Rows);
}
// 輸出楊輝三角
public static void YhTriangle(int array[][], int rows) {
// 行控制
for (int i = 0; i <= rows; i++) {
// 列控制
for (int j = 0; j < array[i].length; j++) {
// 賦值給二位數組,將兩邊的元素賦值爲1
if (i == 0 || j == 0 || j == array[i].length - 1)
array[i][j] = 1;
// 將其正上方元素與左上角元素之和賦值給此元素中。
else
array[i][j] = array[i - 1][j - 1] + array[i - 1][j];
}
}
// 打印輸出楊輝三角
for (int i = 0; i <= rows; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章