second max in array code example

Example 1: find second max element in array in 1 iteration

/**
 * C program to find second largest number in an array
 */

#include 
#include  // For INT_MIN

#define MAX_SIZE 1000     // Maximum array size 

int main()
{
    int arr[MAX_SIZE], size, i;
    int max1, max2;

    /* Input size of the array */
    printf("Enter size of the array (1-1000): ");
    scanf("%d", &size);

    /* Input array elements */ 
    printf("Enter elements in the array: ");
    for(i=0; i max1)
        {
            /*
             * If current element of the array is first largest
             * then make current max as second max
             * and then max as current array element
             */
            max2 = max1;
            max1 = arr[i];
        }
        else if(arr[i] > max2 && arr[i] < max1)
        {
            /*
             * If current array element is less than first largest
             * but is greater than second largest then make it
             * second largest
             */
            max2 = arr[i];
        }
    }

    printf("First largest = %d\n", max1);
    printf("Second largest = %d", max2);

    return 0;
}

Example 2: find maximum and second maximum number in array

#include 
int main()
{
    std::cout << "Enter 5 numbers : ";
    int arr[5];
    
    for (int i = 0; i < 5; std::cin >> arr[i++]);

    int max = arr[0], second = 0;

    for (int i = 1; i < 5; i++)
        if (arr[i] > max)
            max = arr[i];
    std::cout << "Maximum number : " << max << "\n";
    bool found = false;
    for (int i = 0; i < 5; i++)
    {
        if (arr[i] == max)
            continue;
        else if (arr[i] > second)
        {
            second = arr[i];
            found = true;
        }
    }
    if (found)
        std::cout << "Second maximum numbers : " << second;
    else
        std::cout << "Second maximum number not found.";
}

Tags: