204k views
3 votes
Define a function named SwapValues that takes four integers as parameters and swaps the first with the second, and the third with the fourth values. Then write a main program that reads four integers from input and calls function SwapValues() to swap the input values. The main program then prints the swapped values on a single line separated with spaces and ending with a newline.

The program must define and call the following function:
void SwapValues(int& userVal1, int& userVal2, int& userVal3, int& userVal4)

User Hofit
by
8.7k points

1 Answer

2 votes

Final answer:

A program defining the functions:

void SwapValues(int& userVal1, int& userVal2, int& userVal3, int& userVal4) {
int temp;
temp = userVal1;
userVal1 = userVal2;
userVal2 = temp;
temp = userVal3;
userVal3 = userVal4;
userVal4 = temp;
}

The main program:

#include
using namespace std;

int main() {
int userVal1, userVal2, userVal3, userVal4;
cin >> userVal1 >> userVal2 >> userVal3 >> userVal4;
SwapValues(userVal1, userVal2, userVal3, userVal4);
cout << userVal1 << " " << userVal2 << " " << userVal3 << " " << userVal4 << endl;
return 0;
}

Step-by-step explanation:

To define a function SwapValues that swaps the first integer with the second, and the third with the fourth, you can use reference parameters in C++ to alter the values directly.

Here is the code:

void SwapValues(int& userVal1, int& userVal2, int& userVal3, int& userVal4) {
int temp;
temp = userVal1;
userVal1 = userVal2;
userVal2 = temp;
temp = userVal3;
userVal3 = userVal4;
userVal4 = temp;
}

In the main program, you would read four integers, call SwapValues() to swap them, and then print the swapped values:

#include
using namespace std;

int main() {
int userVal1, userVal2, userVal3, userVal4;
cin >> userVal1 >> userVal2 >> userVal3 >> userVal4;
SwapValues(userVal1, userVal2, userVal3, userVal4);
cout << userVal1 << " " << userVal2 << " " << userVal3 << " " << userVal4 << endl;
return 0;
}

This code would effectively swap the input values as requested and output the results.

User Ymg
by
8.2k points