I am a beginner to Java and have studied up to loops only. After loops lecture above pattern was given to print as homework. I have successfully managed to print this pattern with following code:
public class Main {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
{
System.out.print("*");
}
for(int j=1; j<=2*(n-i); j++){
System.out.print(" ");
}
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
{
System.out.print("*");
}
System.out.println(" ");
}
for (int i = n; i >= 1; i--) {
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
System.out.print("*");
for(int j=1; j<=2*(n-i); j++){
System.out.print(" ");
}
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
System.out.print("*");
System.out.println(" ");
}
}
}
I don't know if I have followed the best possible approach according to as much I have studied java until now. Please suggest if any improvements can be made.