20_10

Write a C code to print the largest and the second largest element of an array.

Source code:

 //Write a C code to print the largest and the second largest element of an array.

#include <stdio.h>

int main() 

{

int j, array[5], largest, second;

for(j=0;j<5;++j)

{

printf("Enter the value for %d: ",j);

scanf("%d",&array[j]); 

}

int i;


   if(array[0] > array[1]) 

   {

      largest = array[0];

      second  = array[1];

   }

   else 

   {

      largest = array[1];

      second  = array[0];

   }


   for(i = 2; i < 5; ++i) 

   {

       if( largest < array[i] ) 

       {

          second = largest;

          largest = array[i];

       }

   else if( second < array[i] ) 

       {

          second =  array[i];

       }

    }

printf("Largest - %d, Second - %d", largest, second);   

return 0;

}

Output:

C code to print the largest and the second largest element of an array


No comments:

Post a Comment

Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...