Matthieu Topize Matthieu Topize - 1 month ago 7
Java Question

Java for loop asterisks

I am trying to create a program that would display the following result in that order.


N=1
*
N=2
**
*
N=3
***
**
*



Here is my code:

public static void main(String[] args) {
int Output;

int asterisks;
Scanner input= new Scanner(System.in);
System.out.println("Enter number of output you want: ");
Output= input.nextInt();

for(int j=1; j<=Output;j++){
System.out.println("N= "+ j);


for (int i=j; i>=1; i--){
asterisks=i;
for(int k=1; k<= asterisks; k++){
if(k==asterisks){
System.out.println("*");

}
else
System.out.print("*");
}
}

}
}
}



But so far the code I wrote is outputing


N= 1
*
N= 2
**
*
N= 3
***
**
*
N= 4
****
***
**
*


So I am guess that I need to inverse this
for(int k=1; k<= asterisks; k++)
.

Answer

Try this.

    for (int i = 1; i <= Output; ++i) {
        System.out.println("N= " + i);
        for (int j = 0; j < i; ++j) {
            for (int k = 0; k < i; ++k) {
                System.out.print(k < j ? " " : "*");
            }
            System.out.println();
        }
    }