Checking Even or Odd Numbers in C++

Beginner

Introduction

In this lab, we will learn how to write a program in C++ to check if a given number is even or odd. We will use the modulus operator to determine the remainder of the number divided by 2. If the remainder is 0, the number is even, and if the remainder is 1, the number is odd.

Create a new file

Let's create a new C++ file named even_odd.cpp in your project directory by executing the following command:

touch ~/project/even_odd.cpp

Write the setup code and take input

Let's start by writing the C++ code to welcome the user, display a prompt for input, and take input from the user.

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the Even/Odd Checker:\n\n\n";
    cout << "Enter the number to check: ";
    int n;
    cin >> n;
}

The code above simply displays a welcome message and prompts the user to enter a number. The number entered by the user is stored in a variable named n.

Check if the number is even or odd

Let's now add the code to check if the entered number is even or odd and display the result accordingly.

#include <iostream>
using namespace std;

int main()
{
    cout << "\n\nWelcome to the Even/Odd Checker:\n\n\n";
    cout << "Enter the number to check: ";
    int n;
    cin >> n;

    if(n % 2 == 0)
    {
        cout << "\n\nThe entered number "<< n << " is Even\n";
    }
    else
    {
        cout << "\n\nThe entered number "<< n << " is Odd\n";
    }

    return 0;
}

The code snippet inside the if-statement checks if the remainder of the entered number when divided by 2 is 0. If it is, it means the number is even, and the result is displayed accordingly.

Compile and run the program

Let's now compile and run the program to see if it's working correctly. From the project directory's terminal, execute the following commands:

g++ ~/project/even_odd.cpp -o even_odd
./even_odd

After running the above commands, you should see the following output on the terminal:

Welcome to the Even/Odd Checker:

Enter the number to check: 12


The entered number 12 is Even

Enter different values and see if the program is correctly determining whether the number is even or odd.

Summary

In this lab, we learned how to write a C++ program to check if an entered number is even or odd. We used the modulus operator to determine the remainder of the entered number when divided by 2 and displayed the result accordingly.

Other Tutorials you may like