Java Program to print the diamond shape

Java 8Object Oriented ProgrammingProgramming

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:\n\n");
      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("\n");
         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("\n");
         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:\n\n");
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("\n");
   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("\n");
   s++;
}
raja
Published on 06-Dec-2018 06:38:56
Advertisements