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:
#include <iostream>
: This line includes the input/output stream library, which allows us to use input/output functions likestd::cout
andstd::cin
.int main()
: This is the main function where the execution of the program starts.int number;
: This declares an integer variable namednumber
.std::cout << "Enter a number: ";
: This line prints the message "Enter a number: " to the console.std::cin >> number;
: This line reads a number from the user and stores it in thenumber
variable.if (number % 2 == 0) { ... }
: This is anif
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.std::cout << "The number is even." << std::endl;
: This line prints the message "The number is even." to the console if the condition in theif
statement is true.else { ... }
: This is theelse
part of theif
statement. If the condition in theif
statement is false (i.e., the number is odd), the code inside theelse
block will be executed.std::cout << "The number is odd." << std::endl;
: This line prints the message "The number is odd." to the console if the condition in theif
statement is false.return 0;
: This statement ends themain
function and returns 0 to the operating system, indicating successful execution of the program.