Here is code.I don't know what problem is.When i enter the values,the for loop is not working. I am working on a problem ask me to: find the two largest values among several integers.Assume that the first integer read specifies the number of values remaining to be entered.Thanks guys!
#include <iostream>
using namespace std;
int main()
{
int i, largest, secondLargest, temp;
cout << "Enter the number of integers to be processed followed by the integers:";
cin >> i;
cin >> largest;
cin >> secondLargest;
if (secondLargest > largest)
{
temp = secondLargest;
secondLargest = largest;
largest = temp;
}
for (int b; i > 1; i--)
{
cin >> b;
if (b > largest)
{
secondLargest = largest;
largest = b;
}
}
cout << "Largest is " << largest << endl << "Second largest is " << secondLargest << endl;
system("pause");
}
The program and the loop works. At least nearly.
The only problem is, that the loop body gets executed (i-1)
times instead of (i-2)
times.
To fix this, you can change i > 1
to i > 2
.
edit:
Oh, and you additionally have to check, if b
is between largest
and second_largest
. In that case you have the replace second_largest
with b
.