Cyrus Gomes
Cyrus Gomes

Reputation: 9

Wrapping a value in C

I really wanted to know how do you wrap a value or a letter in C. Say if I were to increment 'z', how can I make it turn to 'a' and vice versa? The same goes with integers. If I have 9, how can I make it turn to 0 upon incrementation?

Upvotes: 0

Views: 359

Answers (1)

kaylum
kaylum

Reputation: 14046

The operator you are looking for is modulo %.

Wrapping integers is straight forward:

int my_int = /* some value */
int wrapped_my_int = my_int % 10;

To wrap ascii characters is a little more complicated because the start value is not 0. Just need to rebase to 0 first and then back to 'a' based:

char my_char = /* some value */
char wrapped_my_char = (my_char - 'a') % ('z' - 'a' + 1) + 'a';

Upvotes: 1

Related Questions