How to make box cross pattern in java

Making box cross pattern





Steps to do this:-

1.take 3 integers i,j,n (i and j is for loop and n id for user input length)

2. take value from user

3.start the i loop (i=1;;i<=n;i++) and start the j loop inside it (j=1;j<=n;j++) here i will print the row and j is for column 

4. check if(i==1||j==1||i==n || j==n ||i==j || i+j==n+1) then print ("*") else print (" ")  close the j loop and print a new line inside in i loop .

explanation of if block

when, i==1 it will print the (***********) 1st row

when,j==1 it will print the( *) first column 
when, i==j it will print the 

  *
    *
      *
         * 
left to right line

when, i+j==n+1 it will print
                   *
                 *
              *
           *
         *
it will print the right to left pattern 

and when, i==n and j==n it will print the last row and last column according to user input

5. save and run

The Source Code

import java.util.Scanner;
class boxcross
{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int i,j,n;// i,j is for loop and n is for user input length
        System.out.println("enter the length");
        n=s.nextInt();
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                if(i==1||j==1||i==n||j==n||i==j||i+j==n+1)
                {
                    System.out.print("*");
                }
                else
                {
                    System.out.print(" ");
                }
            }
            System.out.println();// for new line
        }
    }
}

OUTPUT





Watch My Video

Comments

Popular Posts