David A. David A. - 3 months ago 12
C# Question

Do an action only if a condition is met in all iterations of a loop

Is there a way to only trigger an action when a condition is met in all iterations of a

for
loop?

Example:

if ((i % 1 == 0) && (i % 2 == 0) && (...) && (i % 20 == 0))
{
Do action x
}


This is what I tried, but it didn't work as expected:

for (int b=1; b<21; b++)
{
if (i % b == 0)
{
// Do something
}
}

Answer

There is classic solution:

var flag = true;
for(int b = 2; b < 21; b++)
{
     if (i % b != 0)
     {
         flag = false;
         break;
     }
}
if(flag)
   SomeAction():

At first we assume, that all conditions(loops) are met: var flag = true. If at least one condition is not met: if (i % b != 0), we stop looping process: break; because there is no need to continue checking, and set flag = false, now via flag variable we know the result of our checking and can use it later to determine should we call SomeAction() or not.