Algorithm of program to check if a number is even or odd.
- Start
- Initialize:
number(integer)
- Input:
- User inputs
42 number = 42
- User inputs
- Processing:
- Calculate
42 % 2which equals0 - Since
0 == 0, print “The number 42 is even.”
- Calculate
- End
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> using namespace std; int main() { // Declare a variable to store the number int number; // Get user input cout << "Enter a number: "; cin >> number; // Check if the number is even or odd if (number % 2 == 0) { // If the remainder when dividing by 2 is 0, the number is even cout << "The number " << number << " is even." << endl; } else { // If the remainder when dividing by 2 is not 0, the number is odd cout << "The number " << number << " is odd." << endl; } return 0; } |
Explanation of the Code
- Include Header Files:
#include <iostream>: This header file is required for input and output operations.
- Using the Standard Namespace:
using namespace std;: This line allows us to use standard library names likecoutandcinwithout prefixing them withstd::.
- Main Function:
int main() { ... }: This is the entry point of any C++ program. Themainfunction must return an integer.
- Declare a Variable:
int number;: This declares an integer variable to store the user input.
- 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 thenumbervariable.
- 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 theifstatement is false, meaning the number is odd.
- 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.
- Return Statement:
return 0;: This indicates that the program ended successfully.
