Write a C Program to find the largest pair sum in an unsorted array.(hint: find 2 maximum elements from array and then find the sum of both numbers.)

 

c programs

Write a C Program to find the largest pair sum in an unsorted array.(hint: find 2 maximum elements from array and then find the sum of both numbers.)




#include <stdio.h>

void findTwoMaxElements(int arr[], int size, int* max1, int* max2) {
    *max1 = *max2 = arr[0];

    for (int i = 1; i < size; i++) {
        if (arr[i] > *max1) {
            *max2 = *max1;
            *max1 = arr[i];
        } else if (arr[i] > *max2) {
            *max2 = arr[i];
        }
    }
}

int main() {
    int array[100];
    int n, max1, max2;

    printf("Enter the size of the array: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &array[i]);
    }

    if (n < 2) {
        printf("At least two elements are required in the array.\n");
        return 1;
    }

    findTwoMaxElements(array, n, &max1, &max2);
    int largestPairSum = max1 + max2;

    printf("The largest pair sum in the array is: %d\n", largestPairSum);

    return 0;
}


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.