C++ Example - Check Odd or Even
Below we use % to determine whether a number is odd or even: the principle is that dividing the number by 2 gives a remainder of 0 for even numbers, 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
<<
"
is even.
"
;
else
cout
<<
n
<<
"
is odd.
"
;
return
0
;
}
The output of the above program 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
<<
"
is even.
"
:
cout
<<
n
<<
"
is odd.
"
;
return
0
;
}
The output of the above program is:
输入一个整数: 5
5 为奇数。
C++ Example