Task 3 - Understanding reference types. [3 pointsl The code below shows the numb
ID: 3751933 • Letter: T
Question
Task 3 - Understanding reference types. [3 pointsl The code below shows the numberofDigits function, which returns the number of digits of a given number (data type long). For example, the number 890786786690656798 has 18 number of digits, the function numberofDigits will return the number 18. Every time the function is called, another copy of the parameter passed (long number) will be created. 2 #include 3 using namespace std; 5 int numberOfDigits (long number)f int digit-e while (number) number number / 10; digit+ti 10 return digit; 12 13 14 int main) 15 long x890786786698656798 coutExplanation / Answer
//1
#include<iostream>
using namespace std;
//1
//modifying code so that the number can be passed as a reference
int numberOfDigits(long *number)//receiving through pointer
//changes the actual number
{
int digit =0;
while(*number)
{
(*number) = (*number) /10;
digit++;
}
return digit;
}
int main()
{
long x = 890786786690656798;
cout<<numberOfDigits(&x);//passing by reference/// passing addresss of the variable
return 0;
}
//2
#include<iostream>
using namespace std;
//2
//modifying code so that the number can be passed as a reference
int numberOfDigits(long *number)//receiving through pointer
//preventing the changes to the actual number
{
int digit =0;
long n = *number;//saving a copy to new variable, to prevent changes to the actual number
while(n)
{
n = n /10;
digit++;
}
return digit;
}
int main()
{
long x = 890786786690656798;
cout<<numberOfDigits(&x);//passing by reference/// passing addresss of the variable
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.