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

COMPUTER SOFTWARE APPLICATION - CITS




           Output:


















           Explanation:
              •  This program calculates the sum of elements in an array of integers.
              •  It initializes an array numbers with values {1, 2, 3, 4, 5}.
              •  It iterates through each element of the array using a for loop and adds each element to the variable sum.
              •  Finally, it prints the sum of the array elements.



           TASK 1_Method2:   Java program that allows the user to input array elements through the keyboard and
           displays the sum of those elements

           Here’s a Java program that allows the user to input array elements through the keyboard and displays the sum
           of those elements:



           //Sum of array elements
           import java.util.Scanner;
           public class ArraySum {
               public static void main(String[] args) {
                   Scanner scanner = new Scanner(System.in);



                   // Prompt the user to enter the size of the array
                   System.out.print(“Enter the size of the array: “);
                   int size = scanner.nextInt();



                  // Create an array of the specified size
                   int[] numbers = new int[size];

                   // Prompt the user to enter array elements

                   System.out.println(“Enter the elements of the array:”);
                   for (int i = 0; i < size; i++) {
                       System.out.print(“Element “ + (i + 1) + “: “);
                       numbers[i] = scanner.nextInt();
                   }





                                                           68

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