How to check if all the values of an array are equal to 0?

后端 未结 5 1453
感情败类
感情败类 2021-01-16 14:02

The context of the program is a game involving pegs and discs. The user inputs the amount of pegs (max of 20) and the amount of discs on each peg (max of 10). Two players go

相关标签:
5条回答
  • 2021-01-16 14:21

    try memcmp instead of having separate function with for loop:

    int zeros[sizeof(yourArray)];
    if(memcmp(yourArray,zeros,sizeof(yourArray))==0)
    //do things
    else
    //do things
    
    0 讨论(0)
  • 2021-01-16 14:35
    bool checkPegs(int array[], int size)
    {
      for (int i = 0; i < size; i++)
      {
          if(array[i] != 0)
          {
            return false;
          }
      }
      return true;
    }
    
    0 讨论(0)
  • 2021-01-16 14:43

    there are two errors here

    bool checkPegs(int array[], int size)
    {
      int checker(0);
      for (int i = 0; i < size; i++)
      {
          if(array[i] = 0) // the first one use '==' instead of '='
          {
            return true; // the second one, you are testing the first element only
          }
          else
          {
            return false;
          }
      }
    }
    

    here how it should be

    bool checkPegs(int array[], int size)
    {
    
      for (int i = 0; i < size; i++)
      {
          if(array[i] )
              return false; // return false at the first found
    
      }
      return true; //all elements checked
    }
    
    0 讨论(0)
  • 2021-01-16 14:43

    The way you wrote your code cannot work, for you are actually considering only the first element because of the two return statements in the if/else. Moreover, you use an assignment statement instead of a comparison.

    It follows a reviewed example:

    bool checkPegs(int *array, int size) {
        for (int i = 0; i < size; i++) {
            if(array[i] != 0) { return false; }
        }
        return true;
    }
    

    Keep in mind that it can be optimized and you can do the same using standard utilities, but I assume that you are learning to code and so it's worth to write it for yourself.

    0 讨论(0)
  • 2021-01-16 14:44
    if(array[i] = 0)
    

    That doesn't compare array[i] with 0, it assigns 0 to array[i]. You want array[i] == 0.

    if(array[i] == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
    

    The second issue is that you only check the first element, then return based on that. You should check every element to ensure they are non-zero:

    for (int i = 0; i < size; i++)
    {
        if(array[i] != 0) {
            return false;
        }
    }
    

    Finally, you don't handle the case that size is 0. In that case, you should return true.

    bool checkPegs(int array[], int size)
    {
        for (int i = 0; i < size; i++)
        {
            if(array[i] != 0) {
                return false;
            }
        }
    
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题