This repository contains Java programs for basic array operations and other beginner-level assignments. The main program in this repository demonstrates how to: Find the largest number in a given array. Calculate the sum of all elements in the array. The program uses simple array traversal and basic Java concepts.
To write a Java program to find the largest number and calculate the sum of elements in a given array.
- Start the program.
- Declare an integer array with given numbers.
- Initialize
largest
with the first element andsum
as 0. - Traverse the array:
- If the current element is greater than
largest
, updatelargest
. - Add the current element to
sum
.
- If the current element is greater than
- Display the largest number and sum of elements.
- End the program.
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
// Step 1: Declare the array
int[] numbers = {10, 25, 7, 42, 15};
// Step 2: Initialize largest and sum
int largest = numbers[0];
int sum = 0;
// Step 3: Traverse the array
for (int num : numbers) {
if (num > largest) {
largest = num;
}
sum += num;
}
// Step 4: Display results
System.out.println("Numbers in array: " + Arrays.toString(numbers));
System.out.println("Largest number: " + largest);
System.out.println("Sum of elements: " + sum);
}
}