Exercise#1
unknown
java
3 years ago
1.4 kB
3
Indexable
import java.util.*;
public class FindMax
{
public static void main(String[] args)
{
System.out.println("Please enter how long you want the array to be:");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt(); // size of the array
scanner.close();
int[] numbers = new int[size]; // create an array of integers
// create a new random number generator
Random random = new Random();
// fill the array with random numbers
for (int i = 0; i < size; i++)
{
numbers[i] = random.nextInt(100) + 1; // generate a random integer between 1 and 100
}
// print out the array
for (int i = 0; i < size; i++)
{
System.out.print(numbers[i] + " ");
}
//Space Print
System.out.println();
// find the maximum value in the array
int max = findMax(numbers, 0, 0);
// print out the maximum value
System.out.println("The maximum value is: " + max);
}
public static int findMax(int[] arr, int index, int max)
{
if (index == arr.length)
{ // base case
return max;
}
if (arr[index] > max)
{
max = arr[index];
}
return findMax(arr, index+1, max); // recursive call
}
}
Editor is loading...