Passing by Reference
All right, in this lesson we are going to start using a different method of utilizing values in variables.
So far we have been passing information by Value.
int num = 0;
The example of above is passing information by value. We simply put a number into a variable and then use it for whatever purposes we have designed for it.
In this lesson we have a new way of putting a value into a variable. It is called passing by Reference.
Watch the video for further explanation
So far we have been passing information by Value.
int num = 0;
The example of above is passing information by value. We simply put a number into a variable and then use it for whatever purposes we have designed for it.
In this lesson we have a new way of putting a value into a variable. It is called passing by Reference.
Watch the video for further explanation
Passing by reference Video
So Here is the assignment
We need a very specific function and we need it ASAP.
This is how we imagine it:
its name is "increment";
it returns void;
when invoked with one argument (an int variable),
it simply increments the variable by 1;
when invoked with two arguments (an int variable and int expression),
it increments the variable by the expression's value.
Sorry, we cannot show you the function's header – it would be too easy.
We'll only show you how we invoke the function – the rest is up to you.
Complete the code below.
Run your code and check whether your output is the same as ours.
This is how we imagine it:
its name is "increment";
it returns void;
when invoked with one argument (an int variable),
it simply increments the variable by 1;
when invoked with two arguments (an int variable and int expression),
it increments the variable by the expression's value.
Sorry, we cannot show you the function's header – it would be too easy.
We'll only show you how we invoke the function – the rest is up to you.
Complete the code below.
Run your code and check whether your output is the same as ours.
Sample code
#include
using namespace std;
// Insert your function here
int main(void)
{
int var = 0;
for(int i = 0; i < 10; i++)
if(i % 2) // increment by 1 on odd numbers
increment(var); // i=1 var=1, i=3 var=4, i=5 var=9, i=7 var=16, i=9 var=25
else // increment by i on even numbers
increment(var,i); // i=0 var=0, i=2 var=3, i=4 var=8, i=6 var=15, i=8 var=24
cout << var << endl;
return 0;
}
using namespace std;
// Insert your function here
int main(void)
{
int var = 0;
for(int i = 0; i < 10; i++)
if(i % 2) // increment by 1 on odd numbers
increment(var); // i=1 var=1, i=3 var=4, i=5 var=9, i=7 var=16, i=9 var=25
else // increment by i on even numbers
increment(var,i); // i=0 var=0, i=2 var=3, i=4 var=8, i=6 var=15, i=8 var=24
cout << var << endl;
return 0;
}
Sample Output
25