C++ Example - Determine whether a number is odd or even

C++ Examples

Below we use % to determine whether a number is odd or even. The principle is: divide the number by 2; if the remainder is 0, it is even; otherwise, it is odd.

Example - Using if...else

#include <iostream> using namespace std; int main() { int n; cout << "Enter an integer:"; cin >> n; if ( n % 2 == 0) cout << n << "It is even."; else cout << n << "It is odd."; return 0; }

The output of the above program execution is:

输入一个整数: 5
5 为奇数。

Example - Using the ternary operator

#include <iostream> using namespace std; int main() { int n; cout << "Enter an integer:"; cin >> n; (n % 2 == 0) ? cout << n << "It is even." : cout << n << "It is odd."; return 0; }

The output of the above program execution is:

输入一个整数: 5
5 为奇数。

C++ Examples

other extensions