32

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
    }
}
10
  • 11
    For loops don't return anything. Do you mean when all conditions inside a for loop are correct?
    – Steve
    Aug 12, 2016 at 13:12
  • 2
    To start, you could omit all non-prime numbers, because those are redundant anyhow.
    – Bernhard
    Aug 12, 2016 at 13:13
  • 2
    @Bernhard missing out composites with repeated factors changes the result, e.g. OP code requires 16 and 9 to be factors of i but neither are prime. You could just test for i%232792560 but that's not the question. Aug 12, 2016 at 22:52
  • 3
    Can anyone explain the number of upvotes?
    – oarfish
    Aug 14, 2016 at 16:05
  • 1
    @oarfish Some arbitrary algorithm selected this as a "Hot Network Question", so it gets highlighted in the sidebar across the entire Stack Exchange network, advertising it to readers everywhere on SO and from all other SE sites - who might not be very good judges of question quality on our site. To be clear, I'm not saying it's a bad question specifically, albeit vaguely phrased - but it's definitely not a +22 question either. Aug 15, 2016 at 10:55

9 Answers 9

94

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

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

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.

13
  • 4
    You could start looping from b = 2
    – Biscuits
    Aug 12, 2016 at 15:44
  • 5
    -1 this is the worst answer here, not sure why it was accepted. If you're adverse to LINQ, at the very least extract this to a method... Aug 12, 2016 at 23:29
  • 26
    @BlueRaja-DannyPflughoeft Where the asker has come up with an almost-solution, showing them how to make their solution work is far more valuable than just saying "scrap that and replace it with this one line of LINQ".
    – Rawling
    Aug 13, 2016 at 10:32
  • 2
    @BlueRaja-DannyPflughoeft When Googlers come here in the future, they probably aren't all using C#. I upvoted this and the LINQ answer, but context matters. Aug 14, 2016 at 16:28
  • 1
    @BlueRaja-DannyPflughoeft Sorry didn't see that. This absolutely should be extracted to a method. But I think showing how this could be accomplished in any language is the important part. Barry's answer is C# specific, which is fine, upvote it since the question is tagged C#. But Googling "all loop iterations pass do action" or something similar will inevitably lead users to this question, and they might not be using C# :) Aug 14, 2016 at 17:42
37

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.

11
  • 17
    Make sure to leave a comment where that number comes from when you use this. This is by far the best answer though.
    – Sumurai8
    Aug 13, 2016 at 7:33
  • 12
    @Barry I think he meant "leave a comment in the real source code", not leave a comment here on Stack Overflow. Aug 13, 2016 at 17:07
  • 11
    I believe this doesn't answer the question. This solves the problem posed by the example but the actual question is about the general situation where you have multiple conditions and want to act out on all of them. If I were to come in here thinking "great, have a bunch of checks to do, how can I simplify this", then your answer is going to be useless to me. Were the question "how to check if a number is divisible by lots of numbers", you'd be on point.
    – VLAZ
    Aug 14, 2016 at 11:53
  • 8
    Magic number... please no. Aug 14, 2016 at 16:27
  • 2
    @Barry sure, you've solved the problem of every single person who comes in here to know if a number is a divisible by 2-20. Not the whole demographic, mind, you but only those of them who specifically googled their problem by using "action in a loop" (or similar) as a search term. While those people would probably be grateful, I think they will be a minority of the total amount of people coming in for an advice.
    – VLAZ
    Aug 14, 2016 at 17:38
25

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
}
1
  • 3
    This is the most complete answer; it shows the OP how to do it the way the they intended but couldn't quite finish, but also introduces them and future readers to LINQ.
    – SQB
    Aug 15, 2016 at 9:06
11

Easy:

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

if(isDividable) do something
1
  • 1
    Jeez... You were only 38 seconds later than the accepted answer (now with tons more votes), but IMO yours is better than the first iteration of the top answer because flag isn't descriptive.
    – Izkata
    Aug 14, 2016 at 19:28
5
bool flag = true;
for(int b=1; b < 21 && (flag &= (i % b == 0)) ; b++)
    ;
if(flag)
   do_action();//do your task
2
  • 13
    @HimBromBeere If writing for the Obsfuscated C# Code Contest, then sure. Otherwise, typically code like this will just irritate anyone else who ever has to understand or maintain it. I'm not saying it's not technically clever or valid, but such tricks usually don't last long in sustainable codebases, for good reason... especially in a higher-level language like C# (i.e. I might understand ths more in C) where far better ways of expressing intent are available. Even if one added the missing comments, this would be less self-documenting than writing explicitly or calling a good library function. Aug 12, 2016 at 15:54
  • 1
    I agree the &= is maybe a bit unnecessary to have inside the for statement like that and could be moved to the body to avoid irritating some people who are allergic to convoluted logic. Still by far the best answer to this question. Literally 10s of times better than all the crazy iffers in fors. Aug 14, 2016 at 21:06
3

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.

1
  • 1
    By not breaking, this makes the program pointlessly carry out all subsquent iterations even after the condition it exists to ascertain is proven false. That is bad for both performance and semantics. Aug 14, 2016 at 12:12
3

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
}
5
  • 4
    This requires anyone reading the code to go WTF and mentally execute the code to figure out what it's trying to do. It's not at all clear that the loop does anything useful, what that is, and what if b > max (is that even syntactically valid without parentheses?) means for the given input. If answers using flags or, better, LINQ are so much more numerous - I think there's a reason. And sure, you could add comments explaining, but the best comment is no comment, rather to use code that doesn't require any. Aug 14, 2016 at 12:23
  • 2
    @underscore_d This answer demonstrates a looping technique, and it is a useful skill to have in one's toolbox. There is an entire site dedicated to discussions about code clarity and style, and although your attempt at elucidation may seem helpful, unfortunately you're just polluting so many comment chains here. I do appreciate the comment about missing parentheses though, I've been writing a lot of Swift code lately where they aren't necessary--I've edited my answer to add them in.
    – par
    Aug 14, 2016 at 15:22
  • I've only made comments on 4 posts here. Only 2 can be subjectively accused of "pollution", which is up for debate, but not today. The other 2 point out objective waste/sloppiness in the code, i.e. not using break once an answer is found, continuing to loop for no reason. What am I missing? Do you have concerns ranging outside this thread that you'd like to discuss? Anyway, you're welcome for the parentheses. Aug 14, 2016 at 15:40
  • Sigh. Tilt your windmills, friend.
    – par
    Aug 15, 2016 at 0:33
  • Also, you got it backwards: // do something executes if the condition is not met.
    – Rakete1111
    Aug 15, 2016 at 6:55
3
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.:)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.