Answer to Question #240815 in C++ for Imran

Question #240815
Write a function to sort data (in increasing order) in an array using
a. pass by value
b. and pass by reference.
1
Expert's answer
2021-09-22T23:48:29-0400
/*
 It should be noted that when passing an array to a function, 
the array decays into pointers.
That is, only the option of passing an array to a function by a pointer is possible
Passing an array by value and by reference can only be simulated
*/

#include <iostream>


// Simulate input by value
void sortArray1(double arr[10] , int size)
{  
    for (int i = 0; i < size - 1; ++i) 
    {
        int small = i;
        for (int j = i + 1; j < size; ++j)
        {
            if (arr[j] < arr[small])
                small = j;
        }
        double temp=arr[i];
        arr[i] = arr[small];
        arr[small] = temp;
    }
}


// Simulate input by reference
void sortArray2(double arr[], int size)
{
    for (int i = 0; i < size - 1; ++i)
    {
        int small = i;
        for (int j = i + 1; j < size; ++j)
        {
            if (arr[j] < arr[small])
                small = j;
        }
        double temp = arr[i];
        arr[i] = arr[small];
        arr[small] = temp;
    }
}
int main()
{
  // example 
    double arr1[10] ={ 1.2, 34, 3.7, 48.6, -5, 9, 14.87, 17,0.89,1 };
    sortArray1(arr1, 10);
// output in display
    for (int i = 0; i < 10; ++i)
        std::cout << arr1[i] << " ";
    std::cout << "\n";


    double arr2[10] = { 1.2, 34, 3.7, 48.6, -5, 9, 14.87, 17,0.89,1 };
    sortArray2(arr2, 10);
    // output in display
    for (int i = 0; i < 10; ++i)
        std::cout << arr2[i] << " ";
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS