Home > database >  How do I create the triangle as in the given picture?
How do I create the triangle as in the given picture?

Time:03-08

Triangle [1]: https://i.stack.imgur.com/dTJkc.png

I am not able to get the image with my code. Help.

    for (int col=1; col<=size; col  ) {
            if(col >=row || col==row)    {
            System.out.print(col );
        }else {
            System.out.print(" ");
        }
    }
    System.out.println();
}```

CodePudding user response:

You can do it like this, and if you want a bigger or smaller triangle, adjust the value of the variable numberOfRows.

    Integer numberOfRows = 8;

    for (int i = numberOfRows; i > 0; i--) {
        for (int k = 0; k < numberOfRows - i; k  ) {
            System.out.print("  ");
        }
        for (int j = 1; j <= i; j  ) {
            System.out.print(j   " ");
        }
        System.out.println();
    }

There are cleaner and better ways of doing this, but that should do the job.

  1. The first loop takes care of displaying the right amount of rows, iterating through numberOfRows.

  2. The second loop takes care of displaying spaces before each row, according to the image. Each row have an increasing amount of spaces before the row starts, so for the first one we have zero spaces before, for the second, we have one and so on. So the value that increases according to this logic as the i value change, is the difference between numberOfRows and the value i.

  3. The third loop takes care of displaying the right amount of numbers in each row. The first row should have the same amount of numbers as the number of rows. So increasing the row number by one, we'll need to decrease the amount of numbers in the current row.

CodePudding user response:

    int x = 8;
    int y = -1;
    for (int i = 1; i<=8; i  ){
        for (int j = 0; j <=y; j  ) {
            System.out.print("  ");

        }
        for (int j = 1; j <= x; j  ) {
            System.out.print(j    " ");
        }
        x--;
        y  ;
        System.out.println();
    }

CodePudding user response:

You can do it like this:

for(int i = 1; i <= 8; i  ){
    for(int j = 2; j <= 9; j  ){
        int k = j - i;
        if(k > 0) System.out.print(k   " ");
        else System.out.print("  ");
    }
    System.out.println();
}

A bit shorter is that (with use of the Ternary Operator)

for(int i = 1; i <= 8; i  ){
    for(int j = 2; j <= 9; j  ){
        int k = j - i;
        System.out.print(k > 0 ? k   " " : "  ");
    }
    System.out.println();
}  
  • Related