Reputation: 11
can anyone tell me why this doesn't work? I'm trying to sort five ints using a while loop, but the output is only giving me the numbers I entered in the order I entered them. I'm very new to programming, and I really have no idea what I'm doing.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int n1, n2, n3, n4, n5, temp, i;
cout << "Enter five numbers to be sorted: " <<'\n';
cin >> n1 >> n2 >> n3 >> n4 >> n5;
while(i<4) {
i++;
if(n1>n2) {
temp = n1;
n1 = n2;
n2 = temp;
}
if(n2>n3) {
temp = n2;
n2 = n3;
n3 = temp;
}
if(n3>n4) {
temp = n3;
n3 = n4;
n4 = temp;
}
if(n4>n5) {
temp = n4;
n4 = n5;
n5 = temp;
}
}
cout << n1 << " " << n2 << " " << n3 << " " << n4 << " " << n5 << endl;
system("PAUSE");
return(0);
}
Upvotes: 1
Views: 55
Reputation: 141554
You never initialized i
so it causes undefined behaviour to test i<4
; probably this causes the loop to never be entered.
Change the loop to for (int i = 0; i < 4; ++i)
and take out the earlier definition of i
.
Of course, the sorting logic can be improved a lot by the use of containers instead of having five separate int variables!
Upvotes: 2