Answer to Question #164746 in C++ for chetana

Question #164746

Write functions to swap the contents of two variables where the variables are passed in the function: a) by value; b) by reference, and c) using pointers.


1
Expert's answer
2021-02-18T14:37:44-0500

a) by value

#include <iostream>
using namespace std;
// function definition to swap numbers
void swap(int number1, int number2) {
    int temp;
    temp = number1;
    number1 = number2;
    number2 = temp;
    cout << "a = " << number1 << endl;
    cout << "b = " << number2 << endl;
}
int main() {
    // initialize variables
    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    // call function by passing by values
    cout << "\nAfter swapping" << endl;
    swap(a, b);
    return 0;
}

 

b) by reference

#include <iostream>
using namespace std;
// function definition to swap values
void swap(int &num1, int &num2) {
    int temp;
    temp = num1;
    num1 = num2;
    num2 = temp;
}
int main() {
    // initialize variables
    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    // call function to swap numbers
    swap(a, b);
    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    return 0;
}


c) using pointers

#include <iostream>
using namespace std;
// function definition to swap numbers
void swap(int* number1, int* number2) {
    int temp;
    temp = *number1;
    *number1 = *number2;
    *number2 = temp;
}
int main() {
    // initialize variables
    int a = 1, b = 2;
    cout << "Before swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    // call function by passing variable addresses
    swap(&a, &b);
    cout << "\nAfter swapping" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    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