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; }
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; }
, 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 }
, you don't need variables , bool isEmpty, LINQ, , , , .
you don't need variables
isEmpty
, " , , ". , , . :
for (int i = 0; i < n; i++) { if (S[i] != 0) { return false; } } return true;
bool isEmpty = false; int count = 0; for(int i=0;i<n;i++){ if(S[i] == 0){ count++; } } isEmpty = (count==n);
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).