-3

I hope someone can help. My problem is with using the modulus operator in a for loop. My code is as follows:

for (int i = 0; i < 10; i++)

if (i % 2 == 0) {
method1();
}
else {
method2();
}

I understand how this loop works in that it iterates between if and else because of the even and odd numbers created by the condition that uses the modulus operator (i % 2 == 0)

However, I want to create a condition using the modulus operator so that my loop iterates through 4 methods - as in:

loop starts{

method1();
method2();
method3();
method4();

loop repeats
}

I can't work out how to accomplish this. I would appreciate any help and advice.

Thanks in advance.

Mark Fenwick
  • 147
  • 1
  • 2
  • 10
  • Use plain language first, then try to put it in code. – Ulrich Eckhardt Jan 12 '18 at 20:07
  • *create a condition* you need to tell what condition ? – Ravi Jan 12 '18 at 20:07
  • Is there a reason you don't just put the 4 methods one after each other in the for loop and run 1/4 as many iterations of it? Or can you stop after any one of them? – Bernhard Barker Jan 12 '18 at 20:07
  • 2
    Every **2nd** number is `% 2 == 0`. So what you do think every **4th** number would be? Do you know what the `%` operator does? – Bernhard Barker Jan 12 '18 at 20:09
  • 1
    you need to use mod 4 instead of mod 2. Modding by 4 essentially maps all real numbers to either 0,1,2,3 – victor Jan 12 '18 at 20:14
  • 1
    Yeah. I think you need something like `switch (i % 4) { case 0: method1(); break; case 1: method2(); break; case 2: method3(); break; case 3: method4(); break; }`. But it's not clear what exactly it is that you find difficult. – MC Emperor Jan 12 '18 at 20:14
  • Thanks for your help guys, I got the light bulb moment I was after. – Mark Fenwick Jan 12 '18 at 20:46

3 Answers3

3

Put j = i % 4 And check for method1() j should be equal to j = 0, similarly for Method2() check j = 1. And so on. Put for range conditions to 1 for infinite loop or desired range.

Jitendar
  • 497
  • 2
  • 5
  • 11
2

You could be looking to use the switch statement. More on that here. Basically it takes a variable to switch between cases. For example:

for(int i = 0; i < 10; i++){

  switch(i%2) {

    case 0: method0();
            break;
    case 1: method1();
            break;

  }

}

Here is the out put if method0 printed 0, and method1 printed 1: 1 0 1 0 1 0 1 0 1 0

You can edit the modulus to whatever number you want, you just have to account for the different possibilities.

0

Do you mean something like this?

for(int i = 0; i < 10; i++)
{
     if(i%4 == 0)
     {
         condition
     }
     else if(i%4 == 1)
     {
         condition
     }
     else if(i%4 == 2)
     {
         condition
     }
     else if(i%4 == 3)
     {
         condition
     }
}

Remember to put it on paper if you're confused and loop through your head (as a beginner)

Andreas
  • 154,647
  • 11
  • 152
  • 247
Sean
  • 168
  • 7