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

COMPUTER SOFTWARE APPLICATION - CITS




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

                      int[] numbers = {10, 30, 20, 50, 40};
                     System.out.print(“Element in the array: “ );
                      // Calling the method to find the maximum element
                      int max = findMaxElement(numbers);

                      System.out.println();
                      System.out.println(“Maximum element in the array: “ + max);
                  }
                     // Method to find the maximum element in an array
                  public static int findMaxElement(int[] arr) {

                      int max = arr[0];
                      for (int i = 1; i < arr.length; i++) {
                           System.out.print(arr[i] +” “);
                          if (arr[i] > max) {
                              max = arr[i];

                          }
                      }
                      return max;
                  }
              }

           Output:






















           Explanation:
           •  In this program, we define a method findMaxElement that takes an array of integers as a parameter and
              returns the maximum element in the array.
           •  We declare an array numbers containing integers in the main method.

           •  We call the findMaxElement method and pass the numbers array as an argument.






                                                           100

                               CITS : IT & ITES - Computer Software Application - Exercise 95
   110   111   112   113   114   115   116   117   118   119   120