Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run if statement in loop only once

Tags:

loops

Just curious if its possible. Consider follwing code:

boolean firstRow = true;

while{row = result.next())
{
    if(firstRow)
    {
        firstRow = false;
        //do some setup 
    }

    //do stuff
}

Its pseudo-code and question is general not about some specific programming language.

My question: is it possible to write code that behaves exactly same but without using additional variable (in this case "firstRow"). In FOR loop its possible to check counter variable value but lets leave FOR loops out of this question.

like image 783
Keios Avatar asked Jan 21 '11 13:01

Keios


1 Answers

Yes, do your setup before you start the loop and change it to a do..while. For example:

if (row = result.next()) {
  //do some setup 
  do {
    //do stuff
  } while (row = result.next());   
}
like image 151
kvista Avatar answered Oct 16 '22 08:10

kvista