2nd largest number
#include<iostream>using namespace std;
int main ()
{int A[10], n, i, j, x;
cout << "Enter size of array : ";
cin >> n;
cout << "Enter elements of array : ";
for (i = 0; i < n; i++)
cin >> A[i];
for (i = 0; i < n; i++)
{for (j = i + 1; j < n; j++)
{if (A[i] < A[j])
{x = A[i];
A[i] = A[j];
A[j] = x;
}}}cout << "Second largest number : " << A[1];
cout << "\nSecond smallest number : " << A[n - 2];
return 0;
`````````````````````````````````````````````````````````````````````
#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
Post a Comment