简体   繁体   中英

How could I create a c++ function isOdd that accepts an integer array and its size and returns true is all of the array elements are odd

if ( n % 2 == 0)
    cout << n << " is even.";
  else
    cout << n << " is odd.";

I know how to check if the numbers are odd, but unsure of how to write the rest of the code.

bool isOdd(int int_arr[], int arr_size)
{
    bool is_all_odd = true;
    for(int i = 0; i < arr_size; i++)
    {
        if(int_arr[i] % 2 == 0)
            {
                is_all_odd = false;
                break;
            }
    }
    
    return is_all_odd;
}

You'll want to take in the array like you mentioned, the size, and traverse through it. In this case we just assume all is odd, and check for an even, if we find an even number we change the return value, stop traversing and return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM