Sunday, July 26, 2009

How can i link an "else" with an "if" in a for loop block wihtout including the else in the loop

i'm using visual c++ express edition

How can i link an "else" with an "if" in a for loop block wihtout including the else in the loop
If you want to have the "else" run only once, you can do this.





bool doElse = true;


for(int i = 0; i %26lt; 10; i ++)


{


//this is just a sample loop


if(i == 5)


doElse = false;


}


if(doElse


{


//here is the else statement


//do something


}
Reply:Ok, if you want "else" to execute only once, then do this:





bool elseRan = false;


for (int i = 0; i %26lt; 10; i++)


if (i %26lt; 6) {


*code for 'if'*


} else {


if (!elseRan) {


elseRan = true;


*code for else*


}


}





Basically, we have boolean elseRan which tells us if the 'else' block ran. It is initially set to false, because 'else' didn't execute yet. In that block, we first check if elseRan is true, if it is, then 'else' have ran before, so we don't do anything. But if elseRan is false, then this is our first time running the code. So we first set elseRan to true, and proceed with our code. Hope this helps.





If you don't want else to execute at all, then just delete it.

anemone

No comments:

Post a Comment