Gelgavish
Gelgavish

Reputation: 21

How to make a variable cycle through range?

This is a simple one (I guess)

I just wondered if there is any way to make a variable (Let's say int ) cycle through a range? Right now this is what I would do:

int someInt = 0, max = 10; 
while(1) // This loop is here just for increasing someInt
{
  someInt++;
  if (someInt >= max)
    someInt = 0;
}

Isn't there any other trick to reset someInt? maybe without using if?

Thanks!

Upvotes: 0

Views: 316

Answers (3)

Aqeel Ahmad
Aqeel Ahmad

Reputation: 757

you can simply use mod operator.

int someInt = 0, max = 10; 
for(int i = 0 ; i < 100 ; i++) // This loop is here just for increasing someInt
{
  ++someInt;
  someInt = someInt % max;
  cout<<someInt;
}

Upvotes: 0

Doeus
Doeus

Reputation: 420

Just use the remainder operator (%).

The binary operator % yields the remainder of the integer division of the first operand by the second (after usual arithmetic conversions; note that the operand types must be integral types).

int someInt = 0, max = 10; 
while(1) // This loop is here just for increasing someInt
{
  someInt = (someInt + 1) % max;
}

Upvotes: 2

Galik
Galik

Reputation: 48615

Here I would simply use a for loop inside the while loop:

int max = 10;

while(true) for(int someInt = 0; someInt < max; ++someInt)
{
    // do stuff here
}

Upvotes: 1

Related Questions