|
Answer» Approach: - For storing the largest and smallest numbers create two variables named smallest and largest.
- Assign Integer.MAX_VALUE to the variable smallest
- Assign Integer.MIN_VALUE to the variable largest
- In each traversal of for loop, we will compare the current element with the largest and smallest number and update the value accordingly.
- If a number is larger than the largest, then it can not be smaller than the smallest, therefore, we can skip if the first condition holds.
import java.util.*;public class InterviewBit{ public static VOID main(String args[]) { int[] inputArray = {10,20, 22, 30, 77}; int largest = inputArray[0]; int smallest = inputArray[0]; for( int number : inputArray ) { if(number > largest) { largest = number; } else if (smallest > number) { smallest = number; } } System.out.println("Largest and Smallest numbers are " + largest +" "+smallest); }}Output : Largest and Smallest numbers are 77 10ConclusionIn this article, we have covered the most IMPORTANT and commonly asked interview questions based on arrays. To make the most of all the knowledge AVAILABLE, it is absolutely necessary to practice data structures and algorithms as much as POSSIBLE. You should keep in mind certain properties of array data structures, for example, array index starts at 0, the elements of an array are stored in contiguous MEMORY locations, etc. Additional Interview Resources: - Data Structure Interview Questions
- Algorithm Interview Questions
- DSA Tutorial
|