简体   繁体   中英

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;
}

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;
}

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
    }

I think by you don't need variables your teacher means you don't need the bool isEmpty , You can use LINQ like others are saying, but I doubt you know what that is yet.

Per your requirements, you can say that "if I encounter any non-zero value, I have all the information I need to return a response". If I check all values, and have not found any non-zeros, I also know how to respond then. So try:

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

return true;

try this

bool isEmpty = false;
int count = 0;
for(int i=0;i<n;i++){
   if(S[i] == 0){
      count++;
   }
}
isEmpty = (count==n);

Can you try

S.Any(x => x != 0);

This should give out true if any of the element in array is not equal to 0.

similarly, you can explore the option of All in case you need to check all the elements of an array.

S.All(x => x == 0);

so your code will be

public static bool is_empty(int[] S)
{
    // return true if no element is 0
    return !S.Any(x => x != 0);
    // or use
    return S.All(x => x == 0);
}

better still you don't need to create this method either, as you can directly call this statement from where you are calling this method (unless its called from multiple places).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM