Pros and Cons about Coding

My friend told me a recent coding issue he had been asked during interviews., which i find it interesting so sharing it here.

Scenario 1:

for (i=0, i <N, i ++)

{

   if (condition 1)

    {   dostuff1       }

  else

    {  dostuff2   }

  }

 

Scenario 2:

if (condition 1)

  {    for (i=0, i <N, i ++)

         {   dostuff1();

           }

}

else

{

      for (i=0, i <N, i ++)

         {  

           dostuff2();

        }

}

 

What are the pros and cons of using either one of these approaches? Please feel free to leave comments...It keep me thinking for a while but i got the answers....hehe...

Published Wednesday, August 30, 2006 3:57 PM by darenhan

Comments

# re: Pros and Cons about Coding

Thursday, August 31, 2006 10:28 PM by icelava

Unless Condition 1 is something undiscoverable outside of the loop logic, go with Scenario 2 (or code pattern 2).

When the condition is known before hand, implement the check before running the loop, so the check only happens _once_, rather on each and every iteration of the loop.

# re: Pros and Cons about Coding

Saturday, September 02, 2006 1:52 AM by savagerx

Lol, just for fun.

scenario 1 favours flexibility while scenario 2 favours algorithmic efficiency.

A possible compromise can be achieved with two loops(comprising of method 1 loops and method 2 loops) running on recursions. Thus, we can easily switch over to the other method when condition changes.

# re: Pros and Cons about Coding

Sunday, September 03, 2006 1:56 PM by darenhan

hmm i was thinking of the lines of memory usage and processing...

scenario 2 takes up more memory to process and time also compared to scenario 1 becasue its doing the fo loop twice.

and scenario 2 is more suitable for mission critical applications cos it implements the lst condition lst if that condition is very important then the 2nd condition, whereas scenario 1 is going thro one by one....

:)

# re: Pros and Cons about Coding

Monday, September 04, 2006 6:07 PM by SmallSize

scenario 2 is better. Even though For loop have been quoted twice. Finally only one For loop will execute. Comparison is a expensive task. It is better not to put comparison in a loop.

Powered by Community Server (Commercial Edition), by Telligent Systems