REA98
REA98

Reputation: 63

How to disregard a negative value in a set of input

I'd like to ask what should I do (don't tell the exact code) to disregard a negative value if I were to add 5 integers. For example, I have inputted 1, 2, 3, 4, and -1. The sum should be 10 not 9 since it is required to disregard the negative values. Thank you in advance!

int main()
{
int num, sum=0, i;

for(i=0;i<5;i++)
{
printf("Please enter 5 integers: ");
scanf("%d", &num);
sum+=num;
}
printf("The sum is %d", sum);
return 0;
}

Upvotes: 1

Views: 125

Answers (2)

Bathsheba
Bathsheba

Reputation: 234685

The fastest way I know of is to use

sum += 0 ^ ((0 ^ num) & -(0 < num))

This uses the idiomatic way of computing max

x ^ ((x ^ y) & -(x < y))

for int types (which will be faster than either an if or a ternary.)

If speed is not of the essence and your C implementation has max (or MAX) then do consider using that instead: sum += max(0, num)

Upvotes: 2

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

Using if

 if(num>0)
     sum+=num;

Another way using ternary operator ? :

sum += num>0? num: 0;

Upvotes: 4

Related Questions