When I was using for loop for the same program while printing values and spaces it was not working, may I know the reason why?
Use of for loop
hey @rg361 I have told you about your mistakes in the chat option. Below is code for your reference.
import java.util.Scanner;
public class Pattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = 7;
int row = 1;
int nsp1 = n - 1;
int nsp2 = -1;
int nst = 1;
int value1 = row;
int value2 = 1;
while (row <= n) {
for (int csp1 = 1; csp1 <= nsp1; csp1++) {
//two spaces not single
System.out.print(" ");
}
for (int cst1 = 1; cst1 <= nst; cst1++) {
System.out.print(value1+" ");
value1 = value1 - 1;
}
for (int csp2 = 1; csp2 <= nsp2; csp2++) {
//two spaces not single
System.out.print(" ");
}
if (row != 1 && row != n) {
for (int cst2 = 1; cst2 <= nst; cst2++) {
System.out.print(value2+" ");
value2 = value2 + 1;
}
}
System.out.println();
if (row <= n / 2) {
nst=nst+1;
nsp1=nsp1-2;
nsp2=nsp2+2
;
value1=row+1;
value2=1;
} else {
nst=nst-1;
nsp1=nsp1+2;
nsp2=nsp2-2;
value1=n-row;
value2=1;
}
row = row + 1;
}
}
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.