The modulus operator, %, returns the remainder of a division operation.
public class Main {
public static void main(String args[]) {
int x = 42;
System.out.println("x mod 10 = " + x % 10);
}
}
When you run this program you will get the following output:
x mod 10 = 2
The modulus operator can be applied to floating-point types as well as integer types.
public class Main {
public static void main(String args[]) {
double y = 42.25;
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program you will get the following output:
y mod 10 = 2.25
The following code uses the modulus operator to calculate the prime numbers:
public class Main {
public static void main(String[] args) {
int limit = 100;
System.out.println("Prime numbers between 1 and " + limit);
for (int i = 1; i < 100; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.print(i + " ");
}
}
}
The output:
Prime numbers between 1 and 100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |