Public Group

# Modulus use in c++

This topic is 3582 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.

1. 1
Rutin
26
2. 2
3. 3
4. 4
5. 5

• 10
• 13
• 19
• 14
• 9
• ### Forum Statistics

• Total Topics
632941
• Total Posts
3009337
• ### Who's Online (See full list)

There are no registered users currently online

×