Java 打印锯齿形数字直角三角形的程序

在这个 Java 模式程序中,我们展示了使用 for 循环、while 循环和函数打印锯齿形数字直角三角形模式的步骤。

下面的程序接受用户输入的行数,并使用嵌套的 for 循环遍历行和列。接下来,程序将在直角三角形模式中打印锯齿形数字。

import java.util.Scanner;

public class Example
{
private static Scanner sc;

public static void main(String[] args)
{
sc = new Scanner(System.in);
int rows, i, j, m, n = 1;

System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();

for (i = 1 ; i <= rows; i++ )
{
if (i % 2 != 0)
{
for (j = 1 ; j <= i; j++ )
{
System.out.printf("%d ", n);
n++;
}
}
else
{
m = n + i - 1;
for (j = 0 ; j < i; j++ )
{
System.out.printf("%d ", m);
m--;
n++;
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 11
1 
3 2 
4 5 6 
10 9 8 7 
11 12 13 14 15 
21 20 19 18 17 16 
22 23 24 25 26 27 28 
36 35 34 33 32 31 30 29 
37 38 39 40 41 42 43 44 45 
55 54 53 52 51 50 49 48 47 46 
56 57 58 59 60 61 62 63 64 65 66 

在此程序中,我们用while 循环替换了 for 循环来遍历行和列,并在直角三角形模式形状中打印锯齿形数字。有关更多数字模式程序,请单击此处

import java.util.Scanner;

public class Example
{
private static Scanner sc;

public static void main(String[] args)
{
sc = new Scanner(System.in);
int rows, i, j, m, n = 1;

System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();

i = 1 ;
while (i <= rows )
{
if (i % 2 != 0)
{
j = 1 ;
while ( j <= i)
{
System.out.printf("%d ", n);
n++;
j++;
}
}
else
{
m = n + i - 1;
j = 0 ;
while (j < i )
{
System.out.printf("%d ", m);
m--;
n++;
j++;
}
}
i++;
System.out.println();
}
}
}
Enter Numbers of Rows = 13
1 
3 2 
4 5 6 
10 9 8 7 
11 12 13 14 15 
21 20 19 18 17 16 
22 23 24 25 26 27 28 
36 35 34 33 32 31 30 29 
37 38 39 40 41 42 43 44 45 
55 54 53 52 51 50 49 48 47 46 
56 57 58 59 60 61 62 63 64 65 66 
78 77 76 75 74 73 72 71 70 69 68 67 
79 80 81 82 83 84 85 86 87 88 89 90 91 

在这个 Java 模式程序中,我们创建了一个 RightTriZigzagNums 函数,用于在每一行打印锯齿形数字的直角三角形。

import java.util.Scanner;

public class Example
{
private static Scanner sc;

public static void main(String[] args)
{
sc = new Scanner(System.in);
int rows;

System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();


RightTriZigzagNums(rows);
}
public static void RightTriZigzagNums(int rows)
{
int i, j, m, n = 1;
for (i = 1 ; i <= rows; i++ )
{
if(i % 2 != 0)
{
for (j = 1 ; j <= i; j++ )
{
System.out.printf("%d ", n);
n++;
}
}
else
{
m = n + i - 1;
for (j = 0 ; j < i; j++ )
{
System.out.printf("%d ", m);
m--;
n++;
}
}
System.out.println();
}
}
}
Print Right Triangle of Zigzag Numbers