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

COMPUTER SOFTWARE APPLICATION - CITS





           •  The sum of array elements is returned and stored in the sum variable in the main method.
           •  Finally, we print the sum of array elements to the console.
           These examples illustrate how to pass arrays to methods in Java. By passing arrays to methods, we can perform
           operations on arrays effectively and encapsulate array-related logic within methods, promoting code reusability
           and readability.


           TASK 4: Reversing an Array
                  // Reverse Array Demo
              public class ReverseArrayDemo {
                  public static void main(String[] args) {

                      int[] numbers = {1, 2, 3, 4, 5};
                      // Displaying the original array
                      System.out.print(“Original array : “);
                      for (int num : numbers) {

                          System.out.print(num + “ “);
                      }
                      // Calling the method to reverse the array
                      reverseArray(numbers);
                      // Displaying the reversed array
                      System.out.println();

                      System.out.print(“Reversed array: “);
                      for (int num : numbers) {
                          System.out.print(num + “ “);
                      }

                  }
                  // Method to reverse an array
                  public static void reverseArray(int[] numbers) {
                      int left = 0;
                      int right = numbers.length - 1;

                      while (left < right) {
                          // Swap elements at left and right indices
                          int temp = numbers[left];
                          numbers[left] = numbers[right];

                          numbers[right] = temp;
                          // Move left index to the right and right index to the left
                          left++;
                          right--;
                      }
                  }

              }


                                                           102

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