Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical operation to keep number not less than zero

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 ...

like image 535
user3437460 Avatar asked Apr 03 '14 14:04

user3437460


1 Answers

How about std::max?

int value = 5;
for (int x=0; x<100; x++) {
    cout << value << " ";
    value = std::max(0, --value);
}
like image 169
bstamour Avatar answered Sep 20 '22 20:09

bstamour