C++ is a popular programming language used for developing various types of software applications. It is a general-purpose programming language and widely used in various domains such as gaming, mobile applications, desktop applications, and more. In this article, we will explore how to check whether a given number is even or odd in C++.
In C++, we can use the modulo operator (%) to check whether a given number is even or odd. The modulo operator returns the remainder of dividing two numbers. If a number is even, then its remainder when divided by 2 is 0, and if it is odd, then its remainder when divided by 2 is 1. We can leverage this property to determine whether a given number is even or odd.
Example Code:
Here is an example code snippet that demonstrates how to check whether a given number is even or odd in C++.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0) {
cout << num << " is even" << endl;
} else {
cout << num << " is odd" << endl;
}
return 0;
}
Example Output
Here is an example output for the above code when the input is 7.
Enter a number: 7
7 is odd
In conclusion, we can use the modulo operator in C++ to check whether a given number is even or odd. This is a simple and effective way to determine the parity of a number. We hope this article has helped you understand how to check even or odd numbers in C++.
70 videos|45 docs|15 tests
|
|
Explore Courses for EmSAT Achieve exam
|