Using modulus in for loop
Solution 1
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".
Solution 2
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
dmubu
Updated on July 18, 2022Comments
-
dmubu almost 2 years
I am trying to understand how to repeat loops using the mod operator.
If you have two strings,
"abc"
and"defgh"
, how can%
be used to loop throughabc
, repeating it until the end ofdefgh
is reached? Namely, what is the mod relationship of the length ofabc
anddefgh
?I don't really understand this concept.