In this article, we will write a C program to check even or odd using functions.
The program takes a number as input from the user and checks if the number is even or odd.
Sample Input:
Enter the number: 25
Output:
25 is an Odd Number
A number is called an even number if is it divisible by 2, otherwise, it is called an odd number. For example, 2, 4, 6 are even numbers whereas 1, 3, 5, 7 are odd numbers.
In the following C program, we have defined a function isEven()
which takes a single argument(the number) and checks if the number is even or odd.
If the number is even, the isEven()
function returns a boolean value true, otherwise, it returns a boolean value false.
// C program to check if number is even or odd #include <stdio.h> #include <stdbool.h> //User defined function to check if number is even or odd bool isEven(int num) { if (num % 2 == 0) { // Number is even return true; } else { // Number is odd return false; } } int main() { // Declare the variables int number; bool isNumEven; printf("Enter the number: "); scanf("%d", &number); // Call the isEven() function isNumEven = isEven(number); if (isNumEven) { printf("%d is an Even Number", number); } else { printf("%d is an Odd Number", number); } return 0; }
Output:
Enter the number: 25 25 is an Odd Number
Code Explanation:
- The program first asks the user to enter a number and store it in the
number
variable. - The entered number is passed to the
isEven()
function as an argument. TheisEven()
function checks if the number is divisible by 2, if yes, it returns true, otherwise, it returns false. - The value returned from the
isEven()
function is stored in theisNumEven
variable. - If the value stored in the
isNumEven
variable is true, it means the given number is even, otherwise, it is an odd number. - Finally, the result is printed on the screen using the printf() function.
Thanks for reading.