Tom Pitts
Tom Pitts

Reputation: 600

Shortening a for loop with if statements - C#

This is my current code:

for(int i = 1; i < 13; i + 4)
{
   do something
}
for (int i = 2; i <13; i + 4)
{
   do something
}

And so on for each value of i.

I would like my for loop to do the following without having to write out each individual value:

for(int i = 1; i < 13; i++)
{
    if(i is 1,5,9)
    {
       do something
    }
    if(i is 2,6,10)
    {
       do something
    }

The do something is for example, change text box text.

Thank you.

Upvotes: 2

Views: 199

Answers (5)

Jon Hanna
Jon Hanna

Reputation: 113272

Look at what the criteria have in common; they all modulo by 4 to the same thing:

for(int i = 1; i != 13; ++i)
{
  switch(i % 4)
  {
    case 1:
      // first do something
      break;
    case 2:
      // second do something
      break;
    case 3:
      // third do something
      break;
    case 0:
      // fourth do something
      break;
  }
}

An alternative approach is to increment within the loop:

for(int i = 1; i != 13; ++i)
{
    // first do something
    ++i;
    // second do something
    ++i;
    // third do something
    ++i;
    // fourth do something
}

This approach needs more caution if you aren't guaranteed a whole number of loops (e.g. you're fine here, but if you were ending at i < 12 you'd need to test within the loop).

Upvotes: 3

Philippe Par&#233;
Philippe Par&#233;

Reputation: 4418

I would do something like this:

int[] valuesForTheFirstIf = new int[] { 1, 5, 9 };
int[] valuesForTheSecondtIf = new int[] { 2, 6, 10 };

for (int i = 0; i < 13; i++)
{
    if (valuesForTheFirstIf.Contains(i))
    {
        // do something
    }
    if (valuesForTheSecondtIf.Contains(i))
    {
        // do something
    }
}

Upvotes: 0

Ron Beyer
Ron Beyer

Reputation: 11273

Here is an easy way without making it longer...

for(int i = 1; i != 13; ++i)
{
    if ((i - 1) % 4 == 0)
    {
         //i is 1, 5, 9, etc.
    }
    else if ((i - 2) % 4 == 0)
    {
         //i is 2, 6, 10
    }
}

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use Contains:

for(int i = 1; i < 13; i++)
{
    if(new[]{1,5,9}.Contains(i))
    {
       // do something
    }
    if(new[]{2,6,10}.Contains(i))
    {
       // do something else
    }
}

Upvotes: 2

Codor
Codor

Reputation: 17605

Perhaps you are looking for the division remainder operator % in combination with the switch statement as follows.

for(int i = 1; i < 13; i++)
{
    switch( i % 4 )
    {
        case 0:
            do stuff;
            break;
        case 1:
            do stuff;
            break;
        case 2:
            do stuff;
            break;
        case 3:
            do stuff;
            break;
    }
}

Upvotes: 2

Related Questions