This is how you do it …
Notice that there must be atleast 2 numbers to decide second_largest.
Step 1. input 2 numbers . let one be largest , other be second_largest. Rest of numbers we will input in a while loop.
Step 2.It might be possible that the first 2 numbers be 3, 5 . in such a case second_largest becomes greater than largest . hence if such a condition arise , swap their values. The code till here is :
int main()
{
int largest,second_largest ,num;
scanf("%d",&largest);
scanf("%d",&second_largest);
if(largest<second_largest)
{
//i am swapping values "if" such condition arise , "num" is just a temporary variable
num=largest;
largest=second_largest;
second_largest=num;
}
while(1)
{
//some logic that i will explain later
}
printf("%d\n",second_largest);
return 0;
}
Step 3: Now i will input all values in while loop. All values i input save in “num” variable.As soon as i encounter -1 , i break from loop and present answer.
Step 4:I am taking a loop that will always run infinitely . hence i take “while(1)”. such a loop always run till infinity. now inside , i scanf and input value in “num” variable . if value is -1 , i break from loop. Else , i check if value is greater than largest. if so second_largest becomes largest and largest becomes num. Ex : suppose , largest was 5 and second largest was 4 . i input another value say ,6 . now among 5,4,6 , largest =6 and second_largest =5 (and not 4).Update your second largest also.
Step 5: In case our num is between largest and second_largest , then only our second largest = num. Largest remains unchanged.I have used else if in the code to achieve this. else if is reached only when the above if statement fails. that means largest<= num < second_largest .
Here’s the full code :
int main()
{
int largest,second_largest ,num;
scanf("%d",&largest);
scanf("%d",&second_largest);
if(largest<second_largest)
{
num=largest;
largest=second_largest;
second_largest=num;
}
while(1)
{
scanf("%d",&num);
if(num==-1)
break;
if(num>largest)
{
second_largest=largest;
largest=num;
}
else if(num>second_largest)
second_largest=num;
}
printf("%d\n",second_largest);
return 0;
}