WAP to find the largest and second largest element in an array.

Here is your code in C -



#include <stdio.h>


int main() {

    int a[6], i, l1, l2;
    
    printf ("Enter the elements of array: ");
    
    for (i=0; i<6; i++) {
        scanf("%d", &a[i]);
    }
    
    l1 = a[0];
    
    l2= a[0];
    
    for (i=0; i<6; i++) {
        
        if (l1<a[i]){
            l2 = l1;
            l1 = a[i];
        }
        
        if (l2<a[i] && a[i]!=l1)
            l2 = a[i];
    }
    
    printf("First largest number is %d\nSecond largest number is %d", l1, l2);
    
    return 0;

Output - 


Explanation : -

1. Input the elements in the array (i.e. a[i]).

2. Intialize L1 and L2 as the element present on the index no. zero of elements.

3.  for (i=0; i<6; i++) {
        
        if (l1<a[i]){
            l2 = l1;
            l1 = a[i];
        }
        
        if (l2<a[i] && a[i]!=l1)
            l2 = a[i];
    }

In this loop it will check for if l1 < any element in array then make that element equals to array and make l1 = l2 then after this l1 and l2 will have the largest no. present in array stored in it.

In 2nd if statement it will check l2 < any element in array and that element is not equal to the elements present in l1 then it will be stored in l2.

After these step l1 will have largest no. stored in it and l2 have 2nd largest no. stored in it.

4. Print l1 and l2.

Comments

Popular posts from this blog

WAP to add or to multiply two matrices of order nXn.

WAP that inputs two arrays and saves sum of corresponding elements of these arrays in a third array

WAP to find the minimum and maximum element of the array by using functions.