Write a function in c ++ . please explain it step by step to better understand .
ID: 3548926 • Letter: W
Question
Write a function in c ++ . please explain it step by step to better understand . I DO NOT NEED THE WHOLE PROGRAM , I JUST NEED THE CORRECT CODE FOR THE FUNCTION IN C ++ . ONCE AGAIN JUST WRITE A FUNCTION . int * return_an_array(int n) which takes an integer n and returns a pointer to an array (allocated off of the heap in the function) containing the digits of n in the appropriate positions. If n = 0 return 0 (which is the Write a function in c ++ . please explain it step by step to better understand . I DO NOT NEED THE WHOLE PROGRAM , I JUST NEED THE CORRECT CODE FOR THE FUNCTION IN C ++ . ONCE AGAIN JUST WRITE A FUNCTION . int * return_an_array(int n) which takes an integer n and returns a pointer to an array (allocated off of the heap in the function) containing the digits of n in the appropriate positions. If n = 0 return 0 (which is theExplanation / Answer
int* return_an_array(int n)
{
//if n== 0 return NULL;
if(n==0) return NULL;
//first count no of digits in integer n;
int no_of_digits = 0;
// copy integer n to local variable local to count no of digits in n;
int local = n;
while(local)
{
no_of_digits++;
//now remove one digit by dividing with 10;
local/= 10;
}
// now allocate memory using heap;
int* array_with_digits = new int[no_of_digits];
// now start putting numbers into array;
for(int i=no_of_digits-1; i>=0; i--)
{
// modulus operator gives digit.
array_with_digits[i] = n%10;
// now since already last digits we have stored in array remove that digits by dividing with 10.
n = n/10;
}
// once we filled array return pointer to array.
return array_with_digits;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.