Android Tutorial , Programming Tutorial, Php Tutorial, Learn Android, HTML Tutorial, Coding , Java Tutorial, GTU Programs, Learning Programming

Monday, 5 September 2016

Write a program to find out the second largest value from the N values Stored in array

In this program, code is explain about to find out the second largest value from the array. First , user must set the limit of the array. Then enter value in array. Which value is second largest from the array it will display at the end. In this program, for loop is used to find second largest value. User can also any looping structure if they don't want use for loop.

Step for Execute Program :

1) Open Command prompt
2) Set Path
3) Compile File     // javac SecondLargeArray.java
4) Run File           //java SecondLargeArray
5) Fill the Details



File Name : SecondLargeArray.java


 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
35
36
37
38
39
40
41
42
43
import java.io.*;
class SecondLargeArray
{
 public static void main(String []s) throws Exception
 {
  int n ,second=0,temp;

   DataInputStream da=new DataInputStream(System.in);
  
  System.out.println("Enter length of array :");  
  n=Integer.parseInt(da.readLine());
  
  int []arr1=new int[n];
  System.out.println("Enter value of array :");  
  for(int i=0;i<n;i++)
  {
   arr1[i]=Integer.parseInt(da.readLine()); 
  }
  for(int i=0;i<n;i++)
  {
   for(int j=i+1;j<n;j++)
   {
    if(arr1[i]>arr1[j])
    {
     temp=arr1[i];
     arr1[i]=arr1[j];
     arr1[j]=temp; 
    }
   }
  }

   second=arr1[n-1];
  for(int i=n-1;i>=0;i--)
  {
   if(arr1[i]<second)
   {
    System.out.println("Second Largest value :"+arr1[i]);
    break;
   }
  }

  }
}





Output :

Second Largest Value from Array

0 comments:

Post a Comment

Like us on Facebook

Site Visitor

Powered by Blogger.