codescracker


java

Java Program to Print Diamond Pattern



« Previous Program Next Program »


Print Diamond Pattern

To print diamond pattern in Java Programming, you have to use six for loops, the first for loop (outer loop) contains two for loops, in which the first for loop is to print the spaces, and the second for loop print the stars to make the pyramid of stars. Now the second for loop (outer loop) also contains the two for loop, in which the first for loop is to print the spaces and the second for loop print the stars to make the reverse pyramid of stars, which wholly makes Diamond pattern of stars as shown in the following program.

Java Programming Code to Print Diamond Pattern

Following Java Program ask to the user to enter the number of rows for the diamond dimension to print the diamond pattern on the screen:

/* Java Program Example - Print Diamond Pattern */
		
import java.util.Scanner;

public class JavaProgram
{
    public static void main(String args[])
    {
	
        int n, c, k, space=1;
        Scanner scan = new Scanner(System.in);
		
        System.out.print("Enter Number of Rows (for Diamond Dimension) : ");
        n = scan.nextInt();
		
        space = n-1;
		
        for(k=1; k<=n; k++)
        {
            for(c=1; c<=space; c++)
            {
                System.out.print(" ");
            }
            space--;
            for(c=1; c<=(2*k-1); c++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
		
        space = 1;
		
        for(k=1; k<=(n-1); k++)
        {
            for(c=1; c<=space; c++)
            {
                System.out.print(" ");
            }
            space++;
            for(c=1; c<=(2*(n-k)-1); c++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
		
    }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program print diamond pattern

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test