2nd largest number

 

  1. #include<iostream>
  2. using namespace std;
  3. int main ()
  4. {
  5.     int A[10], n, i, j, x;
  6.     cout << "Enter size of array : ";
  7.     cin >> n;
  8.     cout << "Enter elements of array : ";
  9.     for (i = 0; i < n; i++)
  10.         cin >> A[i];    
  11.     for (i = 0; i < n; i++)
  12.     {
  13.         for (j = i + 1; j < n; j++)
  14.         {
  15.             if (A[i] < A[j])
  16.             {
  17.                 x = A[i];
  18.                 A[i] = A[j];
  19.                 A[j] = x;
  20.             }
  21.         }
  22.     }
  23.     cout << "Second largest number : " << A[1];
  24.     cout << "\nSecond smallest number : " << A[n - 2];
  25.     return 0;



  26. ````````````````````````````````````````````````````````````````````` 


#include <limits.h>
#include <stdio.h>

/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
int i, first, second;

/* There should be atleast two elements */
if (arr_size < 2) {
printf(" Invalid Input ");
return;
}

first = second = INT_MIN;
for (i = 0; i < arr_size; i++) {
/* If current element is greater than first
then update both first and second */
if (arr[i] > first) {
second = first;
first = arr[i];
}

/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest element\n");
else
printf("The second largest element is %dn", second);
}

/* Driver program to test above function */
int main()
{
    printf("The second largest+++++++++ element is %d \n", INT_MIN);
int arr[] = { 12, 35, 1, 10, 34, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
print2largest(arr, n);
return 0;
}



Comments

Popular posts from this blog

Difference between Structure and Array in C

Mutitreading Notes