Write a C++ program to check if a number is even or odd.

Algorithm of program to check if a number is even or odd.

  1. Start
  2. Initialize:
    • number (integer)
  3. Input:
    • User inputs 42
    • number = 42
  4. Processing:
    • Calculate 42 % 2 which equals 0
    • Since 0 == 0, print “The number 42 is even.”
  5. End

Explanation of the Code

  1. Include Header Files:
    • #include <iostream>: This header file is required for input and output operations.
  2. Using the Standard Namespace:
    • using namespace std;: This line allows us to use standard library names like cout and cin without prefixing them with std::.
  3. Main Function:
    • int main() { ... }: This is the entry point of any C++ program. The main function must return an integer.
  4. Declare a Variable:
    • int number;: This declares an integer variable to store the user input.
  5. Get User Input:
    • cout << "Enter a number: ";: This outputs a prompt asking the user to enter a number.
    • cin >> number;: This reads the user input and stores it in the number variable.
  6. Conditional Statement:
    • if (number % 2 == 0) { ... }: This checks if the number is divisible by 2 without a remainder. If true, the number is even.
    • else { ... }: This block executes if the condition in the if statement is false, meaning the number is odd.
  7. Output:
    • cout << "The number " << number << " is even." << endl;: This prints the result if the number is even.
    • cout << "The number " << number << " is odd." << endl;: This prints the result if the number is odd.
    • << endl;: This adds a newline character after the output.
  8. Return Statement:
    • return 0;: This indicates that the program ended successfully.

Leave a Comment

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

Scroll to Top