In: Computer Science
Below is your code:
public class NumberArray {
public static void main(String[] args) {
// problem 1 to calculate sum of 10 numbers in array
int array1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// printing array
System.out.println("Array 1 is: ");
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
System.out.println();
// printing sum of array
calculateSum(array1);
// problem 2 to square the numbers in two dimensional array
int array2[][] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 } };
System.out.println("\nArray before Squaring: ");
ShowNumbers(array2);
array2 = Square(array2);
System.out.println("Array After Squaring: ");
ShowNumbers(array2);
}
public static void calculateSum(int array[]) {
int sumOdd = 0;
int sumEven = 0;
for (int i = 0; i < array.length; i++) {
int num = array[i];
if (num % 2 == 0) {
sumEven = sumEven + num;
} else {
sumOdd = sumOdd + num;
}
}
System.out.println("Sum of Odd numbers: " + sumOdd);
System.out.println("Sum of Even numbers: " + sumEven);
}
public static int[][] Square(int array[][]) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = array[i][j] * array[i][j];
}
}
return array;
}
public static void ShowNumbers(int array[][]) {
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();
}
}
}
Output
Array 1 is:
1 2 3 4 5 6 7 8 9 10
Sum of Odd numbers: 25
Sum of Even numbers: 30
Array before Squaring:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
Array After Squaring:
1 4 9 16 25
36 49 64 81 100
121 144 169 196 225
256 289 324 361 400