Odd or Even Number Checker in C

 

Odd or Even Number Checker in C

This program determines if a given number is odd or even. Below is the C code for the program along with a detailed explanation of its structure and documentation.

Program Code


#include <stdio.h>

/**
 * Function to check if a number is odd or even.
 * @param number - the number to be checked
 * @return 1 if the number is odd, 0 if the number is even
 */
int isOddOrEven(int number) {
    return number % 2;
}

int main() {
    int number;

    // Prompt the user to enter a number
    printf("Enter a number: ");
    scanf("%d", &number);

    // Check if the number is odd or even
    if (isOddOrEven(number)) {
        printf("The number %d is odd.\n", number);
    } else {
        printf("The number %d is even.\n", number);
    }

    return 0;
}

Explanation

Here’s a step-by-step explanation of the program structure:

  1. Include Header File:
    #include <stdio.h>

    This header file is included to use the standard input-output functions like printf and scanf.

  2. Function Definition:
    
    /**
     * Function to check if a number is odd or even.
     * @param number - the number to be checked
     * @return 1 if the number is odd, 0 if the number is even
     */
    int isOddOrEven(int number) {
        return number % 2;
    }
                

    The isOddOrEven function takes an integer as input and returns 1 if the number is odd, and 0 if the number is even. It uses the modulus operator (%) to determine the remainder when the number is divided by 2.

  3. Main Function:
    int main() {
        int number;
    
        // Prompt the user to enter a number
        printf("Enter a number: ");
        scanf("%d", &number);
    
        // Check if the number is odd or even
        if (isOddOrEven(number)) {
            printf("The number %d is odd.\n", number);
        } else {
            printf("The number %d is even.\n", number);
        }
    
        return 0;
    }

    The main function is the entry point of the program.

    • It declares an integer variable number.
    • It prompts the user to enter a number using printf and reads the input using scanf.
    • It calls the isOddOrEven function to check if the number is odd or even and prints the result accordingly.
    • It returns 0 to indicate that the program ended successfully.

 

Leave a Reply

Your email address will not be published. Required fields are marked *