• Advertisement
Sign in to follow this  

Modulus use in c++

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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; // 21
int 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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
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


Ok, now i get. Thanks a bunch.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement