Write a program to print the following pattern:
A
A B
A B C
A B C D
A B C D E
Objective
Write a Java program to print a right-angled triangle using alphabet characters.
Algorithm / Approach
- Use an outer loop with a
charvariable (i) running from'A'to'E'. - Inside, use an inner loop with a
charvariable (j) running from'A'toi. - Print the character
jfollowed by a space. - Print a newline at the end of the outer loop.
Test.java
class Test {
public static void main(String[] a)
{
for(char i = 'A'; i<='E'; i++) {
for(char j = 'A'; j<=i; j++) {
System.out.print(j+" ");
}
System.out.println();
}
}
}
Explanation of the Program
- Java allows the use of
chardata types directly in loop counters. - Characters in Java are stored as ASCII (or Unicode) integer values behind the scenes. 'A' is 65, 'B' is 66, and so on.
- By iterating
jfrom 'A' up to the current row letteri, the program prints an increasing sequence of letters on each row.
Complexity
Time Complexity
O(n2)
Space Complexity
O(1)
Common Mistakes
- Trying to print an integer and cast it to char, which is valid but makes the code much harder to read than just using
charvariables in the loop header.