The logic is very simple here, see the below.
- At first we need to assume the first smallest element.
- Then iterate over the array and compare with each element , whether its smaller than the assumed value or not. If array element is smaller then assign the array element value to assumed variable. Repeat the entire until end.
FindSmallestNumberInArray.java
package com.javadevelopersguide.lab.basic;
/**
* This program illustrate how to find the smallest number from an array.
*
* @author manoj.bardhan
*
*/
public class FindSmallestNumberInArray {
// Find the smallest value from an array.
public static void main(String[] args) {
int[] arr = { 200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150 };
// Assigning 0th index as first smallest number to proceed the program.
int smallest = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] <= smallest) {
smallest = arr[i];
}
}
System.out.println("Smallest Element is - " + smallest);
}
}
Output -
Smallest Element is - 3
Using Java 8
IntStream.of(arr).boxed().min(Comparator.naturalOrder()).get().intValue();
Happy Learning.
Follow for more details on @Facebook!!!
Find More :-
Find More :-
- Java 8 use Option - avoid NullPointerException
- Producer & Consumer problem solution using BlockingQueue.
- Write your first groovy program.
- Top 10 groovy interview question.
- Difference between groovy and java.
- What is full stack development experience.
- 5 fundamental questions of groovy.
- Write your first java program.
- Reverse string using recursive method in java.
- Comparator Interface with Examples
No comments:
Post a Comment