开发者

Using modulus in for loop

开发者 https://www.devze.com 2023-04-06 19:22 出处:网络
I am trying to understand how to repeat loops using the mod operator. If you have two strings, \"abc\" and \"defgh\", how can % be开发者_如何学Python used to loop through abc, repeating it until the

I am trying to understand how to repeat loops using the mod operator.

If you have two strings, "abc" and "defgh", how can % be开发者_如何学Python used to loop through abc, repeating it until the end of defgh is reached? Namely, what is the mod relationship of the length of abc and defgh?

I don't really understand this concept.


Simple.

std::string abc("abc");
std::string defgh("defgh");

for (size_t i = 0; i < defgh.length(); ++i)
{
    printf("%c", abc[i % abc.length()]);
}

Think about what the Modulus operator is doing, it discretely divides the left hand side by the right hand side, and spits back the integer remainder.

Example:

0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1

In our case, the left hand side represents the i'th position in "defgh", the right hand represents the length of "abc", and the result the looping index inside "abc".


The typical usage of mod is for generating values inside a fixed range. In this case, you want values that are between 0 and strlen("abc")-1 so that you don't access a position outside "abc".

The general concept you need to keep in mind is that x % N will always return a value between 0 and N-1. In this particular case, we also take advantage of the fact that if you increase x by 1 x % N also increases by 1. See it?

Another important property of modulus that we use here is the fact that it "rolls over". As you increase x by 1, x % N increases by 1. When it hits N-1, the next value will be 0, and so on.

Look at @Daniel's code. It's C++ but the concept is language-agnostic

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号