Imprime un triangulo diagonal en java

I need to print out a triangle that looks like this:

*
 **
  ***
   ****

The code I have right now

    for(line = 0; line < size; line++){
        for(count = 0; count < line; count++){
            System.out.print("*");
            for(space = 0; space < line; space++)
                System.out.print(" ");
        }
            System.out.println();
    }

entiendo esto

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

preguntado el 27 de noviembre de 13 a las 04:11

temporarily replace the spaces with + or some other character and it will be a bit more evident what is happening -

What exactly is that pattern you're trying to achieve? I mean you shown it but I don't see a fixed pattern there. Can you describe that in words? -

The code you give us does not produce the second pattern -

It is more related to algorithms not just java -

5 Respuestas

for(line = 0; line < size; line++){
    for(space = 0; space < line; ++space)
        System.out.print(" ");
    for(count = 0; count < line; count++)
        System.out.print("*");
    System.out.println();
}

respondido 27 nov., 13:04

You're printing the spaces on the same line. Call System.out.println(); before printing the spaces.

Editar - Ejemplo:

for (line = 0; line < size; line++){
    for(space = 0; space < line - 1; space++)
        System.out.print(" ");
    for (count = 0; count < line; count++)
        System.out.print("*");
    System.out.println();
}

respondido 27 nov., 13:04

You need to first print the prefix spaces. and then print the stars.

Pruébalo con esto:

    int line = 0;
    int size = 6;
    int count = 0;
    int space = 0;
    for (line = 0; line < size; line++) {
        //print spaces
        for (space = 0; space < line; space++)
            System.out.print(" ");

        //Print stars
        //Note: here count condition should be count < line+1, rather than count < line
        //If you do not do so, the first star with print as space only.
        for (count = 0; count < line+1; count++) {
            System.out.print("*");

        }
        System.out.println();
    }

Salida en consola:

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

respondido 27 nov., 13:04

  class Pyramid 
   {
    public static void main(String args[])
    {
       java.util.Scanner pyr=new java.util.Scanner(System.in);
       System.out.println("type a no. to make Pyramid");
       int n= pyr.nextInt();
       for (int i=1; i<=n; i++)
       {
           for(int j=n; j>i; j--)
           {
               System.out.print(" ");
           } 
           for(int k=1; k<=i; k++)
           {
              System.out.print("* ");
           }
            System.out.println(); 
        }
    }

Respondido el 25 de junio de 15 a las 19:06

Just printing the spaces before the asterisks would be fine.

Respondido el 10 de Septiembre de 16 a las 15:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.