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

COMPUTER SOFTWARE APPLICATION - CITS





           Output:















           Explanation:
           •  In this program, we define a method reverseArray that takes an array of integers as a parameter and reverses
              the elements of the array in place.
           •  We declare an array numbers containing integers in the main method.
           •  We call the reverseArray method and pass the numbers array as an argument.
           •  Inside the reverseArray method, we use two pointers (left and right) to traverse the array from both ends and
              swap the elements until they meet in the middle.
           •  After reversing the array, we display the elements of the reversed array in the main method.



           TASK 5: Checking if an Array is Sorted in Ascending Order
               public class SortedArrayDemo {
                  public static void main(String[] args) {

                      int[] numbers = {1, 3, 5, 7, 9};
                      // Calling the method to check if the array is sorted
                      boolean sorted = isSorted(numbers);
                      if (sorted) {
                          System.out.println(“The array is sorted in ascending order.”);
                      } else {

                          System.out.println(“The array is not sorted in ascending order.”);
                      }
                  }
                  // Method to check if an array is sorted in ascending order

                  public static boolean isSorted(int[] arr) {
                      for (int i = 0; i < arr.length - 1; i++) {
                          if (arr[i] > arr[i + 1]) {
                              return false;
                          }

                      }
                      return true;
                  }
              }




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