Coding Questions - Arrays
-
Array Sum:
Question: Write a Java program to find the sum of all elements in an array.
Answer:
public class ArraySum { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; for (int num : numbers) { sum += num; } System.out.println("Sum of the array elements: " + sum); } }Description: This program initializes an array and calculates the sum of its elements using a for-each loop.
-
Find Maximum Element:
Question: Write a Java program to find the maximum element in an array.
Answer:
public class MaxElement { public static void main(String[] args) { int[] numbers = {10, 5, 8, 20, 15}; int max = numbers[0]; for (int num : numbers) { if (num > max) { max = num; } } System.out.println("Maximum element in the array: " + max); } }Description: This program iterates through the array to find the maximum element.
-
Array Rotation:
Question: Write a Java program to rotate elements of an array to the left by a given number of positions.
Answer:
public class ArrayRotation { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; int rotations = 2; for (int i = 0; i < rotations; i++) { int temp = numbers[0]; for (int j = 0; j < numbers.length - 1; j++) { numbers[j] = numbers[j + 1]; } numbers[numbers.length - 1] = temp; } System.out.println("Array after " + rotations + " left rotations: " + Arrays.toString(numbers)); } }Description: This program rotates the elements of an array to the left by the specified number of positions using a temporary variable.
-
Array Intersection:
Question: Write a Java program to find the intersection of two arrays.
Answer:
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class ArrayIntersection { public static void main(String[] args) { int[] array1 = {1, 2, 3, 4, 5}; int[] array2 = {3, 4, 5, 6, 7}; Set<Integer> set1 = new HashSet<>(Arrays.asList(array1)); Set<Integer> set2 = new HashSet<>(Arrays.asList(array2)); set1.retainAll(set2); int[] intersection = set1.stream().mapToInt(Integer::intValue).toArray(); System.out.println("Intersection of the arrays: " + Arrays.toString(intersection)); } }Description: This program uses sets to find the intersection of two arrays, converting the result back to an array.
-
Array Reversal:
Question: Write a Java program to reverse the elements of an array.
Answer:
import java.util.Arrays; public class ArrayReversal { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length / 2; i++) { int temp = numbers[i]; numbers[i] = numbers[numbers.length - i - 1]; numbers[numbers.length - i - 1] = temp; } System.out.println("Reversed array: " + Arrays.toString(numbers)); } }Description: This program reverses the elements of an array using a two-pointer approach.
No comments:
Post a Comment