score:16

Accepted answer

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.

score:1

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.

score:1

string result = array.any(x => x < 0)?"wrong":"positive";

score:3

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.

score:6

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
}

Related Query

More Query from same tag