• 9
• 11
• 9
• 20
• 12

# Modulus use in c++

This topic is 3400 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm kind of confused on the modulus (%) and what it does and how to use it. I would like to see some examples too. Thanks --Garren

##### Share on other sites
Confusing? It gives you the remainder of a division operation. It's not used frequently. Occasionally for mathematical algorithms, occasionally to do something every... x iterations:

for( int i = 0; i < 100; ++i){    std::cout << i;    if( i%5 == 0 ){        std::cout << std::endl;    }}// 0// 12345// 678910// 1112131415// etc.

Sometimes to split a number:

int moneyInCents = 4321;int cents = moneyInCents % 100;                              // 21int dollars = (moneyInCents - (moneyInCents % 100))/100;     // 43

Most often its used with ==0 to see if something is exactly divisible, as in the iteration example.

##### Share on other sites
Think of it as "remainder." m % n returns the remainder of dividing m by n. e.g., 16 % 3 → 1, 19 % 4 → 3, 2 % 3 → 2

##### Share on other sites
its simple. modulo is used when you want to get the REMAINDER of a statement for example 6 % 2 would equal 0 there is no remainder. 5 % 2 would equal 1 as 2 goes into five twice with a remainder of one. so modulus simply returns the remainder pretty easy. pretty straight forward

##### Share on other sites
Let's say you want a random number between 0 and 100, the random number X is 2143242. X % 100 = 42.

##### Share on other sites
Quote:
 Original post by OluseyiThink of it as "remainder." m % n returns the remainder of dividing m by n. e.g., 16 % 3 → 1, 19 % 4 → 3, 2 % 3 → 2

Ok, now i get. Thanks a bunch.