Java Program to print the diamond shape


A diamond shape can be printed by printing a triangle and then an inverted triangle. An example of this is given as follows −

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      int n = 6;
      int s = n - 1;
      System.out.print("A diamond with " + 2*n + " rows is as follows:

");       for (int i = 0; i < n; i++) {          for (int j = 0; j < s; j++)          System.out.print(" ");          for (int j = 0; j <= i; j++)          System.out.print("* ");          System.out.print("
");          s--;       }       s = 0;       for (int i = n; i > 0; i--) {          for (int j = 0; j < s; j++)          System.out.print(" ");          for (int j = 0; j < i; j++)          System.out.print("* ");          System.out.print("
");          s++;       }    } }

Output

A diamond with 12 rows is as follows:

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Now let us understand the above program.

The diamond shape is created by printing a triangle and then an inverted triangle. This is done by using nested for loops. The code snippet for the upper triangle is given as follows.

int n = 6;
int s = n - 1;
System.out.print("A diamond with " + 2*n + " rows is as follows:

"); for (int i = 0; i < n; i++) {    for (int j = 0; j < s; j++)    System.out.print(" ");    for (int j = 0; j <= i; j++)    System.out.print("* ");    System.out.print("
");    s--; }

The code snippet for the inverted lower triangle is given as follows.

s = 0;
for (int i = n; i > 0; i--) {
   for (int j = 0; j < s; j++)
   System.out.print(" ");
   for (int j = 0; j < i; j++)
   System.out.print("* ");
   System.out.print("
");    s++; }

Updated on: 25-Jun-2020

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements