Learn a Java Program to Print a Right Triangle Alphabet Pattern from A to Z. This pattern is created using nested for loops and character typecasting.
Code Explanation (Step-by-Step)
- Create a Scanner class object to accept user input.
- Initialize an integer variable c = 65, which stores the ASCII value of ‘A’.
- The outer for loop controls the number of rows.
- The inner for loop prints the alphabet characters in each row.
- The expression (char)(c + j) converts ASCII values into their corresponding alphabet characters.
- Each row prints one additional alphabet compared to the previous row, forming a right triangle pattern.
import java.util.Scanner;
public class AlphabetPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int n = sc.nextInt();
int c = 65;
System.out.println("Right Alphabetic Triangle Pattern :-");
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
System.out.print((char) (c + j));
}
System.out.println();
}
sc.close();
}
}
Enter the number of rows:
5
Right Alphabetic Triangle Pattern :-
A
AB
ABC
ABCD
ABCDE
Java 8 Program to Print Alphabets A to Z in Right Triangle Pattern
import java.util.Scanner;
import java.util.stream.IntStream;
public class AlphabetPattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows:");
int n = sc.nextInt();
System.out.println("Right Alphabetic Triangle Pattern :-");
IntStream.rangeClosed(1, n)
.forEach(i -> {
IntStream.rangeClosed(0, i - 1)
.forEach(j -> System.out.print((char) ('A' + j)));
System.out.println();
});
sc.close();
}
}
What is a Right Alphabetic Triangle Pattern?
A Right Alphabetic Triangle Pattern is a pattern in which alphabet characters are displayed in the shape of a right-angled triangle. Each row contains one more character than the previous row.
Example:
A
AB
ABC
ABCD
ABCDE
In this pattern:
• The first row contains A.
• The second row contains AB.
• The third row contains ABC.
• Each new row adds the next alphabet character, forming a right triangle.
Here are some Java-related programs that will help you understand Java concepts better: