Imprime un triangulo diagonal en java
Frecuentes
Visto 3,861 veces
0
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
*
**
***
****
*****
******
5 Respuestas
2
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
0
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
0
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
0
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
0
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 java or haz tu propia pregunta.
temporarily replace the spaces with + or some other character and it will be a bit more evident what is happening - vandale
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? - Rahul
The code you give us does not produce the second pattern - vandale
It is more related to algorithms not just java - me_digvijay