C Program to Check Even or Odd Number

Introduction

Determining whether a number is even or odd is a common programming task that helps in understanding the use of conditional statements. This guide will show you how to write a C program to check whether a given number is even or odd.

Problem Statement

Create a C program that:

  • Takes a number as input from the user.
  • Determines whether the number is even or odd.
  • Displays the result.

Example:

  • Input: 4
  • Output: 4 is an even number

Solution Steps

  1. Include the Standard Input-Output Library: Use #include <stdio.h> to include the standard input-output library, which is necessary for using printf and scanf functions.
  2. Write the Main Function: Define the main function, which is the entry point of every C program.
  3. Declare Variables: Declare a variable to store the number.
  4. Input the Number: Use scanf to take input from the user for the number.
  5. Check if the Number is Even or Odd: Use the modulus operator % to check the remainder when the number is divided by 2.
  6. Display the Result: Use printf to display whether the number is even or odd.

C Program

#include <stdio.h> /** * C Program to Check Even or Odd Number * Author: https://www.javaguides.net/ */ int main() { // Step 1: Declare a variable to hold the number int num; // Step 2: Prompt the user to enter a number printf("Enter an integer: "); scanf("%d", &num); // Step 3: Check if the number is even or odd using the modulus operator if (num % 2 == 0) { // If the remainder is 0, the number is even printf("%d is an even number.\n", num); } else { // If the remainder is not 0, the number is odd printf("%d is an odd number.\n", num); } return 0; // Step 4: Return 0 to indicate successful execution } 

Explanation

Step 1: Declare a Variable

  • The variable num is declared as an integer to hold the number entered by the user.

Step 2: Input the Number

  • The program prompts the user to enter an integer using printf. The scanf function then reads the input and stores it in the variable num.

Step 3: Check if the Number is Even or Odd

  • The program uses the modulus operator % to check the remainder when num is divided by 2:
    • If the remainder is 0, the number is even.
    • If the remainder is not 0, the number is odd.

Step 4: Display the Result

  • The program displays whether the number is even or odd using the printf function.

Step 5: Return 0

  • The return 0; statement indicates that the program executed successfully.

Output Example

Example:

Enter an integer: 4 4 is an even number. 

Another Example:

Enter an integer: 7 7 is an odd number. 

Conclusion

This C program demonstrates how to check whether a given number is even or odd using the modulus operator. It covers basic concepts such as variable declaration, taking user input, and using conditional statements, making it a useful example for beginners learning C programming.

Leave a Comment

Scroll to Top