Page 84 - CTS - CSA TP - Volume 2
P. 84
COMPUTER SOFTWARE APPLICATION - CITS
// Calculate the sum of array elements
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
// Display the sum of array elements
System.out.println(“Sum of array elements: “ + sum);
scanner.close(); // Close the scanner to avoid resource leak
}
}
Output:
Explanation:
• The program starts by importing the Scanner class from the java.util package, which is used to read input
from the keyboard.
• It creates a Scanner object named scanner to read input.
• The program prompts the user to enter the size of the array and reads the input using scanner.nextInt().
• It then creates an integer array numbers of the specified size.
• Using a for loop, the program prompts the user to enter each element of the array and reads the input for
each element.
• After reading all the elements, another for loop calculates the sum of all the elements of the array.
69
CITS : IT & ITES - Computer Software Application - Exercise 93