Matthew
Matthew

Reputation: 2280

Cycle a decimal digit by 1 in c#

I'd like to cycle a decimal digit by 1 using a single operation of possible.

if x is 0 - 8 then x = x + 1
if x is 9 then x = 0

or the opposite

if x is 1 - 9 then x = x - 1
if x is 0 then x = 9

Is there a way to do this with C# in one line of code? If not C# are there any other languages that could?

What if I wanted to cycle it by more than one (2 or 3 or whatever)?

Upvotes: 0

Views: 125

Answers (3)

dav_i
dav_i

Reputation: 28137

I think what you're looking for is

var y = (x + 1) % 10;

This gives:

x    y
------
0    1
1    2
...
8    9
9    0

To decrement

var y = (i + 9) % 10;

Obviously to change the amount, just change 1 or 9 respectively

Upvotes: 7

esskar
esskar

Reputation: 10970

int Cycle(int x, int by = 1)
{
    return (x+by) % 10;
}

now you can call Cycle(9, 3) which should give you 2

Upvotes: 1

abelenky
abelenky

Reputation: 64720

int Cycle(int x)
{
    return x+1 % 10;
} 

int result = Cycle(0); // result is 1
int result = Cycle(8); // result is 9
int result = Cycle(9); // result is 0

Upvotes: 3

Related Questions