Reputation: 23
I need to write in C++ a complete boolean function that will take an integer array and it's maximum size as a parameter and return whether or not that array has any elements with a value of 0.
I'm not even sure where to start.
Thanks in advance.
Upvotes: 2
Views: 5242
Reputation: 3049
bool TestForZero(int* myArray, int maxSize)
{
for(int ii=0; ii<maxSize; ++ii)
if(myArray[ii] == 0)
return true;
return false;
}
Upvotes: 1
Reputation: 93410
bool foo(int* array, int size)
{
int i;
for (i = 0; i < size; i++)
{
if (array[i] == 0)
{
return true;
}
}
return false;
}
and to call it you would do something like:
int arr[] = { 1, 2, 3, 4, 0, 6};
foo(arr, 6);
Upvotes: 0
Reputation: 361522
Use std::find
#include <algorithm>
bool ContainsZero(int *arr, int size)
{
return std::find(arr, arr+size, 0) != (arr+size);
}
Upvotes: 3
Reputation: 1607
bool hasZeroes(int * array, int len) {
int zeroCount = 0;
for (int i = 0; i < len; i++) {
if (array[i] == 0) zeroCount++;
}
return zeroCount > 0;
}
Upvotes: 0
Reputation: 22506
This sounds an awful lot like a homework problem, so I'll just give you the concepts and let you learn.
You need to use a "for" loop, check the value of each item in the array, and return true if you find one, otherwise return false after the loop exits.
Upvotes: 0
Reputation: 3772
bool checkFunction(int *myArray, int size)
{
for (int i=0; i < size; ++i)
{
if (myArray[i] == 0)
return true;
}
return false;
}
Are you talking about something like this? This will iterate through the array and return true if there is a value of 0 anywhere.
Upvotes: 3