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 } }
A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.
It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.
The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.
You could also use a simple LINQ query like this one:
if (Enumerable.Range(1, 20).All(b => i % b == 0)) DoAction();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With