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

后端 未结 5 1488
感情败类
感情败类 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: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;
    }
    

提交回复
热议问题