I have problem tu understand the iteration of the flow control.
Someone can help me to understand the iteration of this code?
Thank in advance!
rsiva sankar
Greenhorn
Joined: May 06, 2010
Posts: 1
posted
0
Actually the above code will not compile because the variable j is declared in the inner loop and you are trying to use it in the outer loop. The compiler will say j cannot be resolved
As the others have said, line 7 contains an error, because the variable j is out of scope at that point - that is, the variable j doesn't exist anymore, it only exists in lines 4-6. Suppose that we comment out line 7.
The for keywords creates a loop. In your example, you have a loop over variable i going from 0 until and including 9. Inside that loop, there is a nested loop over variable j. Note that the condition for the nested loop is j<0. That means the loop will never iterate, because j is never less than 0.
See Control Flow Statements in Sun's Java tutorials to learn about the for statement and other control flow keywords of Java.
int[][] a1 = {{1,2,3},{4,5,6},{7,8,9}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a1[j][i]);
}
}
Hi
Lorenzo
first the outer loop will run once for value of i and the inner will run thrice for value of j
the again the loop will increment the value of i to 1 and the inner will run thrice for value of j
this will continue until the value of i is reache to 3 and loop will exit.
output is 147258369
hope this helps.
Thanks & Regards
Sumit Kothalikar
Ulrich Vormbrock
Ranch Hand
Joined: Apr 15, 2010
Posts: 73
posted
0
Hi Lorenzo,
for this type of questions, I generally recommend to write down the whole iteration steps on a piece of paper, for example like this:
The array a1 can be read like this:
a1[0] = {1, 2, 3};
a1[1] = {4, 5, 6};
a1[2] = {7, 8, 9};
Let's take the case where i=1 and j=2:
a[j][i] -> a[2][1] = 8
Hope this helps!
I advise to do like this even in the real exam, because the only fact of writing down can prevent you from the awkward oversights.
The devil is in the details ;-)