Concentric Triangle of Stars and Numbers

This program prints concentric triangles alternating stars and numbers.

Problem Statement

Write a Java program that prints concentric triangles where odd rows have stars and even rows have numbers.

Source Code

1 public class ConcentricTriangleStarsNumbers {
2 public static void main(String[] args) {
3 int n = 6;
4 for(int i=1; i<=n; i++) {
5 for(int j=i; j<n; j++) System.out.print(" ");
6 for(int j=1; j<=2*i-1; j++) {
7 if(i%2==1) System.out.print("*");
8 else System.out.print(i);
9 }
10 System.out.println();
11 }
12 }
13 }

Program Output

     *     
    2 2    
   *****   
  4 4 4 4 4 
 ********* 
66666666666

Explanation

The condition i%2==1 alternates each row between printing a run of stars or a run of the row's own number, forming a hybrid triangle where odd rows use stars and even rows use numbers.

Quick Links to Explore