Skip to content
C

Array Programs

Array-based problems are common in interviews and help build a strong understanding of indexing, traversal, and basic algorithms like searching and sorting.


Why practice these?

Array-based problems are common in interviews and help build a strong understanding of indexing, traversal, and basic algorithms like searching and sorting.

Program 1: Find the Largest Element in an Array

java
public class LargestElement { public static void main(String[] args) { int[] numbers = {12, 45, 7, 89, 34}; int largest = numbers[0]; for (int num : numbers) { if (num > largest) { largest = num; } } System.out.println("Largest element: " + largest); } }

Output:

Largest element: 89

Program 2: Reverse an Array

java
public class ReverseArray { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; for (int i = numbers.length - 1; i >= 0; i--) { System.out.print(numbers[i] + " "); } } }

Output:

5 4 3 2 1 

Program 3: Sum of Array Elements

java
public class ArraySum { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40}; int sum = 0; for (int num : numbers) { sum += num; } System.out.println("Sum: " + sum); } }

Output:

Sum: 100

Key Points to Remember

  • Enhanced for-each loops (for (int num : array)) are convenient for simply reading through array elements.
  • Array-based problems (finding max/min, reversing, sorting) are extremely common in coding interviews.
  • Always be careful with index boundaries to avoid ArrayIndexOutOfBoundsException.