How to print pattern of alphabet in java?

Printing patterns have been solved in last post How to print triangle pattern in java?

But printing pattern of alphabets gets a bit tricky and requires just an extra bit of your attention. Just take variable as char and assign the integer value into char by typecasting into char.

Syntax -: char ch=(char) num; // here num is integer type.

Code for printing aplbhabet in triangle pattern -:

import java.util.Scanner;
public class alpha_pattern {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.err.println(“Input number of Characters : “);
int n=s.nextInt();
char ch;
System.out.println(n+” = “+(char)(‘A’+(n-1)));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(” “);
}
for(int k1=1;k1<=i;k1++)
{
ch=(char)(‘A’+(k1-1));
System.out.print(ch);
}
for(int k2=i-1;k2>=1;k2–)
{
ch=(char)(‘A’+(k2-1));
System.out.print(ch);
}
System.out.println();
}
}
}

Output -:

Leave a Reply