Click here to Skip to main content
15,906,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

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

What I have tried:

int main()
	int prev,curr; /* prev means previous number and curr means current number */
	int lar=0,seclar=0; /* lar means largest number and seclar means second largest number */
	printf("Enter the number:\t");
	if( !(prev == -1))
		while( !(curr == -1))
			if(prev< curr)
				seclar = prev;
			    if(seclar < curr)
				seclar = prev;
			prev = curr;
			scanf("%d", &curr);
 return 0;
Updated 6-Aug-17 3:58am
Kornfeld Eliyahu Peter 6-Aug-17 9:16am    
I will, if you can tell me what's wrong with your solution...
Patrice T 6-Aug-17 9:41am    
What is the problem ?

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
Share this answer
Have two "max" values max and secondMax. Set both to the largest negative number you can fit in an integer. Inside your loop, check each input value against max - it it's bigger, set secondMax to max, then set max to the new value.
If it isn't, check it against secondMax - itf it's bigger, set secondMax to the new value.
After the loop, secondMax has the value you want.

But this is your homework, so I'll give you no code!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900