DPabst
DPabst

Reputation: 35

Need a increasing number of spaces before each line

I need this output

5   
 4     
  3 
   2 
    1 
     0 

the Code I have:

public static void outputEleven()
{
    System.out.println("");
    for(int x=5; x>=0; x--)
    {   
        System.out.println(x);
        for(int s=0; s<=5; s++)
        {
            System.out.print(" ");
        }
    }

}

The output I'm getting:

5
      4
      3
      2
      1
      0

Why am I getting this output? How can I get the output desired?

Upvotes: 0

Views: 1441

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201439

In your inner loop, you want to print i spaces before printing the value. Something like,

for (int i = 0; i < 6; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print(" ");
    }
    System.out.println(5 - i);
}

Outputs (as requested)

5
 4
  3
   2
    1
     0

Alternatively, for the same output, counting backwards like

for (int x = 5; x >= 0; x--) {
    for (int s = 0; s < 5 - x; s++) {
        System.out.print(" ");
    }
    System.out.println(x);
}

Upvotes: 2

Related Questions