Alphabet Y pattern in java

Printing Y shape pattern in java

Disclaimer :-
to understand what happen in this pattern i am recommending you to watch my blog that "how to make V shape pattern" 
to watch this click here

Steps to do this:-
1. take 3 integers i,j,n ( i and j is for loop and n is for user input length )

2. scan the length 

3. now take two integers 
int p1 =1;
and int p2=n*2-1;
4. start the i for loop from (i=1;i<=n;i++) and start the j loop inside i loop and (j=1;j<=n*2;j++) and check if (j==p1||j==p2) and
print "*"  else print " " (a blank string) close the j loop and do this
p1++;
p2--;
print a new line close the i loop

now the upper part is complete

and time for the lower part

5.start the i loop another time (i=1;i<=n;i++) and start the j loop inside i loop from (j=1;j<=n;j++) check 
if(j==n)
{
print"*";
else
{
print " ";
}
close the j loop and print a new line inside i loop and

now the lower part is complete 

6..save and run


The Source Code

import java.util.Scanner;
 class ypat {
     public static void main(String[] args) {
         Scanner s=new Scanner(System.in);

         int i,j,n;

         System.out.println("enter the length");
         n=s.nextInt();

         int p1=1;
         int p2=n*2-1;

         for (i=1;i<=n;i++)
         {
             for (j=1;j<=n*2;j++)
             {
                 if(j==p1||j==p2)
                 {
                     System.out.print("*");
                 }
                 else
                 {
                     System.out.print(" ");
                 }
             }
             p1++;
             p2--;
             System.out.println();
         }
         for (i=1;i<=n;i++)
         {
             for (j=1;j<=n;j++)
             {
                 if(j==n)
                 {
                     System.out.print("*");
                 }
                 else {
                     System.out.print(" ");
                 }
             }
             System.out.println();
         }

     }
}



OUTPUT



Watch My Video

Comments

Popular Posts