Check Whether a Given Number is Even or Odd?

Program to check whether a given number is even or odd. A basic C++ program to understand various mathematical operators and operations in C and C++.

As a kid, you must have read about various types of numbers. Programming is all about numbers and in this lesson, you'll learn how to check whether a given number is an odd number or an even number.

Purpose

Write a program to check whether a given number is an odd number or an even number and print the output message displaying the type

This is a very basic program that will teach you aboout mathematical operators and operations in C++. So before we dive in let's understand what odd and even numbers are.

The Algorithm

Technically, the property even or odd of a number is referred to as Parity. A number's parity is even when it is divisible by 2 with no remainders left and odd if the number has a remainder 1. Also, it doesn't matter whether the number is a positive or a negative integer. So we have our algorithm now, let's dive into code.

#include <stdio.h>
#include <conio.h>

using namespace std;

int main()
{
    int num;

    printf("------------------------------------------------\n");
    printf("Program to check whether a given number is even or odd number \n");
    printf("------------------------------------------------\n");

    printf("Enter the first number: ");
    scanf("%d", &num);

    if (num % 2 == 0)
    {
        printf("The number %d is an even number", num);
    }
    else
    {
        printf("The number %d is an odd number", num);
    }

    getch();

    return 0;
}
Output
------------------------------------------------
Program to check whether a given number is even or odd number
------------------------------------------------
Enter the first number: 33
The number 33 is an odd number

Explanation

As you can see, we first accepted an integer from a user then used the % Modulus or the modulo operator which is an arithmetic operator which produces the remainder of an integer division. Note that the modulus operator cannot be applied to floating point numbers and proces an error.