Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect when an element in an array is empty in C#? (When empty, element = 0)

I have an array of 5 integers, from 1 to 5. My assignment tells me I need to be able to detect whether atleast one element in the array is greater than zero. Only if ALL elements are empty, would I say that var isEmpty is true, and then return the value.

Code:

public static bool is_empty(int[] S, int n)
{

    bool isEmpty = false;

    for (int i = 0; i < n; i++)
    {   
        if (S[i] != 0)
        {
            isEmpty = false;
        }
        else
        {
            isEmpty = true;
        }
    }
    return isEmpty;
}
like image 436
parkie1995 Avatar asked Jan 09 '23 13:01

parkie1995


2 Answers

Your code doesn't work as it considers only the last element in the element in the loop. Try this: Return that the array is not empty once you found a non-empty element; otherwise, return that all elements are empty:

public static bool is_empty(int[] S, int n)
{
    for (int i = 0; i < n; i++)
    {   
        if (S[i] > 0) // negative values still count towards "being empty"
            return false;
    }
    return true;
}
like image 119
Quality Catalyst Avatar answered Jan 15 '23 22:01

Quality Catalyst


I'm not sure why you have the input parameter n. So I've removed it. And instead I've used a foreach loop to loop through every element in the array.

static bool IsEmpty(int[] S)
    {
        foreach (int x in S)
        {
            if (x != 0)
            {
                return false; //If any element is not zero just return false now
            }
        }

        return true; //If we reach this far then the array isEmpty
    }
like image 21
Padraic Avatar answered Jan 15 '23 21:01

Padraic