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

COMPUTER SOFTWARE APPLICATION - CITS





           •  Inside the findMaxElement method, we iterate through the array elements and update the max variable if we
              encounter a larger element.
           •  The maximum element is returned and stored in the max variable in the main method.

           •  Finally, we print the maximum element to the console.



           TASK 3: Calculating the Sum of Array Elements
           public class SumArrayDemo {
               public static void main(String[] args) {
                   double[] values = {2.5, 3.0, 4.5, 1.5, 2.0};

                   // Calling the method to calculate the sum of array elements
                   double sum = calculateSum(values);
                   System.out.println(“Sum of array elements: “ + sum);
               }

               // Method to calculate the sum of array elements
               public static double calculateSum(double[] arr) {
                   double sum = 0;
                   for (double value : arr) {
                       sum += value;
                   }

                   return sum;
               }
           }
           Output:



















           Explanation:
           •  In this program, we define a method calculateSum that takes an array of doubles as a parameter and returns
              the sum of the array elements.
           •  We declare an array values containing double values in the main method.
           •  We call the calculateSum method and pass the values array as an argument.
           •  Inside the calculateSum method, we iterate through the array elements and accumulate their sum in the sum
              variable.





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