Question

                                          &nb

                                                                                                                                                                                                                                                                                   

Write a static method named largestLessThan that takes two arguments. The first argument will be an array of int values (you may safely assume that all values in the array will be positive). The second argument will be an int max value. The method should return the largest value in the array that is less than the max value. If there is no value in the array that is less than the max value, then the method should return 0.

Examples:
    Given the following array declaration and definition.
        int[] theArray = {6, 4, 10, 2, 7, 13, 8, 15};

        largestLessThan (theArray , 13) will return 10
        largestLessThan (theArray , 7) will return 6
        largestLessThan (theArray , 50) will return 15
        largestLessThan (theArray , 1) will return 0

0 0
Add a comment Improve this question Transcribed image text
Answer #1
public class LargestLessThan {

    public static int largestLessThan(int[] arr, int num) {
        int max = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max && arr[i] < num) {
                max = arr[i];
            }
        }
        return max;
    }

    public static void main(String[] args) {
        int[] theArray = {6, 4, 10, 2, 7, 13, 8, 15};
        System.out.println(largestLessThan(theArray, 13));
        System.out.println(largestLessThan(theArray, 7));
        System.out.println(largestLessThan(theArray, 50));
        System.out.println(largestLessThan(theArray, 1));
    }
}
Add a comment
Know the answer?
Add Answer to:
                                          &nb
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT