Alphabet Triangle Pattern
Problem
Read n (1 to 26) and print a triangle of letters. Row i has the first i letters of the alphabet: A, AB, ABC, and so on.
Constraints
- 1 <= n <= 26
Examples
Input
3
Output
A AB ABC
Solutions
Letters are stored as numbers. A is the first letter, so A plus an index gives the next letters in the alphabet. In Java, a char is a number inside the computer. 'A' + 1 is the number of 'B', so we cast the result back to char.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Triangle of letters.
* Input : One integer n (rows).
* Output : n lines of letters.
* Approach: Convert a number to a letter.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
StringBuilder line = new StringBuilder();
// Step 2: Write the first "row" letters. Letter 0 is A, letter 1 is B, and so on.
for (int index = 0; index < row; index++) {
// Step 3: 'A' + index is a number. We cast it back to a char to get the letter.
line.append((char) ('A' + index));
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for rows and an inner loop for the letters or digits.
- Write the output for n = 3 and look for the rule.