20.2k views
2 votes
(1) Precursor to Array ...a Sorting Program: Write a modular program with a function named sort that takes three integer parameters by reference. The function should rearrange the parameter values so that the first parameter gets set to the largest value, the second parameter gets set to the second largest value, and the third parameter gets set to the smallest value. For example, let's say in the main function we are given the variable assignments num1 = 20; num2 = 10; num3 = 30; then the function call sort(num1,num2,num3) should result in the following changes to the variables in the main function: num1 = 30, num2 = 20, and num3 = 10. Note that although the array construct covered in Chapter 7-8 supports a way to solve this type of problem for an arbitrary number of items instead of only for three items, DO NOT use an array for this programming challenge.

User Arpit Vyas
by
5.6k points

1 Answer

2 votes

Here is code in C++.

#include <bits/stdc++.h>

// include header

using namespace std;

// function to rearrangement the numbers

void Sort(int& i, int& j, int& k)

// values are passed by reference

{

// first parameter gets largest value

if(i<j){

// swap the value of i & j

int tmp = i;

i = j;

j = tmp;

}

//second parameter gets second largest value

if(i<k){

// swap the value of i & k

int tmp = i;

i=k;

k = tmp;

}

//third parameter gets smallest value

if(j<k){

// swap the value of k & j

int tmp = j;

j=k;

k=tmp;

}

}

// driver function

int main() {

cout << "Enter three integers: " << endl;

// declaring 3 variables

int num1,num2,num3;

// reading the input

cin >> num1 >> num2 >> num3;

// calling the function

Sort(num1,num2,num3);

// printing the numbers after rearrangement

std::cout<<"Numbers after rearrangement: \\"<< num1 << " " << num2 << " " << num3 << std::endl;

// main ends here

return 0;

}

Step-by-step explanation:

First reading three integer in three different variables namely "num1","num2" and "num3".Pass these variable by reference in the function "sort()". There after comparing value of these three, largest value is assigned to num1, second largest value assigned to num2 and smallest value assigned to num3. Then it will print these value.

Output:

Enter three integers:

20 10 30

Numbers after rearrangement:

30 20 10

User Brandon McClure
by
5.2k points