Two or more solutions:
//Solution 1: call-by-reference function parameter using
// ampersand sign &
void swap_values(int& variable1, int& variable2)
{
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
//Solution 2: call-by-reference function parameter using
// asterisk sign * or pointer syntax
void swap_values_asterisk(int *variable1, int *variable2)
{
int temp;
temp = *variable1;
*variable1 = *variable2;
*variable2 = temp;
}
//Solution 3: call-by-reference function parameter using
// a standard library function, put inside driver
void swap_values_stdLibraryFunction(int& variable1, int& variable2)
{
swap(variable1, variable2); //put inside driver
}
//Solution 4: call-by-reference function parameter using array syntax
void swap_values_array(int array1[], int array2[])
{
int temp;
temp = array1[0];
array1[0] = array2[0];
array2[0] = temp;
}
Driver:
int a, b;
a=1;
b=2;
swap_values(a, b);
cout << "a: " << a << ", b: " << b << endl;
a=1;
b=2;
swap_values_asterisk(&a, &b);
cout << "a: " << a << ", b: " << b << endl;
a=1;
b=2;
swap_values_stdLibraryFunction(a, b);
cout << "a: " << a << ", b: " << b << endl;
int array_a[10];
int array_b[10];
array_a[0] = 1;
array_b[0] = 2;
swap_values_array(array_a, array_b);
cout << "a: " << array_a[0] << ", b: " << array_b[0] << endl;
Program output:
a: 2, b: 1
a: 2, b: 1
a: 2, b: 1
a: 2, b: 1
Reading. Practice. Writing.
Please feel free to comment. Suggestions are also welcomed here. Write something "wholesome serving purpose" here.
Subscribe to:
Post Comments (Atom)
Measure execution time with Julia, example using sorting algorithms
# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...
-
Open LibreOffice Draw program. Select the rectangle shape from shape toolbar at the bottom of drawing page. Click a point and drag-and-re...
-
DiGi Super Long Life is a feature where you can extend your talktime validity to 1 year for just RM38. Indirectly, the subscription fee is ...
-
DiGi Super Long Life is a feature where you can extend your talktime validity to 1 year for just RM30. Indirectly, the subscription fee is...
No comments:
Post a Comment