Friday, 10 November 2017

C Program to Find the Largest Two Numbers in a given Array


Code:

#include
#define MAX 4

void main()
{
    int array[MAX], i, largest1, largest2, temp;

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

    printf("Input interger are \n");
    for (i = 0; i < MAX; i++)
    {
      printf("%5d", array[i]);
    }
    printf("\n");
    /*  assume first element of array is the first larges t*/
    largest1 = array[0];
    /*  assume first element of array is the second largest */
    largest2 = array[1];
    if (largest1 < largest2)
    {
        temp = largest1;
        largest1 = largest2;
        largest2 = temp;
    }
    for (i = 2; i < 4; i++)
    {
        if (array[i] >= largest1)
        {
            largest2 = largest1;
            largest1 = array[i];
        }
        else if (array[i] > largest2)
        {
            largest2 = array[i];
        }
    }
    printf("n%d is the first largest \n", largest1);
    printf("%d is the second largest \n", largest2);
    printf("nAverage of %d and %d = %d \n", largest1, largest2,
(largest1 + largest2) / 2);
}

Output:

Enter 4 integer numbers
80
23
79
58
Input interger are
80   23   79   58

80 is the first largest
79 is the second largest

Average of 80 and 79 = 79


More C Programs:












100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...