How do I check if an integer is even or odd?

Asked 1 years ago, Updated 1 years ago, 119 views

It's the same as the title. How do I check if an integer is even or odd?

c integer

2022-09-22 14:41

1 Answers

When determining whether an integer is even or odd, there are usually two methods.

Use odd if the last bit of an integer is 1, and even if it is 0.

int c = 1;
if( c&1 )
    printf("c is odd\n");
else
    printf("c is even\n");

Definition of even and odd numbers

Use .

int c = 1;
if( c%2 )
    printf("c is odd\n");
else
    printf("c is even\n");

In the next chord, The assembly code for the two was the same, using any optimization option (without option/-O/-Os/-O2/-O3).

/* modulo.c */
#include <stdio.h>

int main(void)
{
    int x;
    for (x = 0; x < 10; x++)
        if (x % 2)
            printf("%d is odd\n", x);
    return 0;
}

/* /* and.c */
#include <stdio.h>

int main(void)
{
    int x;
    for (x = 0; x < 10; x++)
        if (x & 1)
            printf("%d is odd\n", x);
    return 0;
}


2022-09-22 14:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.