Posts Tagged ‘basic java program’

Find Largest and Smallest Value from an Array in Java

It is a sample basic java program. In this java program accepts a dynamic array from the user and find largest and smallest value from an array.

Program Name “LargestSmallest.java”

Program Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Find Maximum and Minimum Value from an Array in Java
import java.util.*;
class LargestSmallest
{
	public static void main(String []args)
	{
		Scanner console=new Scanner(System.in);
		System.out.println("\n********Largest and Smallest Value from Array********");
		System.out.print("\nEnter the size of array: ");
		int size=console.nextInt();
		int num[]=new int[size];
		int i,largest,smallest;
		System.out.println("Enter "+size+" numbers: ");
		for(i=0;i<size;i++)
		{
			num[i]=console.nextInt();
		}
		largest=num[0];
		smallest=num[0];
		for(i=0;i<size;i++)
		{
			if(num[i]>largest)
			{
				largest=num[i];
			}
			else if(num[i]<smallest)
			{
				smallest=num[i];
			}
		}
		System.out.print("\nSmallest value from the array is:  "+smallest);
		System.out.print("\nLargest value from the array is:  "+largest);
	}
}

Output
Java Example Output