In this Java pattern program, we show the steps to print the right angled triangle pattern of zigzag numbers using for loop, while loop, and functions.
The below program accepts the user-entered rows and uses the nested for loop to traverse the rows and columns. Next, the program will print the zigzag numbers in a right angled triangle pattern.
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
Within this Java program, we replaced the Java for loop with a Java while loop to traverse the rows and columns and print the zigzag numbers in a right angled triangle pattern shape.
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
In this Java pattern program, we created a RightTriZigzagNums function to print the right angled triangle of zigzag numbers on each row. For more numeric patterns, refer to the Java Number Pattern Programs article.
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();
}
}
}

Also Read