简体   繁体   中英

while Construct to Sort ints [C++]

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);
    }

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM