163k views
2 votes
How can i write void function that takes three arguments by reference. Your function should modify the values in the arguments so that the first argument contains the largest value, the second the second-largest, and the third the smallest value?​

User Clad Clad
by
6.6k points

1 Answer

6 votes

Answer:

void sort_three_numbers(int& num1, int& num2, int& num3) {

if (num1 < num2) {

std::swap(num1, num2);

}

if (num2 < num3) {

std::swap(num2, num3);

}

if (num1 < num2) {

std::swap(num1, num2);

}

}

Step-by-step explanation:

In this implementation, we first compare num1 and num2, and swap them if num1 is smaller than num2. Then we compare num2 and num3, and swap them if num2 is smaller than num3. Finally, we compare num1 and num2 again, and swap them if num1 is smaller than num2. After these comparisons and swaps, the values of the arguments will be modified so that num1 contains the largest value, num2 contains the second-largest value, and num3 contains the smallest value.

To use this function, you can call it with three integer variables:

int num1 = 10;

int num2 = 5;

int num3 = 3;

sort_three_numbers(num1, num2, num3);

std::cout << num1 << " " << num2 << " " << num3 << std::endl; // prints "10 5 3"

User Mohsen Haddadi
by
7.1k points