Numeric-Alphabet Pyramid Hybrid

This program prints a pyramid alternating numbers and alphabets.

Problem Statement

Write a Java program that prints a pyramid of 6 rows where odd rows have numbers and even rows have alphabets.

Source Code

1 public class NumericAlphabetPyramidHybrid {
2 public static void main(String[] args) {
3 int n = 6, num=1;
4 char ch='A';
5 for(int i=1; i<=n; i++) {
6 for(int j=i; j<n; j++) System.out.print(" ");
7 for(int j=1; j<=2*i-1; j++) {
8 if(i%2==1) System.out.print(num++ + " ");
9 else {
10 System.out.print(ch + " ");
11 ch++;
12 if(ch>'Z') ch='A';
13 }
14 }
15 System.out.println();
16 }
17 }
18 }

Program Output

     1      
    A B C    
   2 3 4 5 6  
  D E F G H I J 
 8 9 10 11 12 13 14 15 
 K L M N O P Q R S T U 

Explanation

The condition i%2==1 decides whether the current row fills its cells with sequential numbers or sequential alphabets, so odd and even rows alternate between numeric and alphabetic sequences within a pyramid shape.

Quick Links to Explore