In: Computer Science
JAVA
/**
* posOfLargestElementLtOeT returns the position of the
largest element in the
* array that is less than or equal to the limit
parameter if all values are
* greater than limit, return -1;
*
* Precondition: the array is nonempty and all elements
are unique. Your
* solution must go through the array exactly
once.
*
* <pre>
* 0 == posOfLargestElementLtOeT(3, new double[] { -7
}) // value:-7 is in pos 0
* 5 == posOfLargestElementLtOeT(3, new double[] { 11,
-4, -7, 7, 8, 1 }), // value:1 is in pos 5
* -1 == posOfLargestElementLtOeT(-7, new double[] { 1,
-4, -5, 7, 8, 11 }), // all elements are > -7
*
* The code below is a stub version, you should replace
the line of code
* labeled TODO with code that achieves the above
specification
* </pre>
*/
public static int posOfLargestElementLtOeT(double
limit, double[] list) {
return -2; // TODO 2: fix this
code
}
Program in java:
//class definition
public class LargestElement {
//main method definition
public static void main(String[] args) {
//calling funtion to
find the position of largest number
System.out.println(posOfLargestElementLtOeT(3, new
double[]{-7}));
System.out.println(posOfLargestElementLtOeT(3, new
double[]{11,-4,-7,7,8,1}));
System.out.println(posOfLargestElementLtOeT(-7, new
double[]{1,-4,-5,7,8,11}));
}
//declaring the function to calculate largest
number
static int posOfLargestElementLtOeT(int val,
double[] array){
//declare varibale
int pos=-1;
double largest=0;
boolean flag=true;
//iterate through the
array to find the largest number within limit
for(int
i=0;i<array.length;i++){
//if the value of the element is less than the specified
limit
if(array[i]<val){
//this condition will be executed only once to store the largest
value
if(flag==true){
//storing the first element less than the specified limit as the
largest
largest=array[i];
//marking this position as the largest element position
pos=i;
}
//checking to find the largest number subsequent from the array
less than specified limit
if(largest<array[i]){
//storing the first element less than the specified limit as the
largest
largest=array[i];
//marking this position as the largest element position
pos=i;
}
}
}
//returning the position
of the largest element
return pos;
}
}
Output: