## 2. Filtering

### Print all even numbers in an array

To **filter** an array, we perform an action on elements that match a condition. This requires an if statement inside a loop:

public class MyProgram { public static void main(String[] args) { int[] b = {123,234,345,456}; for(int i = 0; i < b.length ; i++) { if(b[i] % 2 == 0) { //if b[i] is even System.out.println(b[i]); //print it } } //This program prints 234 and then 456 } }

### Print all prime numbers in an array

This is a more complicated algorithm. We need to check each number in an array and see if it is prime. A pseudo algorithm may look like:

//Given array x //Loop through each element 'e' in x: // Assume e is prime // Loop through each number 'j' between 2 and the square root of e. // If e divides any of 'j' evenly, then e is not prime // If e is prime, print it

Let's look at this in code:

public class MyProgram { public static void main(String[] args) { int[] x = {42,1303,1323,1171,1031,1131,2430,683}; for(int i = 0; i < x.length ; i++) { //we called x[i] e in the pseudo code boolean isPrime = true; for(int j = 2; j*j <= x[i] ; j++) { if(x[i] % j == 0) { isPrime = false; } } if(isPrime) { System.out.println(x[i]); //print it } } //This program prints 1303,1171,1031, and 683 } }

### Sum all prime numbers in an array

This is actually just a small addition to the previous algorithm. We need to add into an int sum declared before the outer loop:

public class MyProgram { public static void main(String[] args) { int[] x = {42,1303,1323,1171,1031,1131,2430,683}; int sum = 0; //the sum variable for(int i = 0; i < x.length ; i++) { boolean isPrime = true; for(int j = 2; j*j <= x[i] ; j++) { if(x[i] % j == 0) { isPrime = false; } } if(isPrime) { sum += x[i]; } } System.out.println(sum); //This program prints 4188 } }

Note that we can collapse the blocks. The previous program might be written as this, and it has the same behavior:

public class MyProgram { public static void main(String[] args) { int[] x = {42,1303,1323,1171,1031,1131,2430,683}; int sum = 0; for(int i = 0; i < x.length ; i++) { boolean isPrime = true; for(int j = 2; j*j <= x[i] ; j++) if(x[i] % j == 0) isPrime = false; if(isPrime) sum += x[i]; } System.out.println(sum); //This program prints 4188 } }