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 any number: 10
Output: Even

Required knowledge

Basic C programming, Functions

As I have already explained in many of my earlier posts how to check the even/odd conditions whether using if else statements or using switch case or using conditional operators or using bitwise operators. You can apply any of the logic with the concept of functions to check even or odd using functions. Here I am using concept of bitwise operators to find even or odd, as its the fastest method of checking even/odd.

Program to check even or odd

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

#include <stdio.h>


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


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


Output
Enter any number: 22
The number is even.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment