0

OK I'm embarrassed I have to ask this but I'm stuck so here we go, please nudge me in the right direction. We need to create this using a nested loop:

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

Here's what I came up with.

int row,col; 
for(row = 5; row >= 1; row--)
{ 
    for (col = 0; col < 5 - row; col++)
        println("");

    for(col = 5; col >= row; col--)
        print("*");
}

It ALMOST works but it prints spaces between each row and I cannot for the life of me figure out why.

James
  • 11
  • 1
  • 2

5 Answers5

2

Why not just one println(""); at the end of the loop instead of looping that statement? You only need the one new line per row of stars.

Dolphiniac
  • 1,632
  • 1
  • 9
  • 9
1

I think you only want to use one inner loop, to print each row of stars. Then print a newline at the end of each row:

int row, col;
for(row = 1; row <= 5; row++) {
    for(col = 0; col < row; col++) {
        print("*");
    }
    println("");
}
Mox
  • 571
  • 5
  • 14
0

Why don't you do this:

for (int row = 0; row < 5; row++) {
        for (int col = 0; col <= row; col++) {
            System.out.print("*");
        }
        System.out.print("\n");
}
Houbie
  • 1,406
  • 1
  • 13
  • 25
0

Why don't you simplify it?

int row, col;
for(row=0; row<5; row++) {
    for(col=0;col<=row;col++) {
        System.out.print("*");
    }
    System.out.println();
}

Print one row at a time, and then print the line-end


For the sake of only one I/O operation, a function may be a suitable approach:

public String starStarcase(int rows) {
    int row, col;
    String str="";
    for(row = 0; row < rows; row++) {
        for(col = 0; col <= row; col++) {
            str += "*";
        }
        str += "\n";
    }
    return str;
}

To print the result:

System.out.println(starsStaircase(5));
Barranka
  • 20,547
  • 13
  • 65
  • 83
0

You can try this, it should work:

for(int j = 0; j < row; j++){
    for(int i = 1; i <= row; i++){
        System.out.print(i < row-j ? " " : "#");
    }
    System.out.println("");
}
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68