How to determine 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 destination tells me that I need to determine at least one element in the array is greater than zero. Only if all the elements are empty, I would say that var isEmpty is true and then returns a value.

The 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;
}
+4
source share
5 answers

Your code does not work as it only considers the last element in the loop element. Try this: return that the array is not empty if you find 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;
}
+6
source

, n. . foreach .

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
    }
+3

, you don't need variables , bool isEmpty, LINQ, , , , .

, " , , ". , , . :

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

return true;
0

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

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

true, 0.

, All , .

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

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

it’s even better not to create this method, since you can directly call this operator from where you call this method (if its call is not called from several places).

0
source

Source: https://habr.com/ru/post/1583863/


All Articles