Matthieu Topize
Matthieu Topize

Reputation: 41

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++).

Upvotes: 2

Views: 1826

Answers (2)

user4910279
user4910279

Reputation:

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();
        }
    }

Upvotes: 1

Mureinik
Mureinik

Reputation: 311163

You can't print "backwards". The trick here is to print spaces before the asterisks in each line, starting with no spaces in the first line:

int n = 4; // Just an example, this should be taken from user input
for (int i = 0; i < n; ++i) {
    for (int j = 0; j < i; ++j) {
        System.out.print(' ');
    }
    for (int j = 0; j < (n - i); ++j) {
        System.out.print('*');
    }
    System.out.println();
}

Upvotes: 1

Related Questions