In programming, modulus is useful to keep numbers in range not exceeding an upper bound limit.
For example:
int value = 0;
for (int x=0; x<100; x++)
cout << value++%8 << " "; //Keeps number in range 0-7
Output:
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7...
Now consider this situation:
int value = 5;
for (int x=0; x<100; x++)
cout << value-- << " ";
Output: 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7...
My question is: How to set the lower bound limit to 0 WITHOUT using any conditional statement like if or switch case?
Output I want: 5 4 3 2 1 0 0 0 0 0 0 0 ...
How about std::max
?
int value = 5;
for (int x=0; x<100; x++) {
cout << value << " ";
value = std::max(0, --value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With