Java Exercise
In this exercise, you will create a Java program that uses arrays and matrices to store and manipulate data. First, you will create a one-dimensional array that will hold a series of numbers, and then perform operations such as summing all the array elements. Next, you will create a two-dimensional array (an array of arrays) to store a table of values, and practice accessing and modifying the array elements. Finally, you will print the results to the console to demonstrate the use of arrays and matrices in your program.
Instructions:
- Create a **one-dimensional array** that stores at least 5 integers.
- Write a program that iterates through the **one-dimensional array** and calculates the sum of its elements.
- Create a **two-dimensional array** of size 3x3 and fill each cell with integers.
- Access and modify some of the elements of the **two-dimensional array**.
- Print the **one-dimensional array** and the **two-dimensional array** to the console to display the results.
This exercise will help you understand how to work with **one-dimensional arrays** and **two-dimensional arrays** in Java, essential skills for managing data in applications that require more complex data structures.
View Example Code
public class ArraysMatrices {
public static void main(String[] args) {
// One-dimensional array with 5 elements
int[] array = {1, 2, 3, 4, 5};
// Calculate the sum of the array elements
int sum = 0;
for (int num : array) {
sum += num;
}
System.out.println("Sum of the array: " + sum);
// Two-dimensional 3x3 matrix
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Modify a value in the matrix
matrix[1][1] = 10; // Change the value in the second row, second column
// Print the matrix
System.out.println("Two-dimensional matrix:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Line break after each row
}
}
}
Output:
Sum of the array: 15
Two-dimensional matrix:
1 2 3
4 10 6
7 8 9
This program demonstrates how to work with **one-dimensional arrays** and **two-dimensional arrays** in Java. First, a **one-dimensional array** is defined to store multiple integer values, and the program iterates through the array to calculate the **sum** of its elements. Then, a 3x3 **two-dimensional array** (an array of arrays) is created, where each element is an integer. The program also shows how to **modify** a specific value within the array. Finally, it prints the **array sum** and the contents of the **two-dimensional array** to show how to access and manipulate this data effectively.