Question: Problem 1 Pass by Reference-to-Pointer - Find the odd and even elements in an integer array Overview: find the odd and even elements in an
Problem 1
Pass by Reference-to-Pointer - Find the odd and even elements in an integer array
Overview: find the odd and even elements in an integer array, and store them in two separate integer arrays passed to the function by reference-to-pointer. We will call this function findOddAndEvenNumbers. This function will iterate over an input array to:
- Find the number of odd elements and even elements in the array.
- Allocate the required amount of memory to the odd and even arrays respectively.
- Copy the odd numbers into the odd array
- Copy the even numbers into the even array.
In case the input array has no even/odd numbers, we will not allocate any memory to the even/odd array, and its pointer will point to nullptr.
Specifications:
1. a function called findOddAndEvenNumbers.
i. INPUT PARAMETERS: It should take six arguments -
- numbers is an input array of type int which holds a list of numbers. A pointer to the array is passed to your function.
- length is the length of the numbers array.
ii. OUTPUT PARAMETERS: The findOddAndEvenNumbers should not return anything.
a.odd is an array pointer for an array of type int. A reference to this pointer is passed to the function. odd must be updated to point to an array of size equal to the number of odd numbers, and must hold all the odd numbers from the numbers array.
b.even is an array pointer for an array of type int. A reference to this pointer is passed to the function. even must be updated to point to an array of size equal to the number of even numbers, and must hold all the even numbers from the numbers array.
c.numOdd must be updated to the number of odd numbers in the numbers array.
d.numEven must be updated to the number of even numbers in the numbers array.
2. a complete program to do the following :
i.Use the function prototype provided below:
void findOddAndEvenNumbers(int* numbers, int*& odd, int*& even, int length, int& numOdd, int& numEven);
Note
Notice we don't return anything, and instead, we use the parameters passed by reference, to update its contents. In C++, we can use parameters passed by reference whenever we want a function to return multiple variables. Here, passing parameters as a reference to a pointer is very important as without it, any updates to the pointers themselves inside the function will not persist inside the main function.
The test wii be :
int numbers[] = { 1 , 4, 3 ,7, 13 ,12 ,41, 33, 2};
int length = 9;
What I expect:
Number(size = 9 ) : [1 4 3 7 13 12 41 33 2]
Odd numbers ( size = 6 ): [ 1 3 7 13 41 33 ]
Even numbers (size = 3 ) : [4 12 2]
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
