3. Write a java program to
• Read and store 10 numbers in an Arr ay.
• Display the sum mat ion of posit ive numbe rs less than 8.
• Display t he sorted arr ay elements in descending orde r.
To write a Java program that reads and stores 10 numbers in an array, and then performs additional operations like finding the sum of positive numbers less than 8 and displaying the sorted array elements in descending order, you can follow the steps below:
1. Start by creating a new Java class. Let's name it "NumberArrayProgram".
2. Declare a class-level constant variable named SIZE, and set its value to 10. This will represent the size of the array.
```java
public class NumberArrayProgram {
private static final int SIZE = 10;
public static void main(String[] args) {
// Rest of the code will go here
}
}
```
3. Inside the main method, declare an integer array named "numbers" with the size equal to the SIZE constant.
```java
int[] numbers = new int[SIZE];
```
4. Use a loop to read 10 numbers from the user and store them in the array.
```java
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers:");
for (int i = 0; i < SIZE; i++) {
numbers[i] = scanner.nextInt();
}
```
5. Calculate the sum of positive numbers less than 8 by iterating over the array and adding up the positive numbers that are less than 8.
```java
int sum = 0;
for (int i = 0; i < SIZE; i++) {
if (numbers[i] > 0 && numbers[i] < 8) {
sum += numbers[i];
}
}
System.out.println("Sum of positive numbers less than 8: " + sum);
```
6. Sort the array elements in descending order using the `Arrays.sort()` method and a custom comparator.
```java
Arrays.sort(numbers);
System.out.println("Sorted array elements in descending order:");
for (int i = SIZE-1; i >= 0; i--) {
System.out.println(numbers[i]);
}
```
7. Finally, close the scanner to prevent resource leaks.
```java
scanner.close();
```
The complete program will look like this:
```java
import java.util.Arrays;
import java.util.Scanner;
public class NumberArrayProgram {
private static final int SIZE = 10;
public static void main(String[] args) {
int[] numbers = new int[SIZE];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 10 numbers:");
for (int i = 0; i < SIZE; i++) {
numbers[i] = scanner.nextInt();
}
int sum = 0;
for (int i = 0; i < SIZE; i++) {
if (numbers[i] > 0 && numbers[i] < 8) {
sum += numbers[i];
}
}
System.out.println("Sum of positive numbers less than 8: " + sum);
Arrays.sort(numbers);
System.out.println("Sorted array elements in descending order:");
for (int i = SIZE-1; i >= 0; i--) {
System.out.println(numbers[i]);
}
scanner.close();
}
}
```
Now, when you run the program, it will prompt you to enter 10 numbers. After entering the numbers, it will display the sum of positive numbers less than 8 and the sorted array elements in descending order.