c++ check if number is even or odd

To check if a number is even or odd in C++, you can use the modulo operator (%). Here is the code snippet:

#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;

    if (number % 2 == 0) {
        std::cout << "The number is even." << std::endl;
    } else {
        std::cout << "The number is odd." << std::endl;
    }

    return 0;
}

Explanation:

  1. #include <iostream>: This line includes the input/output stream library, which allows us to use input/output functions like std::cout and std::cin.

  2. int main(): This is the main function where the execution of the program starts.

  3. int number;: This declares an integer variable named number.

  4. std::cout << "Enter a number: ";: This line prints the message "Enter a number: " to the console.

  5. std::cin >> number;: This line reads a number from the user and stores it in the number variable.

  6. if (number % 2 == 0) { ... }: This is an if statement that checks if the number is divisible by 2 with no remainder. The % operator calculates the remainder of the division. If the remainder is 0, then the number is even.

  7. std::cout << "The number is even." << std::endl;: This line prints the message "The number is even." to the console if the condition in the if statement is true.

  8. else { ... }: This is the else part of the if statement. If the condition in the if statement is false (i.e., the number is odd), the code inside the else block will be executed.

  9. std::cout << "The number is odd." << std::endl;: This line prints the message "The number is odd." to the console if the condition in the if statement is false.

  10. return 0;: This statement ends the main function and returns 0 to the operating system, indicating successful execution of the program.