find two largest values for 10 numbers

following code is used to find the largest value for 10 number, using similar approach, find the find two largest values for 10 numbers. You may input each number only once..thanx ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

int main()
{
	int counter, number, largest;
	counter = 1;

	cout << "Enter a number: ";
	cin >> largest;

	while ( counter < 10 ) {
		cout << "Enter next number: ";
		cin >> number;

		if ( number > largest )
			largest = number;
		counter++;
	}

	cout << "The largest no. is : " << largest << endl;
	return 0;
}
What's your question?
I guess you need to modify your code in order to show the user not only the largest number, but also the "almost" largest... you could include an auxiliary vairiable, say second_largest and between lines 16 and 17 copy the "largest" into the "second_largest" before largest = number;
After pondering a lot, i got the solution.
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
// To find the two largest values of the 10 numbers.
#include <iostream>
using namespace std;

int main()
{
	int num1 = 0, num2 = 0, num, count = 1;

	while ( count <= 10 ) {
		cout << "Enter number: ";
		cin >> num;

		if ( num > num1 )
			num1 = num;

		if ( num1 > num2 ) {
			num = num2;
			num2 = num1;
			num1 = num;
		}
	
		count++;
	}

	cout << "Largest number is: " << num2 << endl;
	cout << "2nd largest numbre is: " << num1 << endl;
	return 0;
}
Great!!!
Analize also this code, it does the same in fewer steps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main()
{
	int largest = 0, secondLargest = 0, num, count = 1;

	while ( count <= 10 ) {
		cout << "Enter number: ";
		cin >> num;
		if (num > largest){
		secondLargest = largest;
		largest = num;
		}
		count++;
	}
	cout << "Largest number is: " << largest << endl;
	cout << "2nd largest numbre is: " << secondLargest << endl;
	return 0;
}


in 12th line, secondLargest takes former largest before largest takes a new vaule.
@Marcos, short and nice. worked. thnx.
Topic archived. No new replies allowed.