Let\'s consider the following function: void do It (int& a, int b) {a = a + 5; b
ID: 3801217 • Letter: L
Question
Let's consider the following function: void do It (int& a, int b) {a = a + 5; b = b + 5} void doIt2(int a, int& b) {a = a + 5; b = b + 5} void doIt3(int& a, int& b) {a = a + 5; b = b + 5} Write a main program that prompts the user for two integer numbers (numl and num2). Then, the main program calls the functions dolt, dolt l, and dolt2 with num l and num2 as parameters. The main program will finally print the content of num 1 and num2 on the screen in the main function, after each function is called. Explain what is the difference between a and b results, for both casesExplanation / Answer
This program explains the difference between call by value and call by refence of passing parameters to method.
call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
doIt function :
'a' is call by reference parameter but not 'b' (see the & sign before the varibale name). So changes happened to 'a' inside the function affected the passed argument and it got incremented by 5.
doIt2 function:
b is a call by reference parameter. So Inside changes affected the passed argument and it got incremented by 5.
doit3 function:
both 'a' and 'b' were passed as call by reference parameters. hence both the variables got incremented by 5.
#include <iostream>
using namespace std;
void doIt(int&a, int b)
{
a = a + 5;
b = b + 5;
}
void doIt2(int a, int& b)
{
a = a + 5;
b = b + 5;
}
void doIt3(int&a, int& b)
{
a = a + 5;
b = b + 5;
}
int main()
{
int a,b;
cout << "Please Enter num1" << endl;
cin >> a;
cout << "Please Enter num2" << endl;
cin >>b;
cout << "Given input (num1,num2): (" << a << " ," << b << ")" <<endl;
doIt(a,b);
cout << "After invoking doIt function, The values are (num1, num2): (" << a << " ," << b << ")" <<endl;
doIt2(a,b);
cout << "After invoking doIt2 function, The values are (num1, num2): (" << a << " ," << b << ")" <<endl;
doIt3(a,b);
cout << "After invoking doIt3 function, The values are (num1, num2): (" << a << " ," << b << ")" <<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.