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 ..
 ``1234567891011121314151617181920212223`` ``````#include 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; }``````
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.
 ``12345678910111213141516171819202122232425262728`` ``````// To find the two largest values of the 10 numbers. #include 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.

 ``1234567891011121314151617181920`` ``````#include 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.