Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to print the following pattern:
A
A B
A B C
A B C D
A B C D E

Java Code Example — Pattern Programs

ADVERTISEMENT

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

  1. Use an outer loop with a char variable (i) running from 'A' to 'E'.
  2. Inside, use an inner loop with a char variable (j) running from 'A' to i.
  3. Print the character j followed by a space.
  4. 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 char data 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 j from 'A' up to the current row letter i, 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 char variables in the loop header.
ADVERTISEMENT