C program to check even or odd using macro

Write a C program to check even or odd using macro. How to check whether a given number is even or odd using macro in C program. Logic to check even or odd numbers using macro.

In previous post we learned to add basic logic to our macro. We learned to find square and cube of an number using macro. Here in this post we will move a step further. We will learn to add conditions to a macro. 

In this post you will come to learn how to add basic conditions to a macro. We will write a macro to check if a given number is even number or not. In short we will transform our even odd function to macro.

Required knowledge

Basic C programming, Macros, Bitwise operator

During the course of C programming tutorials I have explained several ways to check even or odd number. In case you missed any one of them, below are some quick links.

How to find even or odd using macro?

During the course of macro exercises, we learned how to define macro. So, let us get started and define a macro which accept a argument to check for even or odd. Here I am using bitwise operator to check even or odd number

Example:

#define IS_ODD(x) (x & 1)

The above macro accepts an argument. It returns 1 if xis odd otherwise returns 0. You can use the above macro to check both even and odd. 

Program to check even or odd using macro

/**
 * C program to check even or odd number using macro
 */

#include <stdio.h>

// Define macro to check odd number
#define IS_ODD(x) (x & 1)

int main()
{
    int num;

    // Input a number from user
    printf("Enter any number to check even or odd: ");
    scanf("%d", &num);

    if (IS_ODD(num))
        printf("%d is ODD\n", num);
    else
        printf("%d is EVEN\n", num);

    return 0;
}

Output

Enter any number to check even or odd: 22
22 is EVEN

Happy coding 😉

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>