Is there a better way we can solve this question , do we have to deal with corner cases explicitly?
A better approach to Pattern 19?
package pattern_practice_questions;
import java.util.Scanner;
public class Pattern19 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int nst = n/2;
int nsp = 1;
int rows = 1;
while (rows <= n) {
if (rows == 1 || rows == n) {
for (int cst = 1; cst <= n; cst++) {
System.out.print("*");
}
} else {
for (int cst = 1; cst <= nst; cst++) {
System.out.print("*");
}
for (int csp = 1; csp <= nsp; csp++) {
System.out.print(" ");
}
for (int cst = 1; cst <= nst; cst++) {
System.out.print("*");
}
if (rows <= n / 2) {
nst -= 1;
nsp += 2;
} else {
nst += 1;
nsp -= 2;
}
}
System.out.println();
rows++;
}
}
}
This is my code
According to me, for pattern questions, there is just a single approach, mostly, no better alternative.
okay so it’s right if I deal with corner cases using if else?
Yes definitely you can do that
1 Like