Sunday, February 25, 2018

C program: Find the second largest number in the input. Without using arrays.

You 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.  

#include<stdio.h>

int main(){
int largest=0,firstInput=0,secondInput=0,secondLargest=0;
scanf("%d",&firstInput);
if(firstInput != (-1))
 {
   
    scanf("%d",&secondInput);
    while(secondInput !=(-1))
    { 
        if(secondInput>firstInput)
        {
        largest=secondInput;
        secondLargest=firstInput;
        firstInput=largest;
        }
        else
        {  
          if(secondInput>secondLargest)
          secondLargest=secondInput;
        }

        scanf("%d", &secondInput);
    }


}
printf("%d",secondLargest);
  return 0;
}

Thanks
Happy computing !

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows