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. The program is written in C++ and includes detailed documentation to explain its structure and functionality.

Program Explanation

The program consists of a simple main function that performs the following tasks:

  • Prompts the user to enter a number.
  • Reads the input number.
  • Uses a conditional statement to check if the number is odd or even.
  • Prints the result to the console.

Source Code


// Include the necessary header files
#include <iostream>  // For input and output operations

// Use the standard namespace to avoid prefixing 'std::' before standard functions and objects
using namespace std;

/**
 * Main function: Entry point of the program
 * 
 * This function prompts the user for a number, checks if the number is odd or even,
 * and outputs the result.
 * 
 * @return int - Returns 0 to indicate successful execution
 */
int main() {
    int number;  // Declare an integer variable to store the user's input

    // Prompt the user to enter a number
    cout << "Enter a number: ";
    cin >> number;  // Read the number from the user

    // Check if the number is even or odd using the modulus operator
    if (number % 2 == 0) {
        // If the remainder when divided by 2 is 0, the number is even
        cout << number << " is even." << endl;
    } else {
        // If the remainder when divided by 2 is not 0, the number is odd
        cout << number << " is odd." << endl;
    }

    return 0;  // Return 0 to indicate successful execution
}
    

Detailed Documentation

Header Files:
The program includes the <iostream> header file to enable input and output operations using cin and cout.

Namespace:
The using namespace std; directive is used to avoid the need to prefix standard library functions and objects with std::.

Main Function:
The main function is the entry point of the program. It performs the following steps:

  • Declares an integer variable number to store the user’s input.
  • Prompts the user to enter a number using cout and reads the input using cin.
  • Uses an if statement to check if the number is even by evaluating the expression number % 2 == 0.
  • If the condition is true, the program outputs that the number is even; otherwise, it outputs that the number is odd.

 

Leave a Reply

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