C program to check even or odd using functions

Write a C program to input any number from user and check whether the given number is even or odd using functions. How to find whether a number is even or odd using functions in C programming. Write a function in C programming to check whether a given number is even or odd.

Example

Input

Input any number: 10

Output

10 is even

Required knowledge

Basic C programming, Functions

Declare function to find even odd

In my previous posts I have explained various ways to check even numbers. You can embed the logic to check even numbers using any of the following approaches in a function.

Must know -

For this program I will use bitwise & operator to check even numbers.

  1. First let us give a meaningful name to our function, say isEven().
  2. Next, the function must accept one integer which is to be validated for even condition, say isEven(int num).
  3. Finally, as per the name the function must return true if given integer is even otherwise false. However, C does not supports boolean values. In C programming, 0 is represented as false and 1 as true. Hence, the isEven() function must return an integer.

So the function declaration to check even number is - int isEven(int num);

Program to check even or odd

/** 
 * C program to check even or odd using functions
 */

#include <stdio.h>


/**
 * Check whether the least significant bit of the number is 1 or not. 
 * If it is 1 then the number is odd else even.
 */
int isEven(int num)
{
    return !(num & 1);
}


int main()
{
    int num;
    
    /* Input number from user */
    printf("Enter any number: ");
    scanf("%d", &num);
    
    
    /* If isEven() function returns 0 then the number is even */
    if(isEven(num))
    {
        printf("The number is even.");
    }
    else
    {
        printf("The number is odd.");
    }
    
    return 0;
}

Output

Enter any number: 22
The number is even.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>