

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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++; }
- Related Questions & Answers
- C++ Program to print the diamond shape
- Python Program to print the diamond shape
- Java Program to Print Diamond Star Pattern
- Java Program to Print Half Diamond Star Pattern
- Program to print Diamond Pattern in C
- Program to print Inverse Diamond pattern on C++
- C Program to print hollow pyramid and diamond pattern
- Program to print hollow pyramid and diamond pattern in C++
- Function to create diamond shape given a value in JavaScript?
- How to print the stars in Diamond pattern using C language?
- How to print a diamond using nested loop using C#?
- Java Program to Print the ASCII values
- Java Program to Print a Collection
- Java Program to Print an Integer
- Java Program to Print a String
Advertisements