Challenge: Find Maximum and Minimum in Array
Taak
Swipe to start coding
Your task is to write two methods: one to find the maximum value and one to find the minimum value in the array.
- In the
findMax
method, initialize themax
variable with the first element of the array. - In the for loop, compare the current element with
max
. - If the current element is greater, update
max
with the current element. - Return the value of the
max
variable. - In the
findMin
method, initialize themin
variable with the first element of the array. - In the for loop, compare the current element with
min
. - If the current element is smaller, update
min
with the current element. - Return the value of the
min
variable. - In the
main
method, call thefindMax
method with the correct parameter, pass thenumbers
array into it, and assign the result to themax
variable. - In the
main
method, call thefindMin
method with the correct parameter, pass thenumbers
array into it, and assign the result to themin
variable.
Oplossing
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.example;
public class Main {
static int findMax(int[] array) {
int max = array[0];
for (int number : array) {
if (number > max) {
max = number;
}
}
return max;
}
static int findMin(int[] array) {
int min = array[0];
for (int number : array) {
if (number < min) {
min = number;
}
}
return min;
}
public static void main(String[] args) {
int[] numbers = {10, -3, 25, 7, 99, -50, 0, 12};
int max = findMax(numbers);
int min = findMin(numbers);
System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);
}
}
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 2. Hoofdstuk 8
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.example;
public class Main {
static int findMax(int[] array) {
int max = array[___];
for (int number : array) {
if (___ > max) {
max = ___;
}
}
return ___;
}
static int findMin(int[] array) {
int min = array[___];
for (int number : array) {
if (___ < min) {
min = ___;
}
}
return ___;
}
public static void main(String[] args) {
int[] numbers = {10, -3, 25, 7, 99, -50, 0, 12};
int max = ___;
int min = ___;
System.out.println("Maximum: " + max);
System.out.println("Minimum: " + min);
}
}
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.