Final answer:
Enhanced for loops in Java, also known as for-each loops, are used to simplify iterating over arrays. For printing all elements in a single row, use 'System.out.print(element + " ")' within the loop. To compute the maximum or count negative numbers, a variable is used to store the result, updated as the loop iterates over the array elements.
Step-by-step explanation:
Enhanced For Loop Examples in Java
To complete the tasks given, you can use the 'enhanced for loop' or 'for-each loop' in Java, which simplifies iteration over arrays and collections. Below are examples of how to write enhanced for loops for each task.
a. Printing All Elements of an Array
To print all elements of an array in a single row separated by spaces, you can use the following code:
int[] array = {1, 2, 3, 4, 5};
for (int element : array) {
System.out.print(element + " ");
}
b. Computing the Maximum of All Elements in an Array
To compute the maximum of all elements in an array, use this loop:
int[] array = {1, 2, 3, 4, 5};
int max = Integer.MIN_VALUE;
for (int element : array) {
if (element > max) {
max = element;
}
}
System.out.println("Maximum value is: " + max);
c. Counting Negative Elements in an Array
To count how many elements are negative in an array, the following loop can be utilized:
int[] array = {-1, 2, -3, 4, 5};
int countNegatives = 0;
for (int element : array) {
if (element < 0) {
countNegatives++;
}
}
System.out.println("Number of negative elements: " + countNegatives);