John
John

Reputation: 65

Upside down right triangle in Java

I need to do this:

*****
 ****
  ***
   **
    *

and I have this code:

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

which outputs this:

*****
****
***
**
*

I cant figure out how to implement the spaces. Any help appreciated.

Upvotes: 1

Views: 23682

Answers (4)

Shaahul
Shaahul

Reputation: 548

    int count = 6;
    for(int i=0; i<=count; i++) {

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

        for (int j = 0; j <= (count - i); j ++) {
            System.out.print("*");
        }

        System.out.println();
    }

you can pass your value into count, its works pretty nice.

Upvotes: 0

user3437460
user3437460

Reputation: 17454

Just print k number of spaces before start of every line.

To solve this kind of problems, it will be easy if you break it down and observe the pattern.

*****  0 space
 ****  1 space
  ***  2 spaces
   **  3 spaces
    *  4 spaces

After taking note of this pattern, you ask yourself will you be able to print this?

0*****
1****
2***
3**
4*

We see that the number is similar to the start of every line. Hence we could make use of variable i. (your outer loop counter) and we have..

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

Now, you just have to convert your numbers at the start of every line to the number of spaces and you have..

for (int i=0; i<5; i++){
    for(int k=0; k<i; k++)    //using i to control number of spaces
        System.out.println(" ");
    for (int j=5; j>i; j--){ 
        System.out.print("*");
    }
    System.out.println("");
}

Upvotes: 1

Wander Nauta
Wander Nauta

Reputation: 19625

Here's a solution with one less loop than the other answers, if you really want to wow the person who's grading your assignment:

for (int y = 0; y < 5; y++) {
    for (int x = 0; x < 5; x++) {
        System.out.print((x >= y) ? "*" : " ");
    }

    System.out.println();
}

Upvotes: 2

Tunaki
Tunaki

Reputation: 137084

You need to use two for-loops: one for the number of spaces and one for the number of *:

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

Java 8 solution:

IntStream.range(0, 5).forEach(i -> {
    IntStream.range(0, i).forEach(j -> System.out.print(" "));
    IntStream.range(i, 5).forEach(j -> System.out.print("*"));
    System.out.println();
});

Upvotes: 6

Related Questions