954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

modulus operator %

Hmm I was lookin through a recursion program in this book i have here and the only thing I'm having trouble with is the modulus operator.

I know that it returns the remainder of 2 numbers.

But, suppose I have this: x % y

If x > y then the result is x. Am I tripping out o_O?

degamer106
Junior Poster
131 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 
If x > y then the result is x. Am I tripping out o_O?



if x is 6 and y is 2, then the result is 0.

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 

i'm sorry i meant if x < y.

degamer106
Junior Poster
131 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 
i'm sorry i meant if x < y.


Yes, then result will be x.

SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

Yes I have also noticed this its is true that if x

Waqaskhan411
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

I think you've misunderstood how modulus works, or maybe I've misunderstood you :P

Basically in your x % y example, you are taking y away from x until x is less than y, then returning x.

Example in C that I wrote a while ago:

int mod(int a, int b)
{
	for(; a > b; a -= b);
	
	return a;
}


So if x = 1, y = 8

if 1 > 8 we take away 8, but it isn't so...
answer is 1

Auraomega
Junior Poster in Training
57 posts since Jul 2010
Reputation Points: 12
Solved Threads: 7
 

Then tell me what would be 3*3*3%4?

Daita
Newbie Poster
14 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

Answer is 3 ..

First 3*3*3 gives 27
thn modulus operator gives remainder of 27%4
Hence ans is 3..

I got your doubt

U thinking

3*3*3%4
= 3*3*(3%4)
= 3*3*3
= 27

but its wrong ..

U need to refer operator precedence in C

* / % Multiplication/division/modulus left-to-right
so first multiplication is done and thn division if any and thn modulus operator comes..
Hence the result 3..

Shankye
Junior Poster
168 posts since Nov 2010
Reputation Points: 48
Solved Threads: 16
 

ya i agree with Shankye
As u already know that modulus operator gives the remainder of the division of two operands ...!!...n in case two operands are such that
x

ankitcuul
Newbie Poster
2 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0
 

Check this
precedence of all operators ..

http://www.difranco.net/cop2220/op-prec.htm

Shankye
Junior Poster
168 posts since Nov 2010
Reputation Points: 48
Solved Threads: 16
 

Problem solved may be ..
Mark it solved

Shankye
Junior Poster
168 posts since Nov 2010
Reputation Points: 48
Solved Threads: 16
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You