2

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.

7 Answers 7

3
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.

Sign up to request clarification or add additional context in comments.

Comments

3

Use std::find

#include <algorithm>

bool ContainsZero(int *arr, int size)
{
   return std::find(arr, arr+size, 0) != (arr+size);
}

Comments

2

How about reading a tutorial on arrays in C++?

Comments

1
bool TestForZero(int* myArray, int maxSize)
{
    for(int ii=0; ii<maxSize; ++ii)
      if(myArray[ii] == 0)
        return true;

  return false;
}

1 Comment

I had try catch in there because technically, the OP asked to pass a 'maximum' (not actual) size. My implementation was wrong, so I took it out.
0

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.

3 Comments

Yes, I'm doing homework. Is that ok to questions like this here? I'm a newb to the site and any unwritten rules.
Homework questions are perfectly fine as long as you've done your research, are asking questions to understand your homework and not just have your homework done for you.
Indeed. Like many other communities of coders out there, we are here to help you learn, not solve your problems for free. So if you wish to learn, you will really enjoy this website. Good luck in your learning, hope you keep it up!
0
bool hasZeroes(int * array, int len) {
  int zeroCount = 0;
  for (int i = 0; i < len; i++) {
    if (array[i] == 0) zeroCount++;
  }
  return zeroCount > 0;
}

Comments

0
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.