C Program to Check Whether a Number is Even or Odd

Updated on November 27, 2024
Check whether a number is even or odd header image

Introduction

Determining whether a number is even or odd is a fundamental concept in computer programming and mathematical computations. This simple test can influence the flow of logic in applications ranging from simple loops to complex conditional structures.

In this article, you will learn how to create a C program to check if a number is even or odd. Practical examples will help you understand the implementation and usage of conditional statements in C for this purpose.

Basic Even or Odd Check

Create a Function to Determine Evenness

  1. Start by defining a function that takes an integer as its argument.

  2. Inside the function, use the modulus operator % to test if the number is divisible by 2.

  3. If the number is divisible by 2, return true indicating even; otherwise, return false.

    c
    #include <stdio.h>
    #include <stdbool.h>
    
    bool isEven(int num) {
        return (num % 2 == 0);
    }
    

    The function isEven returns true if num is divisible by 2, indicating the number is even. If not, it returns false, implying the number is odd.

Main Function to Test Even or Odd

  1. Define the main() function where you prompt the user for a number.

  2. Use the isEven function to check the number and display the appropriate message based on whether the number is even or odd.

    c
    int main() {
        int number;
        printf("Enter an integer: ");
        scanf("%d", &number);
    
        if (isEven(number)) {
            printf("%d is even.\n", number);
        } else {
            printf("%d is odd.\n", number);
        }
        return 0;
    }
    

    This main function reads an integer from the user and checks its evenness using the isEven function. It then prints whether the given number is even or odd.

Conclusion

Creating a C program to check whether a number is even or odd showcases basic programming skills involving input/output operations and conditional statements. By following through with these examples, you improve your ability to handle fundamental data manipulation and improve clarity in programming through the creation of specialized functions. Continue experimenting with these foundations to enhance your ability in C programming for various applications.