Java Programs on Single-Dimensional
Arrays
Program 1: Find the Largest Element in an Array
public class LargestElement {
public static void main(String[] args) {
// Declare and initialize the array
int[] numbers = {45, 12, 98, 23, 67};
// Assume the first element is the largest
int largest = numbers[0];
// Loop through the array to find the largest
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update if current element
is larger
}
}
// Print the largest element
System.out.println("The largest number is: " + largest);
}
}
Program 2: Count Even and Odd Numbers in an Array
public class CountEvenOdd {
public static void main(String[] args) {
// Declare and initialize the array
int[] nums = {10, 23, 45, 66, 77, 88};
int evenCount = 0;
int oddCount = 0;
// Loop through each number
for (int num : nums) {
if (num % 2 == 0) {
evenCount++; // Increment even counter
} else {
oddCount++; // Increment odd counter
}
}
// Print the result
System.out.println("Total Even Numbers: " + evenCount);
System.out.println("Total Odd Numbers: " + oddCount);
}
}
Program 3: Reverse an Array
public class ReverseArray {
public static void main(String[] args) {
// Declare and initialize the array
int[] original = {1, 2, 3, 4, 5};
System.out.println("Original Array:");
for (int num : original) {
System.out.print(num + " ");
}
System.out.println("\nReversed Array:");
// Loop from the end to the beginning
for (int i = original.length - 1; i >= 0; i--) {
System.out.print(original[i] + " ");
}
}
}