Write a java program to find smallest element and largest element in an Array.

 

Write a java program to find smallest element and largest element in an Array.


Or


Write a java program to find minimum element and maximum element in an Array.


Program:
import java.util.*;
public class max_min
{
public static void main (String args[])
{
int min,max,i,n;
Scanner sc=new Scanner(System.in);

System.out.println("Enter the  size  of an array: ");
n=sc.nextInt();

int a[]=new int[n];
System.out.println("Enter the  elements of an array: ");
for(i=0; i<n; i++)
{
a[i]=sc.nextInt();
}

min=a[0];
max=a[0];

for( i=0; i<n; i++)
{
//minimum
if(min>a[i])
{
min=a[i];
}
//maximum
if(max<a[i])
{
max=a[i];
}
}

System.out.println("\nThe smallest element is: "+min);

System.out.println("\nThe largest element is: "+max);
}
}


Output:

Enter the  size  of an array:
8
Enter the  elements of an array:
1
3
2
10
20
5
4
30
The smallest element is: 1

The largest element is: 30

Comments

Popular posts from this blog

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Write a java program to demonstrate static variable, methods, blocks.