TechArena Community How to find second largest value from array

#1
18-11-2009
 Member Join Date: Jan 2009 Posts: 48
How to find second largest value from array

Hi friends,

I am beginner is programming field,May be because of that I have troubles while writing complex and large programs. One of them is below.

I have to write the program which will display the second highest value from the array values.But there is also one condition that the this number should not be negative value.

Can you able to help me to code this program.
#2
18-11-2009
 Member Join Date: Oct 2005 Posts: 2,389
Re: How to find second largest value from array

Hi,

Good thing for you is that I have coded the program to print second highest value from the all values from the array. see below:

Quote:
 #include void main() { int i,j,n,a[20],first_max,second_max; printf("Enter how many numbers you want to enter"); scanf("%d",&n); for(i=0;ia[1]) first_max=a[0]; second_max=a[1]; else first_max=a[1]; second_max=a[0]; for(j=2;jsecond_max) if(a[j]>first_max) { first_max=a[j]; second_max=first_max; } else second_max=a[j]; printf("The second largest number is %d", second_max); }
#3
18-11-2009
 Member Join Date: May 2008 Posts: 2,383
Re: How to find second largest value from array

Something below can help you. I used sorting method to find the 2nd highest number.

Code:

Quote:
 public static void main(String[] args) { int array[]={13,12,34,56,73,21,232,234,235,240}; int max ,secndmax; max = secndmax= array[0]; System.out.println("Initial value is "+ secndmax); for (int i=1;imax ){ secndmax=max; max=array[i]; }else if(array[i]>secndmax){ secndmax = array[i]; } } System.out.println("Second Max element is "+ secndmax); }
__________________
The FIFA Manager 2009 PC Game
#4
18-11-2009
 Member Join Date: Feb 2008 Posts: 1,848
Re: How to find second largest value from array

I am not giving you the all the answer. But according to me you have to use 'if loop' to verify condition inside 'for loop'.

For reference take look on the below loop:

Quote:
 max = second_max= array[0]; for (i=0;i,length;i++) { if (array[i]>max) { 2ndmax=max; max=array[i]; } } return second_max

 Tags: