In this Java pattern program, we show the steps to print the number in an X pattern using for loop, while loop, and functions. The below program accepts the user-entered rows and uses the nested for loop and if else to traverse the rows and columns. Next, the program will print the X pattern of numbers.
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;
System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();
for (i = 0 ; i < rows; i++ )
{
for (j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%d", j + 1);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 12
1 12
2 11
3 10
4 9
5 8
67
67
5 8
4 9
3 10
2 11
1 12
Within this program, we replaced the for loop with a while loop to traverse the rows and columns and print the X shape number pattern. For more Number pattern programs, please click here.
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;
System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();
i = 0 ;
while (i < rows )
{
j = 0 ;
while (j < rows )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%d", j + 1);
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Numbers of Rows = 17
1 17
2 16
3 15
4 14
5 13
6 12
7 11
8 10
9
8 10
7 11
6 12
5 13
4 14
3 15
2 16
1 17
In this Java pattern program, we created an XNumPattern function to print the X number pattern on each row.
import java.util.Scanner;
public class Example
{
private static Scanner sc;
public static void main(String[] args)
{
sc = new Scanner(System.in);
System.out.print("Enter Numbers of Rows = ");
int rows = sc.nextInt();
XNumPattern(rows);
}
public static void XNumPattern(int rows)
{
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%d", j + 1);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}