Write a program to input integer elements into an array of size 20 and perform the following operations: (i) Display the largest number from the array. (ii) Display the smallest number from the array. (iii) Display the sum of all the elements of the array.
Topic: Largest, smallest and sum of array elements
Answer
import java.util.Scanner;
class LargestSmallest { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[] = new int[20];
System.out.println("Enter 20 integers :"); for(int i = 0; i < 20; i++) a[i] = sc.nextInt();
int large = a[0], small = a[0], sum = 0;
for(int i = 0; i < 20; i++) { if(a[i] > large) large = a[i]; if(a[i] < small) small = a[i]; sum = sum + a[i]; }
System.out.println("Largest number = " + large); System.out.println("Smallest number = " + small); System.out.println("Sum of elements = " + sum); } }
Three tasks, all handled in a single traversal — there is no need for three separate loops.
The critical decision is how to initialise large and small. Set BOTH to the first element, a[0]. Initialising large to 0 fails the moment every element is negative, and initialising small to 0 fails whenever every element is positive. Taking the first element as the starting point is always safe, whatever the data.
Note that two separate ifs are used rather than if-else: a single element could in principle update neither, and using else if would be wrong in the first pass where a[0] equals both.
sum starts at 0, since it is built by addition — contrast a product accumulator, which must start at 1.
Check with the numbers 1 to 20 in any order: largest 20, smallest 1, sum 210.
a[] int[20] - the twenty integers entered by the user large int - largest element found so far small int - smallest element found so far sum int - running total of all the elements i int - loop variable sc Scanner - object used to read input