Wednesday, March 18, 2009

Puzzle 8 – Misleading Count.

Language – Java | Type – Concept | Last date 22-Mar-2009 12:00 p.m. IST | Points 2

This is why ‘i’ am so important …

package com.twisters;
public class MyLoop {
public static void main(String[] args) {
for(int i=0;i<10;i++){
for(i=0;i<5;i++){
System.out.println("Testing");
}
}
}
}
Got an answer? Why don’t you leave it here.

2 comments:

  1. The loop will print out Testing infinately. This happens because every time the outer for loop enters the inner for loop the iterator "i" is reset to 0, and when the inner loop exits it will be 5. The outer i++ then takes effect, making i=6. Since 6<10, the outer for loop executes again, starting the inner for loop. That for loop sets i=0, and the whole process starts over again.

    ReplyDelete
  2. Hi all,

    Concept-
    Here the outer loop initialize the value of "i" with 0 only once, while inner for loop will initialize it every time.

    Output-
    Infinite loop.

    Reason-
    1st iteration- -->
    outer--> i=0
    inner--> it will iterate till i<5 i.e. at i=4,
    exit at i=5,
    2nd iteration-->
    outer--> due to i++ , i=6.
    inner--> nowinner loop will again initializes i with 0 above process occurs again and so on.]


    Thanks,
    Tanzy.

    ReplyDelete

Solution for this question?