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.
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;
}
Comments
Leave a comment