Triangle printing (for loop)
I'm trying to create this output using the for loop :
aaaaa
*aaaa
o*aaa
oo*aa
ooo*a
this is the code i wrote:
Code Java:
public class Triangles
{
public static void main(String args[])
{
int q=5;
for (int p=1; p<=q; p++ )
{
for (int x=1; x<p; x++)
System.out.print("o");
System.out.print("*");
for (int y=q; y>=p; y--)
System.out.print("a");
System.out.println("");
}
}
}
but this is the output i get:
*aaaaa
o*aaaa
oo*aaa
ooo*aa
oooo*a
i tried changing the code a few times but all i get are weird outputs.
Can anybody please tell me whats wrong with my code? and if its possible tell me which part should i fix.
THANKS for any help :x
Re: Triangle printing (for loop)
aaaaa
*aaaa
o*aaa
oo*aa
ooo*a
Ok
I take it you start with all a's
then you change the first a to a *
then you change that star to an o and move the * over to the second a
and then you continue
Re: Triangle printing (for loop)
Code java:
public class Triangles
{
public static void main(String args[])
{
/* int q=5;
for (int p=1; p<=q; p++ )
{
System.out.println("P is: " + p);
for (int x=1; x<p; x++)
System.out.println("X is: " + x);
System.out.print("o");
System.out.print("*");
for (int y=q; y>=p; y--)
System.out.println("Y is: " + y);
System.out.print("a");
System.out.println("");
}
*/
String str = "aaaaa";
String[] str2 = new String[5];
System.out.println(str);
for (int i =0; i < 5; i++)
{
char[] chars = new char[str.length()];
for (int x =0; x < chars.length; x++)
{
chars[x] = str.charAt(x);
}
if (str.charAt(i) == 'a')
{
chars[i] = '*';
str2[i] = new String(chars);
str = str2[i];
if ( i > 0 && str.charAt(i-1) == '*' )
{
chars[i-1] = 'o';
str2[i] = new String(chars);
str = str2[i];
}
System.out.println(str2[i]);
}
}
}
}
aaaaa
*aaaa
o*aaa
oo*aa
ooo*a
oooo*