blog

Home / DeveloperSection / Blogs / Java program to find the largest and smallest number along with its index in an array of 10 element

Java program to find the largest and smallest number along with its index in an array of 10 element

Devesh Kumar Singh2423 16-Nov-2015
What is an Array?

 

Array is a collection of similar type of elements that have contiguous memory location.

Java array is an object that contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index. 


Advantage of Java Array

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.

  • Random access: We can get any data located at any index position.
Disadvantage of Java Array

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Thus we have the following program to accomplish our task:


package largestsmallest;
import java.io.*;
public class LargestSmallest {
    public static void main(String[] args)throws IOException {
        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));         int num[]=new int[10];
        int lindex=0,sindex=0;
        for(int i=0;i<10;i++)
        {
            System.out.println("enter a number");
            num[i]=Integer.parseInt(br.readLine());
        }
        int smallest = num[0];
        int largetst = num[0];
        for(int i=1; i<10; i++)
        {
            if(num[i] > largetst)
            {
                largetst = num[i];
                lindex=i;
            }
            if (num[i] < smallest)
            {
                 smallest = num[i];
                 sindex=i;
            }
        }
    System.out.println("Largest Number is : " + largetst+" At Index "+ lindex);     System.out.println("Smallest Number is : " + smallest+" At Index "+sindex);
}
   OUTPUT:
enter a number
44
enter a number
8
enter a number
96
enter a number
2
enter a number
76
enter a number
49
enter a number
72
enter a number
184
enter a number
22
enter a number
12
Largest Number is : 184 At Index 7
Smallest Number is : 2 At Index 3

Updated 13-Mar-2018

Leave Comment

Comments

Liked By