Wednesday, July 7, 2010

Java: Enhanced for loop and Array puzzle.

I have done a lot of programming related puzzles as a student and professional for fun or for taking tests. But this seemingly innocent and straightforward looking piece of code stumped me !  I had to actually try this out in Eclipse running in debug mode to Watch the variables. Now when i figured what is happening it looks straightforward.

The reason why i could not figure this out is first of all  :
1) It looked straightforward ( overconfidence stepped in )
2) I was used to the for(int counter = 0; counter< ...; counter++)  way of writing for loops and indexing arrays.

Whatever said, this one was a good puzzle. And i will NOT forget this one all my life :) ! 

public class Main {
   
    public static void main(String... pArgv) {
        int []arr = {1,2,3,4};
        for ( int i : arr )
        {
           arr[i] = 0;
        }
        for ( int i : arr )
        {
           System.out.print(i);
        }
    }
}


By the way the output is : 0030

No comments:

Post a Comment

Followers

About Me

I'm a software developer with interests in Design Patterns, Distributed programming, Big Data, Machine Learning and anything which excites me. I like to prototype new ideas and always on the lookout for tools which help me get the job done faster. Currently, i'm loving node.js + Mongodb.