Problem with descending order code?

I have been having trouble with pass by value, and that is what this assignment is aimed toward. After the code executes, 4 numbers print out, followed by a long string of numbers i am not expecting. I want the code to print the list of numbers input into descending order. Any help or hints would be appreciated. Thank you.
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
29
30
31
32
33
#include <iostream>
using namespace std;
int descending_order(int num[5]);
int main()
{
    int num[5];
    num[5]=descending_order(num);
    for(int cnt3=0; cnt3<5; cnt3++)
        cout<<num[cnt3]<<endl;
    system("pause");
    return 0;
}
int descending_order(int num[5])
{
    int temp, flag=1;
    cout<<"Please enter 5 numbers"<<endl;
    cin>>num[1]>>num[2]>>num[3]>>num[4]>>num[5];
    for(int cnt2=0; (cnt2<5)&&(flag==1); cnt2++)
    {
        flag=0;
        for(int cnt=0; cnt<4; cnt++)
        {
            if(num[cnt]>num[cnt+1])
            {
                temp=num[cnt];
                num[cnt]=num[cnt+1];
                num[cnt+1]=temp;
                flag=1;
            }
        }
    }
}
the first thing that jumps out at me is that an array created with a length of 5 should have its contents accessed with 0 through 4

Also I see descending order is supposed to return an integer, but return is never used.

Here's one 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
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
    int c = *a;
    *a = *b;
    *b = c;
}
void bubbleSort(int *first, int *last)
{
    for (int *i = first; i != last; ++i)
        for (int *j = first; j < i; ++j)
            if (*i > *j)
                swap(i, j);
}
int main() {
    int nums[5];
    cout << "Enter 5 integers:\n";
    for (int *p = nums; p != nums + 5; ++p)
        cin >> *p;
    cout << endl;
    bubbleSort(nums, nums + 5);
    for (int *p = nums; p != nums + 5; ++p)
        cout << *p << endl;
    return 0;
}
Last edited on
You can use STL algorithms to sort easily
http://www.cplusplus.com/reference/algorithm/sort.html
Topic archived. No new replies allowed.