1. Array In C

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

Method 1

Assuming the first element of the array to be the largest and second element to be the next largest value and then swapping with the next element if the next is larger

#include <stdio.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 integer 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("\n Average of %d and %d = %d \n", largest1, largest2,
 
    (largest1 + largest2) / 2);
 
}

Output

Enter 4 integer numbers
80
23
79
58
Input interer are
80   23   79   58
  
80 is the first largest
79 is the second largest
  
Average of 80 and 79 = 79
Comments to: C Program to Find the Largest Two Numbers in a given Array

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

Login

Welcome to WikiCoders

Join the site and store the save posts for later, share your own articles
Join WikiCoder
Registration is closed.