Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Nested Loop Initialization

I am new at java, so there is some piece of code in nested loop I don't understand...

for(int i=0; i<3; i++){
 for(int j=1; j<3; j++){
   System.out.println(i + "" + j);
 }
}

it will run: 01,02,11,12,21,22

but when I changed into this:

int j=1;
for(int i=0; i<3; i++){
 for(; j<3; j++){
   System.out.println(i + "" + j);
 }
}

it become like this: 01,02

can anyone explain it to me?

like image 465
duniaBerat23 Avatar asked Aug 22 '13 05:08

duniaBerat23


2 Answers

The difference between the loops is that j is being reset each time in the top example but in the second example it is keeping its value.

In the top example, each time the inner for loop starts j is being reinitalized to 1 so it will go through the 1,2,3 values. When j gets to 3 it will exit the loop which is why you see the j value as 1 then 2. This is run each time the outer loop runs giving you the 0, 1 and 2 for your i values.

In the bottom example j is never reset so it will only increase. The first time through the loop it goes through the 1, 2, 3 values and exits the loop giving you the 01, 02 values you have seen. Since it does not get reset it stays as 3 so as i increases the inner loop will always exit without printing, giving you the output you are seeing.

To get the same output for the bottom example you need to reset the value to 1, which is basically what the first element of the for loop is doing.

int j = 1;
for(int i = 0; i < 3; i++) {
    j = 1; //reset the value each time through the outer loop
    for(; j < 3; j++) {
        System.out.println(i + "" + j);
    }
}
like image 168
n00begon Avatar answered Oct 04 '22 11:10

n00begon


In your first code

At case i=0

The inner loop starts with condition j=1

j=1 initialized **Condition satisfies** continue
j=2 incremented **Condition satisfies** continue
j=3 incremented **Condition Failed**    loop ends

The inner first executes it complete cycle and tend to increment of i Now i=1

Again

j=1 initialized **Condition satisfies** continue
j=2 incremented **Condition satisfies** continue
j=3 incremented **Condition Failed**    loop ends

But in your second code, j is declared outside and once j is set to 3, it remains same. So condition failed for second loop.

At case i=0

j=1 declared    **Condition satisfies** continue
j=2 incremented **Condition satisfies** continue
j=3 incremented **Condition Failed**    loop ends

At case i=1

j=3 Already set**Condition Failed**    loop ends

loop fails

like image 35
Pandiyan Cool Avatar answered Oct 04 '22 10:10

Pandiyan Cool