Page 85 - CTS - CSA TP - Volume 2
P. 85

COMPUTER SOFTWARE APPLICATION - CITS




              •  Finally, it prints out the sum of the array elements.
              •  The scanner.close() statement closes the scanner to release system resources.
           This program allows the user to dynamically input array elements and calculates the sum accordingly.


           TASK 2: Finding Maximum Element in an Array
           public class MaxElement {
               public static void main(String[] args) {

                   // Declare and initialize an array
                   int[] numbers = {10, 5, 20, 8, 15};
                    System.out.print(“Element in the array are: “);
                  // Assume the first element is the maximum
                   int max = numbers[0];



                   // Iterate through the array to find the maximum element
                   for (int i = 1; i < numbers.length; i++) {
                       System.out.print(numbers[i]+” “) ;
                       if (numbers[i] > max) {

                           max = numbers[i];
                       }
                   }
                   System.out.println();

                   // Print the maximum element
                   System.out.println(“Maximum element in the array: “ + max);
               }
           }
           Output:

































                                                           70

                               CITS : IT & ITES - Computer Software Application - Exercise 93
   80   81   82   83   84   85   86   87   88   89   90