Java Program to find Smallest element in the array
Get array size n and n elements of array, then find the smallest element among those elements.
Sample Input 1:
5 5 7 9 3 1
Sample Output 1:
1
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class SmaArr
{
public static void main(String args[])
{
int size,i,num;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size Of Array:");
size=sc.nextInt();
int a[]=new int[100];
System.out.println("Enter The Array Elements:\n");
for(i=0;i<size;i++)
{
a[i]=sc.nextInt();
}
int min=a[0];
for(i=0;i<size;i++)
{
if(a[i]<min)
{
min=a[i];
}
}
System.out.println("The Smallest Element In The Array Is:"+min);
}
}
Program Explanation
Array is a Collection of data with same type.
1. Get the size of the Array
2. Create a array with the given size (Array has 0 to size-1 index to access every location)
0 1 2 3 ...... size-2 size-1
3. Get Inputs for Array (See Previous Problems for detail)
4. Initially assume a[0] is the largest number
max = a[0]
In the second For Loop,
i starts at 0, and incremented by 1 after every iteration. iteration stops when i is equal to size.
in every iteration the if(a[i]<min) checks the located element in current index is less than min
if the element located in any position is less than min, then assign the element as min by using min= a[i]
finally min holds the minimum value in the array after all the iterations.
Comments
Related Programs
- Java Program to get and print the array elements
- Java Program to find the sum of array elements.
- Java Program to find the average of array Elements
- Java Program to Search an Element in an array
- Java Program to find Largest element in the array
- Java Program to print all the numbers which are less than given key element from a given array.
- Java Program to Sort the Elements in ascending order.
- Java Program to Sort the Elements in descending order.
- Addition of Matrix in Java
- Java Program to delete an Element from the Array
- Java Program to merge two Arrays
- Java Program to Multiply two Matrices
- Java Program to Reverse the Elements of Array
- Java Program to Reverse the First Half Elements of Array
- Java Program to Reverse the Second Half Elements of Array
- Java Program to find the Second Largest Number in the Array
- Java Program to find the Second Smallest Number in the Array
- Java Program to transpose the Matrix