|
Even and Odd numbers between two numbers
Print even and odd numbers between two numbers.
|
package com.bethecoder.tutorials.coding.examples;
import java.util.ArrayList;
import java.util.List;
/**
* Print even and odd numbers between two numbers.
*/
public class EvenOddNumTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(getEvenNums(2, 20));
System.out.println(getEvenNums(201, 225));
System.out.println(getOddNums(2, 20));
System.out.println(getOddNums(201, 225));
}
private static List<Integer> getEvenNums(int min, int max) {
return getNums(min, max, true);
}
private static List<Integer> getOddNums(int min, int max) {
return getNums(min, max, false);
}
private static List<Integer> getNums(int min, int max, boolean even) {
List<Integer> nums = new ArrayList<Integer>();
for (int i = min; i < max ; i ++) {
if (even && i % 2 == 0) {
nums.add(i);
} else if (!even && i % 2 == 1) {
nums.add(i);
}
}
return nums;
}
}
|
| |
It gives the following output,
[2, 4, 6, 8, 10, 12, 14, 16, 18]
[202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224]
[3, 5, 7, 9, 11, 13, 15, 17, 19]
[201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223]
|
|