// here I have tried to print the number of positive , negative ,even , odd , elements in the array . The rest of the output is right , except it is print 0 in case of even , when obviously they are not 0.So What is the bug here!
#include <stdio.h>
int main()
{
int arr[10] = {2, 4, 6, 8, 10, 11, 13, 15, -2, -4};
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
for (int i = 0; i < 10; i )
{
if (arr[i] & 1 == 0)
{
even ;
}
if (arr[i] & 1 == 1)
{
odd ;
}
if (arr[i] > 0)
{
pos ;
}
else if (arr[i] < 0)
{
neg ;
}
}
printf("the odd are %d ,the even are %d ,the positive are %d , the negative are %d\n", odd, even, pos, neg);
return 0;
}
CodePudding user response:
This is because of operator precedence
arr[i] & 1 == 0
is equivalent to arr[i] & (1 == 0)
, which is arr[i] & 0
, which is obviously 0, so the condition is always false.
You want to do this instead:
if ((arr[i] & 1) == 0)
{
even ;
}
if ((arr[i] & 1) == 1)
{
odd ;
}
The odd test already works because arr[i] & 1 == 1
is arr[i] & (1 == 1)
which is arr[i] & 1
which is equivalent to what you were checking anyway.
CodePudding user response:
arr[i] & 1 == 0
is always zero because of operator precendence.
It is equivalent with arr[i] & (1 == 0)
which is clearly not what you want.
Try
if ((arr[i] & 1) == 0) {
even
}
CodePudding user response:
&
has lower precedence than ==
, so arr[i] & 1 == 0
is structure as arr[i] & (1 == 0)
instead of (arr[i] & 1) == 0
. To get the latter, you must use explicit parentheses.
Turn on warnings in your compiler, elevate them to errors, and pay attention to the compiler messages. With Clang, start with -Wmost -Werror
. With GCC, start with -Wall -Werror
. With MSVC, start with /W3 /Wx
.
CodePudding user response:
The problem with your code is the conditions you're using. They're wrong. The correct way to find out whether a number is odd or even is this:
if (num % 2 == 0)
{
// Even
}
if (num % 2 != 0)
{
// Odd
}
So the final code:
#include <stdio.h>
int main()
{
int arr[10] = { 2, 4, 6, 8, 10, 11, 13, 15, -2, -4 };
int pos = 0;
int neg = 0;
int even = 0;
int odd = 0;
for (int i = 0; i < 10; i )
{
if (arr[i] % 2 == 0)
{
even ;
}
if (arr[i] % 2 != 0)
{
odd ;
}
if (arr[i] > 0)
{
pos ;
}
else if (arr[i] < 0)
{
neg ;
}
}
printf("the odd are %d ,the even are %d ,the positive are %d , the negative are %d\n", odd, even, pos, neg);
return 0;
}