• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Modulus Operator

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sir i want to know about the modulus operater and please tell me how to operator

class Modulus {

public static void main(String [] args){
int a=3;
int b=5;
System.out.println("The ans of b%a "+b%a);//in this ans come 2
System.out.println("The ans of b/a "+ b/a);

System.out.println("The ans of a%b "+a%b);//in this ans come 3 why?
System.out.println("The ans of a/b "+a/b);
}}
 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The modulus is basically the remainder of dividing two numbers.
To find 5%3 just think of 5/3 which is 1 with a remainder of 2
10%2 is 0 because the two numbers divide evenly with no remainder.
For 3%5 the answer is 3 because 3/5 is 0 with a remainder of 3. I have heard the modulus operator referred to as the remainder operator.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!
Sometimes you will bump into this sort of code.
-5%2
-5%-2
As I've been thought from KHE remeber that if any of the int values �r negative then the product of the modulos results a negative result. If both are negative then it results in a negative result. Therefor, don't pay to much attention to the negative number.
5%2
5-2 = 3
3-2 = 1
1 - 2 1 < 2 so the result is 1
5%2= 1
add a - infront of 1
result = -1.
This is just how you could think. In normal mathematics using -5%-2you must actually add. Like this
-5%2- To reduce the value add
-5+2 = -3
-3+2 = -1
so -5%2= -1
In nagative number mod negative number the actuall calculation goes something like this.
-5%-2- to reduce the value
-5-(-2) = -3
-3-(-2) = -1
result -1
// Hope I didn't mess things up for you
 
reply
    Bookmark Topic Watch Topic
  • New Topic