Q7. Get odd numbers from array

Get all odd numbers from an int array

Unlike in Java we cannot return an array from a C++ function however we can return a pointer to an array. Read the comments carefully which I have put to explain the more difficult parts of this program

/* GetOddsAsArray.cpp */
 
#include <iostream>
using namespace std;
 
//function prototype declarations
int* getOddsAsArray(int arr[], int arrsize); 
void printArray(int arr[], int arrsize);
 
int oddArrSize = 0; //global variable - accessible from all functions
 
int main() {    
    int arr[] = {1,2,3,4,5,6,7}; //the input array
 
    //declare an int pointer that will hold the address of the first location
    //of the element in our odds array
    int* oddsArrayPtr = getOddsAsArray(arr, 7);
 
    cout << "array is ";
    printArray(arr, 7);
 
    cout << "oddArrSize=" << oddArrSize << endl;
 
    cout << "odds array is "; 
    printArray(oddsArrayPtr, oddArrSize); //notice that we are passing a pointer
 
    cin.get();
    return 0;
}
 
//unlike Java we cannot return arrays in C++ so we have to use pointers and
//return a pointer that points to the location of the first element in the array
int* getOddsAsArray(int arr[], int arrsize) { 
    //first count the number of odds in the array arr
    int oddCount = 0;
    for(int i = 0; i < arrsize; i++)
        if( arr[i] % 2 != 0)
            oddCount++;
 
    //now create a pointer to the array of  odd numbers using the oddCount
    //since we cannot return an array of integers in C++ like in Java
    int* oddsArrayPtr = new int[oddCount];
 
    //iterate over the arr array again and copy the odd numbers to array at 
    //the location of pointer oddsArrayPtr
    int nextIndex = 0; //keeps track of the next position in oddsArray 
    for (int i = 0; i < arrsize; i++) {
        if (arr[i] % 2 != 0) {
            //copy the odd number into the odds array at the nextIndex position
            //notice that we use the position of the pointer to point to copy to 
            //the next element in the array
            oddsArrayPtr[nextIndex] = arr[i];
            //increment nextIndex where the next odd from arr will be copied
            nextIndex++;
        }
    }
    //set the size of the odd array
    oddArrSize = oddCount;
 
    //return the oddsArrayPtr;    
    return oddsArrayPtr;     
}
 
/* print all the elements in an array */
void printArray(int arr[], int arrsize) {
     int arrIdx = 0;
     cout << "[";
     while (arrIdx < arrsize) { //example of iterating an array using while loop
 
        if( arrIdx != (arrsize - 1) )
          cout << arr[arrIdx] << ",";
        else
          cout << arr[arrIdx];
 
        arrIdx++;
     }
     cout << "]" << endl;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License