Create a java program that generates elements (randomly from 10 – 75) of a 2-dimensional array
(5x5) using the Random Class then perform the following:
1) Output the array elements
2) Output the sum of prime numbers in the array
3) Output the elements in the main diagonal.
4) Output the sum of the elements below the diagonal.
5) Output the sum of the elements above the diagonal.
6) Output the odd numbers below the diagonal.
7) Output the even numbers above the diagonal.
import java.util.Random;
public class Main {
public static void main(String[] args) {
boolean[] primes = new boolean[76];
for (int i = 2; i < primes.length; i++) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = true;
}
}
Random random = new Random();
int[][] array = new int[5][5];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(66) + 10;
}
}
System.out.println("\n1) Output the array elements");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("\n2) Output the sum of prime numbers in the array");
int primesSum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (!primes[array[i][j]]) {
primesSum += array[i][j];
}
}
}
System.out.println(primesSum);
System.out.println("\n3) Output the elements in the main diagonal.");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i][i]);
}
System.out.println("\n4) Output the sum of the elements below the diagonal.");
int sumBelow = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
sumBelow += array[i][j];
}
}
System.out.println(sumBelow);
System.out.println("\n5) Output the sum of the elements above the diagonal.");
int sumAbove = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array[i].length; j++) {
sumAbove += array[i][j];
}
}
System.out.println(sumAbove);
System.out.println("\n6) Output the odd numbers below the diagonal.");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[i][j] % 2 != 0) {
System.out.println(array[i][j]);
}
}
}
System.out.println("\n7) Output the even numbers above the diagonal.");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array[i].length; j++) {
if (array[i][j] % 2 == 0) {
System.out.println(array[i][j]);
}
}
}
}
}
Comments
Leave a comment