Create a diamond shape using for loop in java

Asked By 0 points N/A Posted on -
qa-featured

Can you help me create a program that will display a diamond shape using for loop in Java?

Have you done this program before? Can I have the code? Thanks.

SHARE
Answered By 0 points N/A #102006

Create a diamond shape using for loop in java

qa-featured
Diamond Shape.
import java.io.* ;
public class diamond {
    public static void main(String args[]){
        int len =5 , p, q = len , r , s = 1 ; 
        for ( int row = 0 ; row <= len ; row++ ){                    //The first half of diamond
            for( p = 0; p < q ; p++){         //leading spaces of a line keeps decreasing by 1
                System.out.print(" ");
            }
            for( r = 0 ; r<s ; r++){           //trailing *s of the line keeps increasing by 2.
                System.out.print("*");
            }
            q = q-1;
            s = s+2;
            System.out.println("");
        }
        q = 1;
        s = len * 2 – 1;
        for( int row = 0;row < len ; row++){                 //for second half of diamond
            for(p = 0 ; p < q; p++){       //leading spaces of the line keeps decreasing by 1
                System.out.print(" ");
            }
            for( r = s; r>0 ;r–){               //trailing *s of the line keeps decreasing by 2
                System.out.print("*");
            }
            q = q + 1;
            s = s – 2;
            System.out.println("");
        }
    }
 

 

Let me Explain it
The entire code prints a diamond shape of stars. First you need to ask for the maximum number of stars. More the number of stars, the bigger is the diamond.
The program has two steps.
First, Put continuous spaces from the left decreasing one space per row. Start with the maximum number of stars minus one.
Then put continuous stars from the left increasing one star per row.
Stop the above after a fixed number of stars.
 
Second, Put continuous spaces from the left increasing one space per row.
Then put continuous start from the left decreasing two stars per row starting from the number of stars minus one at end of the first step.
Stop when number of stars is one.
Thus you get a diamond shape.

Related Questions