Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to generate random number array within a range and get min and max value
At first, create a double array −
double[] val = new double[10];
Now, generate and display random numbers in a loop that loops until the length of the above array. We have used nextInt here for random numbers −
for (int i = 0; i < val.length; i++) {
val[i] = new Random().nextInt(100);
System.out.println(val[i]);
}
Now, get the min and max values. Compare each value of the random array with the MIN and MAX values −
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for (int i = 0; i < val.length; i++) {
if (val[i] < min)
min = val[i];
if (val[i] > max)
max = val[i];
}
Example
import java.util.Random;
public class Demo {
public static void main(String[] args) {
double[] val = new double[10];
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
System.out.println("Random number array...");
for (int i = 0; i < val.length; i++) {
val[i] = new Random().nextInt(100);
System.out.println(val[i]);
}
for (int i = 0; i < val.length; i++) {
if (val[i] < min)
min = val[i];
if (val[i] > max)
max = val[i];
}
System.out.println("Minimum element = " + min);
System.out.println("Maximum element = " + max);
}
}
Output
Random number array... 75.0 42.0 47.0 71.0 12.0 70.0 86.0 97.0 14.0 41.0 Minimum element = 12.0 Maximum element = 97.0
Advertisements