views:

626

answers:

7

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 cant 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?

A: 

Use one additional variable to keep position of a/z border. Increase value of that variable in each iteration.

Roman
A: 

Take a look at this: http://stackoverflow.com/questions/1446181/simple-fun-c-asterisk-hill

Most of the implementations are in C/C++ but you can apply the concept to java.

JonH
so i should be using a nested for loop instead right?
Dan
A: 
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.

IVlad
+4  A: 

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
Ledhund
+1 This is the right answer.
Chinmay Kanchi
+7  A: 

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.

missingfaktor
Simplest answer here.
Andrew Duffy
@Rahul G - Like the way you gave him direction without solving the problem
SOA Nerd
+1  A: 

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);       
        }

    }

}
Adam
For large `i`, this is going to be far more inefficient, though since you spend much less time blocking for I/O, it might turn out to be a very large `i` indeed :)
Chinmay Kanchi
@Chinmay Kanchi - that is highly unlikely for this particular piece of code.
JonH
Both good points. I did think that it would be easier to understand for the poster as written though.
Adam
@JonH: True enough. Just thought it was worth mentioning.
Chinmay Kanchi
A: 
String AA = "aaaaa";
String ZZ = "zzzzz";

for (int i = 0; i <= 5; i++) {
    System.out.println(AA.substring(i) + ZZ.substring(5 - i));
}