Reputation: 26518
I have an array, say
int[] array = new int[] { 1, 5, 11, 5 };
How can I check (in the most easy and efficient way) that all elements are positive? If at least one number is not a positive integer, the system will respond in a negative way.
Desired output:
if all the numbers are positive, then it will display "All Positive" else "Wrong"
My shot
int[] array = new int[] { 1, 5, 11, 5 };
var x = array.All(c => c >= '0' && c <= '9');
if (x == true) "Positive" else "Wrong";
Upvotes: 8
Views: 22605
Reputation: 223282
Use Enumerable.Any like:
if(array.Any(r => r < 0))
{
//Negative number found
}
else
{
//All numbers are positive
}
Or you can use Enumerable.All Like:
if(array.All(r => r > 0))
{
//All numbers are positive
}
else
{
//Negative number found
}
Upvotes: 6
Reputation: 1501926
You were nearly there before - but you were comparing with characters instead of integers.
If you want to check whether everything is strictly positive, use:
bool allPositive = array.All(x => x > 0);
If you actually want to check they're all non-negative (i.e. 0 is acceptable) use:
bool allNonNegative = array.All(x => x >= 0);
You should definitely consider what you want to do with 0, as your problem statement is actually contradictory. ("All positive" and "no negative" aren't the same thing.)
Note that just like Any
, All
will quit as soon as it knows the result - so if the first value is negative, it won't need to look through the rest.
Upvotes: 17
Reputation: 98810
You almost there. But in your condition, you comparing characters instead of integers which is wrong in your situation.
Use Enumerable.All
like;
Determines whether all elements of a sequence satisfy a condition.
int[] array = new int[] { 1, 5, 11, 5 };
bool allPositive = array.All(x => x > 0);
Console.WriteLine(allPositive);
Here is a DEMO
.
Remember 0
is not positive.
Upvotes: 3
Reputation: 7918
Below is a C# solution to your problem (it should be rather efficient performance-wise):
int[] array = new int[] { 1, 5, 11,5 };
bool _allPositive=true;
for (int i=0;i<array.length;i++){
if(array[i]<0 {_allPositive=false; break;}
}
bool _allPositive
indicates the result (you can use string var if you prefer). Essentially, the same syntax can apply to Java-like languages, including scripting.
Upvotes: 1