Friday, 5 September 2014

Second Largest Element In C Without Arrays

Finding the Second Largest Element without using arrays

We are given a sequence of integers as input, terminated by a -1. (That is, the input integers may be positive, negative or 0. A -1 in the input signals the end of the input.)

-1 is not considered as part of the input. 

Find the second largest number in the input. You may not use arrays.

C code as follows:

#include <stdio.h>

int main()
 {  int l,sl,a,b,c; /*a,b first two input numbers to initialise largest (l),second lar(sl) numbers;

    scanf("%d",&a);
    l=a;
    if (a!=-1) 
     {
       scanf("%d",&b);
       if (b>l){sl=l;l=b;}
       else {sl=b;}
      }
    else return 0;  
    scanf("%d",&c);
    while(c!=-1)
     { 
       if ((c<l)&& (c>sl))
           sl=c;
       if (c>l)
        {sl=l;
         l=c;}
      scanf("%d",&c);
      }
printf("%d",sl);
return 0;

}

No comments:

Post a Comment