Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Rewrite the following Function Using Pass by reference. #include using namespace

ID: 3686243 • Letter: R

Question

Rewrite the following Function Using Pass by reference.

#include using namespace std;

void swap(double *, double *);

int main () {

double firstNum = 20, secNum = 6;

swap(&firstNum, &secNum);

cout << "firstNum = " << firstNum << "secNum = " << secNum << endl;

return 0;

}

void swap(double *nm1, double *nm2)

{ double temp;

temp = *nm1; *nm1 = *nm2; *nm2 = temp; }

I tried this but its not working and I'm not sure why.

#include<iostream>
using namespace std;

void swap(double* a, double* b){
  
   double temp = a; a = b; b = temp;
  
}

int main(void){
   a = 3;
   b = 6;
   swap(a,b);
  
}

Explanation / Answer

#include<iostream>

using namespace std;

void swap(double &, double &); // pass by reference

int main () {

double firstNum = 20, secNum = 6;

swap(firstNum, secNum);

cout << "firstNum = " << firstNum << " secNum = " << secNum << endl;

return 0;

}

void swap(double &nm1, double &nm2)
{
   double temp;

   temp = nm1; nm1 = nm2; nm2 = temp;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote