Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program concept

Tags:

c

I'm sorry if this question seems very noobish.

I'm having trouble figuring out the best way to approach this problem.

Here's the basic idea in code:

  int iterator = 0;

  if ((iterator % 2) == 1){
    // do first option
    iterator++;
    return;
  } else if ((iterator % 2) == 0){
    // do second thing
    iterator++;
    return;
  } else if ((iterator % 3) == 0){
    // do third option
    iterator++;
    return;
  } else{
    // error
    return;
  }

Essentially the function will be called once a second (it's a watchapp for Pebble).

I can get the first two options to work but i'm having trouble with the third. I assume it's because of the % 3 being too vague.

How would you guys approach this?

like image 599
lkemitchll Avatar asked Jan 18 '26 05:01

lkemitchll


2 Answers

Is this what you're after?

if ((iterator % 3) == 0){
    // do first option
} else if ((iterator % 3) == 1){
    // do second thing
} else if ((iterator % 3) == 2){
    // do third option
} 
iterator++;

This can be re-written as:

switch (iterator++ % 3) {
case 0:
     // first option
     break;
case 1: 
     // second option
     break;
case 2: 
     // third option
}
like image 159
azz Avatar answered Jan 20 '26 17:01

azz


You never get to the third option, because iterator % 2 can be either 0 or 1.

like image 41
Ashalynd Avatar answered Jan 20 '26 19:01

Ashalynd