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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With