Friday, 16 December 2016

C program to find the second largest in an array without sorting

The simplest way to find the second largest number in an array is to sort the numbers in either ascending or descending order and print the second number or last but one number respectively. Even though it is easier to understand, it consumes more time for sorting and also the numbers are reshuffled in the array. The following program finds the second largest without sorting the numbers in the array.

//Program to find the largest and the second largest number in an array
#include<stdio.h>
#include<conio.h>
main()
{
  int i, n, a[10], max, smax;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  printf("\nEnter the numbers in the array one by one\n");
  for(i=0;i<n;i++)
  scanf("%d",&a[i]);

  max=a[0];
  for(i=0;i<n;i++)
    if (a[i]>max)
       max=a[i];

  smax=a[0];
  for(i=0;i<n;i++)
    if ((a[i]>smax && a[i]<max) || smax==max)
       smax=a[i];

  printf("the largest number is %d\n",max);
  printf("the second largest number is %d\n",smax);

  getch();
}

/*
OUTPUT
-------
Enter the number of elements in the array
5                                                                              
                                                                               
Enter the numbers in the array one by one                                      
2                                                                              
8                                                                              
7                                                                              
1                                                                              
9                                                                              
the largest number is 9                                                        
the second largest number is 8                                                
*/

No comments:

Post a Comment