Page

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

#include<stdio.h>
#include<conio.h>
#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
100
30
80
68
Input interger are
100  30   80   68

100 is the first largest
80 is the second largest

Average of 100 and 80 = 90

No comments:

Post a Comment