English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

This is driving me insane!!!!! Why the hell does this output a square of hashes? The first for loop produces one hash five times, which are printed one by one and followed by a line termination each time. Meanwhile the second for loop does the same, so why isn't the output two vertical lines of five hashes? Someone please explain this to me before I kill myself!!!


public class HashSquare {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
{
for(int m=0 ; m<5 ; m++)

{
for(int n = 0; n<5 ; n++)

System.out.print ("#");
System.out.println("");
}

}
}
}

2007-10-12 06:22:45 · 6 answers · asked by Anonymous in Computers & Internet Programming & Design

6 answers

The loops are nested. That means that for each time the outer loop ('m') runs, the inner loop ('n') runs five times.

You might be able to understand this easier if you printed the value of n instead of a hash:
System.out.print(n);

2007-10-12 11:30:14 · answer #1 · answered by Daniel R 6 · 0 0

It's doing what you told it to do. Your second for loop is embedded within the first so that the second one produces a line of five hashes, and the first for loop causes this to be repeated 5 times, producing a square.

If you want 2 vertical lines of 5 hashes change the first loop to only repeat twice i.e.
for(int m=0 ; m<2 ; m++)

2007-10-12 13:38:33 · answer #2 · answered by Aoife 2 · 0 0

Note that there is no { after the second for loop. Which means the second loop prints JUST the #, and not the line break. The line break only gets printed after the loop is terminated.

2007-10-12 13:31:11 · answer #3 · answered by Mike Panda 2 · 0 0

Both loops don't print it - only the inner for loop does. You've always got to keep the bigger picture when working with loops. So, the outer loop (the "m-loop") only does two things each iteration - it starts the n-loop, and it then prints a newline. For each n-loop iteration, it prints a hash character. So, it goes like this:
m-loop0:
n-loop0:
print #
print #
print #
print #
print #
end n-loop0
print newline
end m-loop0
m-loop1:
n-loop1:
print #
print #
print #
print #
print #
end n-loop2
print newline
end m-loop2
m-loop2:
n-loop2:
print #
print #
print #
print #
print #
end n-loop2
print newline
end m-loop2
...
and so on.

Hope this helps!

2007-10-12 13:32:28 · answer #4 · answered by nogoodaddress 5 · 0 0

ami ...

it is a loop in loop

and..

Greeting to the U.Stat. of Am.

2007-10-12 13:31:22 · answer #5 · answered by Anonymous · 0 0

JAVA
not javascript !

2007-10-12 13:29:11 · answer #6 · answered by JavaScript_Junkie 6 · 0 0

fedest.com, questions and answers