0% found this document useful (0 votes)
19 views6 pages

Java Array and 2D Array Exercises

dyguydgdy ydgiudid tdiudiugd iddggd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views6 pages

Java Array and 2D Array Exercises

dyguydgdy ydgiudid tdiudiugd iddggd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Array and 2D Array Questions

Array Questions
1. Declare an array of 10 integers in Java.

2. Initialize an array with the first 5 prime numbers.

3. Find the sum of all elements in an array.

4. Find the maximum element in an array.

5. Reverse the elements of an array.

6. Check if an array contains a specific value.

7. Count the number of even and odd numbers in an array.

8. Sort an array in ascending order.

9. Merge two arrays into one.

10. Find the duplicate elements in an array.

11. Remove duplicates from an array.

12. Rotate an array to the left by one position.

13. Find the second largest element in an array.

14. Check if two arrays are equal.

15. Move all zeros to the end of the array.

2D Array Questions
1. Declare a 2D array of integers with 3 rows and 3 columns.

2. Initialize a 3x3 matrix with values from 1 to 9.

3. Find the sum of all elements in a 2D array.

4. Print the elements of a 2D array row-wise.

5. Print the elements of a 2D array column-wise.

6. Transpose a 2D array.

7. Add two 2D arrays.

8. Multiply two 2D arrays.

9. Find the maximum element in each row of a 2D array.


10. Check if a 2D array is a square matrix.

11. Check if a 2D array is symmetric.

12. Calculate the sum of diagonal elements.

13. Find the row with the maximum sum.

14. Rotate a 2D array 90 degrees clockwise.

15. Check if a 2D array is an identity matrix.


Solutions: Array Questions
1. 1. Declare an array of 10 integers in Java.

Solution:

int[] arr = new int[10];

2. 2. Initialize an array with the first 5 prime numbers.

Solution:

int[] primes = {2, 3, 5, 7, 11};

3. 3. Find the sum of all elements in an array.

Solution:

int sum = 0; for (int num : arr) sum += num;

4. 4. Find the maximum element in an array.

Solution:

int max = arr[0]; for (int num : arr) if (num > max) max = num;

5. 5. Reverse the elements of an array.

Solution:

for (int i = 0; i < [Link] / 2; i++) { int temp = arr[i]; arr[i] = arr[[Link] - 1 - i]; arr[[Link] - 1 - i]

= temp; }

6. 6. Check if an array contains a specific value.

Solution:

boolean found = false; for (int num : arr) if (num == value) found = true;

7. 7. Count the number of even and odd numbers in an array.

Solution:

int even = 0, odd = 0; for (int num : arr) { if (num % 2 == 0) even++; else odd++; }

8. 8. Sort an array in ascending order.

Solution:

[Link](arr);

9. 9. Merge two arrays into one.


Solution:

int[] merged = new int[[Link] + [Link]]; [Link](arr1, 0, merged, 0, [Link]);

[Link](arr2, 0, merged, [Link], [Link]);

10. 10. Find the duplicate elements in an array.

Solution:

for (int i = 0; i < [Link]; i++) for (int j = i + 1; j < [Link]; j++) if (arr[i] == arr[j])

[Link]("Duplicate: " + arr[i]);

11. 11. Remove duplicates from an array.

Solution:

Set<Integer> set = new HashSet<>(); for (int num : arr) [Link](num);

12. 12. Rotate an array to the left by one position.

Solution:

int first = arr[0]; for (int i = 1; i < [Link]; i++) arr[i - 1] = arr[i]; arr[[Link] - 1] = first;

13. 13. Find the second largest element in an array.

Solution:

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int num : arr) { if (num > first) {

second = first; first = num; } else if (num > second && num != first) second = num; }

14. 14. Check if two arrays are equal.

Solution:

boolean equal = [Link](arr1, arr2);

15. 15. Move all zeros to the end of the array.

Solution:

int[] result = new int[[Link]]; int index = 0; for (int num : arr) if (num != 0) result[index++] = num;
Solutions: 2D Array Questions
1. 1. Declare a 2D array of integers with 3 rows and 3 columns.

Solution:

int[][] matrix = new int[3][3];

2. 2. Initialize a 3x3 matrix with values from 1 to 9.

Solution:

int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};

3. 3. Find the sum of all elements in a 2D array.

Solution:

int sum = 0; for (int[] row : matrix) for (int val : row) sum += val;

4. 4. Print the elements of a 2D array row-wise.

Solution:

for (int[] row : matrix) [Link]([Link](row));

5. 5. Print the elements of a 2D array column-wise.

Solution:

for (int j = 0; j < matrix[0].length; j++) { for (int i = 0; i < [Link]; i++) [Link](matrix[i][j]

+ " "); [Link](); }

6. 6. Transpose a 2D array.

Solution:

int[][] transpose = new int[matrix[0].length][[Link]]; for (int i = 0; i < [Link]; i++) for (int j

= 0; j < matrix[0].length; j++) transpose[j][i] = matrix[i][j];

7. 7. Add two 2D arrays.

Solution:

int[][] sum = new int[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) sum[i][j] = a[i][j] + b[i][j];

8. 8. Multiply two 2D arrays.

Solution:

int[][] product = new int[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 3; k++)
product[i][j] += a[i][k] * b[k][j];

9. 9. Find the maximum element in each row of a 2D array.

Solution:

for (int[] row : matrix) { int max = row[0]; for (int val : row) if (val > max) max = val;

[Link]("Max: " + max); }

10. 10. Check if a 2D array is a square matrix.

Solution:

boolean isSquare = [Link] == matrix[0].length;

11. 11. Check if a 2D array is symmetric.

Solution:

boolean symmetric = true; for (int i = 0; i < [Link]; i++) for (int j = 0; j < matrix[0].length; j++) if

(matrix[i][j] != matrix[j][i]) symmetric = false;

12. 12. Calculate the sum of diagonal elements.

Solution:

int diagSum = 0; for (int i = 0; i < [Link]; i++) diagSum += matrix[i][i];

13. 13. Find the row with the maximum sum.

Solution:

int maxSum = Integer.MIN_VALUE, rowIndex = -1; for (int i = 0; i < [Link]; i++) { int rowSum =

0; for (int val : matrix[i]) rowSum += val; if (rowSum > maxSum) { maxSum = rowSum; rowIndex = i; }

14. 14. Rotate a 2D array 90 degrees clockwise.

Solution:

int[][] rotated = new int[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) rotated[j][2-i] = matrix[i][j];

15. 15. Check if a 2D array is an identity matrix.

Solution:

boolean isIdentity = true; for (int i = 0; i < [Link]; i++) for (int j = 0; j < matrix[0].length; j++) if

((i == j && matrix[i][j] != 1) || (i != j && matrix[i][j] != 0)) isIdentity = false;

Common questions

Powered by AI

To determine if two arrays are equal in Java, consider using the Arrays.equals() method, which checks if both arrays are not only the same length but also have identical elements in the same order. It simplifies and ensures an accurate comparison by handling both reference and primitive types correctly, maintaining semantic correctness and eliminating manual iteration pitfalls .

To count even and odd numbers in an array, iterate over the array elements, use modulus operation (num % 2), and increment respective counters for even when modulus equals zero and odd otherwise. This method is crucial in data analysis for categorizing datasets, detecting trends or anomalies in numerical data fields, and simplifying subsequent data operations by transforming distributions into tangible counts .

To check if a 2D array is symmetric, verify if the number of rows equals the number of columns and then iterate through the array checking if element [i][j] equals element [j][i] for all i and j. Assumptions include that the array is a square matrix. Potential pitfalls are neglecting to check for non-square matrices or missing asymmetric elements due to incomplete iteration. The check fails without these considerations, leading to incorrect symmetry conclusions .

Rotating an array to the left by one position involves holding the first element temporarily, shifting subsequent elements left, and placing the first element at the end. This can be expanded to rotate by multiple positions efficiently. Practical applications include data shuffling in cyclic patterns, simulating buffer operations, or implementing features in gaming logic where shifting states in sequences is required .

Removing duplicates from an array in Java involves challenges such as maintaining insertion order and ensuring algorithmic efficiency. Utilize a hash set to track unique elements when iterating through the array. This approach leverages the O(1) average time complexity for insertions in hash sets, balancing both efficiency and simplicity. A potential downside is increased space complexity due to auxiliary data structures, but it's outweighed by performance gains in context-specific applications .

To transpose a 2D array, create a new matrix where rows become columns and vice versa. Iterate through each element of the original matrix, setting the element at [i][j] in the original matrix to [j][i] in the transposed matrix. This transposing operation is vital in mathematical operations such as determinant calculation, solving systems of equations, and simplifying operations like finding the inverse of matrices .

Two arrays in Java can be merged using the System.arraycopy method. First, create a new array with a length equal to the sum of the two arrays. Use System.arraycopy to copy elements from the first array to the new array, and then from the second array to the new array starting from the first array's length. This method efficiently concatenates the arrays .

Sorting an array involves arranging elements in a specified order. Java's built-in Arrays.sort() enhances this process using the Dual-Pivot Quicksort algorithm, which is efficient and has an average time complexity of O(n log n). This method automatically adapts for both reference types and primitives, offering an optimized approach with minimal complexity and high efficiency compared to manual sorting implementation .

The diagonal sum of a 2D array, specifically square matrices, is calculated by summing elements at positions where row and column indices are equal. This sum has mathematical relevance in trace calculation, affecting determinant values, eigenvector assessments, and simplifying scalar-multiplication verifications. These applications are pivotal in fields like linear algebra and computer graphics, where matrix properties fundamentally affect system behavior .

The algorithm to find the second largest element iterates through the array, maintaining two variables: 'first' and 'second'. Initialize 'first' to the lowest integer value and 'second' to the same. For each element, if it is greater than 'first', update 'second' with 'first' and 'first' with the current element. If the current element is greater than 'second' and not equal to 'first', update 'second'. This approach ensures the algorithm runs in O(n) time, which is efficient . Its significance lies in applications where identifying the second-ranked element is crucial, such as finding runner-ups in competitions or the next-highest salary in a dataset.

You might also like