In this Java pattern program, we show the steps to print the X pattern of alphabets 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 If else statement helps to print the alphabet in an X pattern.
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();
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%c", a + j);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}
Enter Numbers of Rows = 11
A K
B J
C I
D H
E G
F
E G
D H
C I
B J
A K
Within this program, we replaced the for loop with a while loop to traverse the rows and columns of X and print the alphabet in an X pattern shape. For more Alphabet Patterns, 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, a = 65;
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("%c", a + j);
}
else
{
System.out.printf(" ");
}
j++;
}
System.out.println();
i++;
}
}
}
Enter Numbers of Rows = 15
A O
B N
C M
D L
E K
F J
G I
H
G I
F J
E K
D L
C M
B N
A O
In this Java pattern program, we created an XPatternofAlpha function to print the X shape or pattern of user-given rows filled with the alphabet.
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();
XPatternofAlpha(rows);
}
public static void XPatternofAlpha(int rows)
{
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j < rows; j++ )
{
if (i == j || j == rows - 1 - i)
{
System.out.printf("%c", a + j);
}
else
{
System.out.printf(" ");
}
}
System.out.println();
}
}
}