C Program to Check Even or Odd Number

1. Introduction

In mathematics, an even number is divisible by 2 without leaving a remainder, whereas an odd number will leave a remainder when divided by 2. In the realm of programming, understanding whether a number is even or odd can be crucial for various algorithms and logic flows. Today, we will walk through a simple C program that discerns if a given number is even or odd.

2. Program Overview

Our program will:

1. Prompt the user to input a number.

2. Determine if the number is even or odd using the modulus operator.

3. Display the result to the user.

3. Code Program

#include <stdio.h>  // Incorporate the Standard I/O library

int main() {  // Initiate the program

    int num;  // Declare an integer variable

    // Request the user for a number
    printf("Enter an integer: ");
    scanf("%d", &num);  // Capture the entered number

    // Use the modulus operator to determine even or odd status
    if(num % 2 == 0)
        printf("%d is even.\n", num);  // Notify if the number is even
    else
        printf("%d is odd.\n", num);  // Notify if the number is odd

    return 0;  // End the program gracefully
}

Output:

Enter an integer: 7

4. Step By Step Explanation

1. #include <stdio.h>: This line incorporates the standard input and output library, enabling us to use essential I/O functions.

2. int main(): The primary entry point of our C program.

3. Variable Declaration:

  • num: An integer variable that will keep the user's input.

4. User Input:

  • We encourage the user to enter a number.
  • We use the scanf function with the %d format specifier to store the input number in the num variable.

5. Even or Odd Determination:

  • We use the modulus operator (%), which gives the remainder of the division of two numbers.
  • If num % 2 yields a remainder of 0, it means the number is divisible by 2 and hence, even. Otherwise, the number is odd.
  • Based on this logic, we employ an if-else structure to decide and display whether the number is even or odd.

6. Output: The program subsequently shows if the provided number is even or odd.

This simple yet effective technique, anchored on the modulus operation, is a quintessential example of how basic arithmetic can be harnessed for decision-making in programming.

Comments