Pattern 27 want to ask for the error in my code ,sending it in the description section

Scanner scn=new Scanner(System.in);
int row=scn.nextInt();
int nsp=row-1;
int cst=1;
int m=1;
for(int i=1;i<=row;i++)
{
for(int j=1;j<=nsp;j++)
{
System.out.print(" “);
}
for( m=1;m<=cst;)
{ if((m<=i))
{ System.out.print(m);
m++;
}
else
{ System.out.print(m-1);
m–;
}
}
for(int j=1;j<=nsp;j++)
{
System.out.print(” ");
}
cst+=2;
nsp–;
System.out.println();
}

not resolved ,still there is an issues .kindly check it once so that i can proceed further

Your loop of m was wrong. Basically you are changing the variable m inside loop and condition was also on the same variable. Below is the correct code with some changes.

public static void main(String[] args) {

	Scanner scn = new Scanner(System.in);
	int row = scn.nextInt();

	int nsp = row - 1;
	int cst = 1;
	int m = 1;

	for (int i = 1; i <= row; i++) {

		int val = 1;

		for (int j = 1; j <= nsp; j++) {
			System.out.print(" ");
		}

		for (m = 1; m <= cst; m++) {
			if ((m < i)) {
				System.out.print(val);
				val++;
			} else {
				System.out.print(val);
				val--;
			}
		}

		for (int j = 1; j <= nsp; j++) {
			System.out.print(" ");
		}

		cst += 2;
		nsp--;
		System.out.println();
	}

}
1 Like