In: Computer Science
Question 3
A. Show the output of the following code.
#include <iostream>
using namespace std;
void magic (int &a, int b, int& c)
{
a *= 2;
b = b+2;
c = c-2;
}
int main ()
{
int x=1, y=3, z=7;
magic (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
magic (z, y, x);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
What is the parameter passing scheme for a, b and c in magic( ) function ?
B. Show the output of the following code.
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n=length-1; n>=0; n--)
cout << arg[n] << " ";
cout << endl;
}
int main ()
{
int firstarray[] = {3, 15, 10};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,2);
printarray (secondarray,3);
return 0;
}
Question 3 A):
#include <iostream>
using namespace std;
void magic (int &a, int b, int& c)
{
a *= 2;
b = b+2;
c = c-2;
}
int main ()
{
int x=1, y=3, z=7;
magic (x, y, z);
cout << "x=" << x << ", y=" << y <<
", z=" << z;
magic (z, y, x);
cout << "x=" << x << ", y=" << y <<
", z=" << z;
return 0;
}
Screesnhots:
Output:
The parameter passing mechanism is both call by value and call by reference too.
Since in magic() method x reference(address) and z reference(addess) is used, the function magic() for x and z is call by reference method.
Since in magic() method y is used directly (formal parameter) , the function magic() for y is call by value method.
Parameter scheme for x is call by reference.
Parameter scheme for y is call by value.
Parameter scheme for z is call by reference.
Quesiton 3 B):
#include <iostream>
using namespace std;
void printarray (int arg[], int length)
{
for (int n=length-1; n>=0; n--)
cout << arg[n] << " ";
cout << endl;
}
int main ()
{
int firstarray[] = {3, 15, 10};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,2);
printarray (secondarray,3);
return 0;
}
Screeshots:
Output: