C++ program to read n numbers and print the second largest number

Is this correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  #include <iostream>
using namespace std;
main( )
{
int n, c;
float v, l = 0.0, s = 0.0;

cout << "SECOND LARGEST NUMBER of n values\n\n";
cout << "Number of values to input: ";
cin >> n;
cout << "\nEnter values...\n";
c = 1;

while( c <= n )
{
cout << "Value " << c << ": ";
cin >> v;
if( c==1 )
l = s = v;

if( v > l )
{
s = l;
l = v;
}
else if( v > s || l == s )
s = v;
c = c + 1;
}
cout << "\nSecond largest value " << s << endl;

return 0;
}
Is this correct?

Dunno, your program is too difficult to read I do not even bother reading.
It is bad, even though your program may be correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

int main()
{
	int i, N;
	double val, largest = -10000000, second_largest = -10000000;

	cout << "SECOND LARGEST NUMBER of n values\n\n";

	do
	{
		cout << "Number of values to input: ";
		cin >> N;

		if(N <= 2)
		{
			cout << "The number of values must be 2 or higher! Please try again\n\n";
		}
	}
	while(N <= 2);

	i = -1;
	while(++i < N)
	{
		cout << "\nEnter values...\n";	
		cin >> val;

		if(val > largest) 
		{
			second_largest = largest; largest = val;
		}
		else if(val > second_largest) 
		{
			second_largest = val;
		}
	}

	cout << endl;
	cout << "The largest value " << largest << endl;
	cout << "The second largest value " << second_largest << endl;

	return 0;
}
I would use a for loop for this as we know how many times we would need to carry out the operation.

1
2
3
4
5
6
7
8
9
10
11
12
13
	
for (int i = 0; i < n; i++) {
	cout << "Enter number " << i + 1 << ": ";
	cin >> temp;

	if (temp > first) {
		second = first;
		first = temp;
	}
	else if (temp > second) {
		second = temp;
	}
}


Apart from that SakurasouBusters answer is on the money.

Also you could use the int limits like this
1
2
int first = numeric_limits<int>::min();
int second = numeric_limits<int>::min();
Last edited on
1. Read 'n' numbers: while (std::cin >> n) [CTRL-Z] to stop reading
2. store the input in a std::vector container.
3. Use the std::sort function to sort the values in numeric order #include<algorithm>
4. grab the 2nd to last element, or sort in reverse order and get the 2nd element.

Topic archived. No new replies allowed.