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

Do action only if condition is met in all iterations of 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 doesn't work as expected

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

Answer

Try this:

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