Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

for-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     } } 
like image 832
Newbie404 Avatar asked Aug 12 '16 13:08

Newbie404


People also ask

Does for loop run only when the condition is true?

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.

Can you have to conditions in a for loop?

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.

What loop is used if you know when the condition will be met?

The while loop is used to repeat a section of code an unknown number of times until a specific condition is met.


Video Answer


1 Answers

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

if (Enumerable.Range(1, 20).All(b => i % b == 0))     DoAction(); 
like image 126
Kinetic Avatar answered Oct 13 '22 00:10

Kinetic