Write a C program to input a number from user and check whether given number is even or odd using functions. How to check even or odd using functions in C programming. Write a function in C programming to check even or odd.
Example
Input
Input any number: 10
Output
10 is even
Required knowledge
Basic C programming, Functions, Returning value from function
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 – Program to check even number using conditional operator.
Let us define a function to check even or odd.
- First give a meaningful name to our function, say
isEven()
. - Next, the function must accept one integer which is to be validated for even condition, say
isEven(int num)
. - Finally as per name, the function must return
true
if given integer is even otherwisefalse
. However, C does not supports boolean values. In C programming, 0 is represented asfalse
and 1 (any non-zero integer) astrue
. Hence,isEven()
we must return an integer from function.
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>
/**
* Function to check even or odd
* Returns 1 is num is even otherwise 0
*/
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;
}
In the above program I have used bitwise operator &
to check even or odd numbers. However you can also use if else statement to check even or odd numbers.
Output
Enter any number: 22 The number is even.
Happy coding 😉
Recommended posts
- Function and recursion programming exercises index.
- C program to find maximum or minimum between two numbers using functions.
- C program to check prime, strong, armstrong or perfect numbers using functions.
- C program to count even and odd elements in array.
- C program to sort even and odd elements separately.
- C program to print even and odd numbers using recursion.