1

I'm really confused on the theory behind this. Not sure how to return the array from my isAscending function so i can print out in the main.

#include <iostream>
#include <string>

using namespace std;

// Implement printArray here
void printArray(int array[], int n){
    for (int i = 0; i < n; ++i )
        cout << array[i] << endl;
};

// Implement isAscending here

int isAscending(int array[], int n){


    for(int i = 0; i <= n; ++i){
        for(int j = 0; j <= n; ++j){
            if(array[i] > array[j+1]){
                int temp = array[j+1];
                array[j+1] = array[j];
                array[j] = temp;

            }
        }
    }



    return printArray(array, n);


};

// DO NOT CHANGE MAIN FUNCTION BELOW
int main() {
    int myarray[100];
    cout << "Enter number of integers : ";
    int n;
    cin >> n;
    cout << "Enter " << n << " integers" << endl;
    for (int i = 0; i < n; i++)
       cin >> myarray[i];
    cout << "Contents of array : ";

    printArray(myarray, n);

    cout << "Output of isAscending: " << isAscending(myarray, n) <<    endl;
}

Should I use pointers to pass the elements in the array i am stuck.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

1 Answers1

5

The short answer is you don't. When you pass an array to a function, you're actually just passing a pointer to the first element (the array decays to a pointer when you pass it as an argument). This means that if you modify the array in the function, you're modifying the original array and not a copy. Therefore, your isAscending() function will bubble sort the array you called it on and it does not need to return anything.

Just a side note, it seems like the assignment simply wants you to check if an array is ascending, instead of sorting it. In that case, isAscending() should return a bool.

If you need a function to return an array, you can't just pass a pointer to the first element since the array goes out of scope as soon as the function returns. You could dynamically allocate the array, but that just creates a bunch of new problems. Another way might be to return the pointer to the first element of the array passed to it as an argument like this, but there isn't much point in doing that since the caller already has access to the array.

The best way would be to use something like std::array or std::vector, which you can return by value just like any other variable. I would also recommend getting a good book.

(I provided this answer besides flagging as a duplicate since I thought the answer of the duplicate question was not complete enough and might mislead someone into trying to return a pointer to a local array)

eesiraed
  • 4,626
  • 4
  • 16
  • 34