Newbie404
Newbie404

Reputation: 523

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
    }
}

Upvotes: 32

Views: 8263

Answers (9)

Dan
Dan

Reputation: 89

bool action = true;
for(int b=1;b<21;b++)
{
     if (i % b != 0)
           {
               action = false;
               break;
           } 
}

After this:

if (action)
{
// do your action 
}

Hope it helped.:)

Upvotes: 3

Good Night Nerd Pride
Good Night Nerd Pride

Reputation: 8452

So you want to chain a number of very similar boolean expressions without writing them all explicitly.

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

The first thing you could do is to extract the combined expression used in the if statement into a new function. This makes your code more readable.

public static void Main()
{
    // ...

    if (DivisibleByAllUpTo20(i))
    {
        //do action x
    }

    // ...
}

private static bool DivisibleByAllUpTo20(int i)
{
    return (i % 1 == 0) && (i % 2 == 0) && (...) && (i % 20 == 0);
}

DivisibleByAllUpTo20() can then be implemented with a for loop like you tried.

private static bool DivisibleByAllUpTo20(int i)
{
    for (int b = 1; b < 21; b++)
    {
        if (i % b != 0)
            return false;
    }

    return true;
}

By the way: the LINQ namespace provides lots of helper methods that lets you write such code much more concisely and cleaner:

using System.Linq;

// ...

if (Enumerable.Range(1, 20).All(n => n % i == 0))
{
    // do action x
}

Upvotes: 25

par
par

Reputation: 17724

There are quite a few similar answers here that use a flag. A simpler solution is to use the loop variable (b in your question) as the condition to test:

int b;
int max = 20;

for (b = 1; b <= max && i % b == 0; ++b) ;

if (b > max) {
    // do something
}

Upvotes: 3

Kinetic
Kinetic

Reputation: 2650

You could also use a simple LINQ query like this one:

if (Enumerable.Range(1, 20).All(b => i % b == 0))
    DoAction();

Upvotes: 94

Slava Utesinov
Slava Utesinov

Reputation: 13488

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.

Upvotes: 86

Barry
Barry

Reputation: 303057

How about just:

if (i % 232792560 == 0) {
    // do action
}

If you want to check that your number is divisible by lots of numbers, that's equivalent to checking if your number is divisible by the least common multiple of all of those numbers. In this case, that's 24*32*5*7*11*13*17*19.

Upvotes: 37

Alexander Kiselev
Alexander Kiselev

Reputation: 446

bool flag = true;
for(int b=1; b < 21 && (flag &= (i % b == 0)) ; b++)
    ;
if(flag)
   do_action();//do your task

Upvotes: 5

Alexander Holzinger
Alexander Holzinger

Reputation: 70

You could write it like this

bool doAction = true;
for(int b=1;b<21;b++)
{
  if (!(i % b == 0))
    {
      doAction = false;
    } 
}
if (doAction)
{
  do action x;
}

That sets the bool to false when one condition is false, so it only executes do action x; when all conditions are true.

You could also do it in less lines with Linq:

var divisors = Enumerable.Range(1, 20);
if(divisors.All(div => i % div == 0))
{
  //do someting
}

Explanation: Enumerable.Range returns an Array with values 1 to 20 and the .All checks the Lambda expression for each object.

Upvotes: 3

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Easy:

bool isDividable = true;
for(int b=1; b<21; b++)
{
     if (i % b != 0)
     {
         isDividable = false;
         break;
     }
}

if(isDividable) do something

Upvotes: 11

Related Questions