Using a for loop to print a pattern in Java [closed]
I am trying to print out this pattern using a for loop in Java but I am kind of stuck.
zzzzz
azzzz
aazzz
aaazz
aaaaz
aaaaa
I can print:
a
aa
aaa
aaaa
aaaaa
using:
String i = " ";
int a = 0;
for (i="a";i.length()<=5;i=i+"a")
System.out.println(i);
and
zzzzz
zzzz
zzz
zz
z
using:
String i = " ";
for (i="zzzzz";i.length()>0;i=i.substring(0,i.length()-1))
System.out.println(i);
But I can't figure out how to combine them. I was thinking about replacing the substring of i
and increasing the value of the end index by one 开发者_如何学运维everytime but not sure of to code it. I started with something like this:
String i = " ";
String b = " ";
for (i="zzzzz";i="aaaaa";i=i.replace(i.substring(0,))
System.out.println(i);
Any ideas?
Pseudocode :
for(i <- 0 to 5) {
print( i times "a" followed by (5 - i) times "z")
print a new line
}
Now implement this in Java.
You can increment or decrement more than one variable with the loop
for (int a = 0, z = 5; a <= 5 ; a++, z-- )
{
System.out.println(a+" "+z);
}
would output
0 5
1 4
2 3
3 2
4 1
5 0
In java:
public class Pattern {
public static void main(String [] args) {
for(int i=0;i<6;i++) { //This works out the number of lines
String line = "";
for(int a=0;a<i;a++) {
line+="a";
}
for(int z=0;z<(5-i);z++) {
line+="z";
}
System.out.println(line);
}
}
}
Z = 5
A = 0
while ( Z >= 0 )
{
for ( i = 0; i < A; i++ ) print 'A';
for ( i = 0; i < Z; i++ ) print 'Z';
print newline;
++A;
--Z;
}
is one way.
String AA = "aaaaa";
String ZZ = "zzzzz";
for (int i = 0; i <= 5; i++) {
System.out.println(AA.substring(i) + ZZ.substring(5 - i));
}
Use one additional variable to keep position of a/z border. Increase value of that variable in each iteration.
You might try the following:
public class pattern2
{
public static void main()
{
int i,j,k,num=0;
for(i=1;i<=6;i++)
{
for(j=1;j<=num;j++)
System.out.print("a");
for(k=6;k>i;k--)
System.out.print("z");
System.out.println();
num++;
}
}
}
精彩评论