In: Computer Science
Write a function that removes all even numbers from an array. The function should take the array, length of the array, and a pointer for number of odd numbers found as arguments and return a pointer to the new array. If there are no odd numbers found in the array, your code should print "No odds found." and return NULL.
Use the function header:
int *removeEvens(int *a, int length, int *oddsFound);
Example:
Input array a[ ] = {3, 4, 5, 6, 7}
*oddsFound = 3
return array = {3, 5, 7}
The size of the return array needs to be the number of odd numbers found.
Note: You can determine if a number is even by checking if a[x] % 2 == 0.
C++ Program:
#include <iostream>
using namespace std;
//Function that removes even numbers from array
int *removeEvens(int *a, int length, int *oddsFound)
{
int i, k=0;
int *oddNumbers;
//Initializing oddsFound to 0
*oddsFound = 0;
//Counting number of odd
numbers
for(i=0; i<length; i++)
{
//Evaluating for odd
number
if(a[i] % 2 != 0)
//Incrementing count
*oddsFound += 1;
}
//If there are no odd numbers
if(oddNumbers == 0)
{
//Printing error message
and returns NULL
cout << "\n\n No
odds found. \n\n";
return NULL;
}
else
{
//Allocating space to
array
oddNumbers = new
int[*oddsFound];
//Storing odd
numbers
for(i=0; i<length;
i++)
{
//Searching for odd number
if(a[i] % 2 != 0)
{
//Adding to array
oddNumbers[k] = a[i];
k++;
}
}
//Returns odd
numbers array
return oddNumbers;
}
}
//Main function
int main()
{
//Array
int a[] = {3, 4, 5, 6, 7};
int oddsFound;
int *oddNumbers;
int i;
//Calling function
oddNumbers = removeEvens(a, 5,
&oddsFound);
cout << "\n\n Odd numbers: ";
//Printing odd numbers
for(i=0; i<oddsFound; i++)
{
cout << " "
<< oddNumbers[i];
}
cout << "\n\n";
return 0;
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output: