Print a ‘Y’ shaped pattern from asterisks in N number of lines.
Note : N is even.
Example 1 :
Input : N = 4
Output :
* *
* *
*
*
Example 2 :
Input : N = 8
Output :
* *
* *
* *
* *
*
*
*
*
Citrix interview question :
We have to print Y shaped pattern. From example we can easily observe pattern of upper part and lower part of Y is different. So, we have to make different logic for upper part and lower part of Y.
Explanation :
For n = 8 we have to print 8 rows and first n/2=4 rows ( upper part ) are “V” shaped and last n/2=4 rows are “|” shaped.
Upper part of Y :
n=8 number of star in every row is 2 * * i=0 no.space before star = 0 | no of space in between star = 7 * * i=1 no.space before star = 1 | no of space in between star = 5 * * i=2 no.space before star = 2 | no of space in between star = 3 * * i=3 no.space before star = 3 | no of space in between star = 1 Generally i=n/2-1 no.space before star = i | no of space in between star = (n-1)-=2;
So, We can take a for loop and in the for loop we first store i spaces then 2 stars and then make a variable initializing with n-1 and print spaces n-1 times then decrease the variable value by 2.
Lower part of Y :
1 star will be printed after n/2 spaces
* i=4 no.space before star = n/2
* i=5 no.space before star = n/2
* i=6 no.space before star = n/2
* i=7 no.space before star = n/2
We can do it easily with a another for loop. In the for loop for each iteration print n/2 space and 1 star.
Implementation :
import java.io.*;
class Main {
public static void main (String[] args) {
int n = 8;
String[] s = yShapedPattern(n);
for(int i=0; i<n; i++){
System.out.println(s[i]);
}
}
static String[] yShapedPattern(int N) {
String[] s = new String[N];
int sp = N-1;
int i = 0;
//for upper part
for(; i<N/2; i++,sp-=2){
StringBuilder sb = new StringBuilder();
for(int j=0; j<i; j++){
sb.append(" ");
}
sb.append("*");
for(int j=0; j<sp; j++){
sb.append(" ");
}
sb.append("*");
s[i]= sb.toString();
}
//lower part
for(; i<N; i++){
StringBuilder sb = new StringBuilder();
for(int j=0; j<N/2; j++){
sb.append(" ");
}
sb.append("*");
s[i]= sb.toString();
}
return s;
}
}
Output :
* *
* *
* *
* *
*
*
*
*