Hello,
I am working through the "Programming Principles and Practice Using C++", and have come across some confusion about the following code concerning the "modulo" operation. I know that in the simplest form the modulus operation reveals the remainder of integer division. So, 5%2 yields a remainder of 1. What I do not understand is:
(val%2) res = "odd"
What does the above code mean, and how does it indicate an odd number? I know that an odd integer divided by 2 will yield a 1. But how does this statement condition anything. Would it not make more sense to say: if (val%2 > 0) res="odd";
[code]
#include "std_lib_facilities.h"
int main()
try
{
int val = 0;
cout << "Please enter an integer: ";
cin >> val;;
if (!cin) error("something went bad with the read");
string res = "even";
if (val%2) res = "odd"; // a number is even if it is 0 modulo 2 and odd otherwise
cout << "The value " << val << " is an " << res << " number\n";
keep_window_open(); // For some Windows(tm) setups
}
Expression within the parenthesis of if is a conditional. Conditional's type is bool. It is either true or false.
Expression 5%2 returns an integer. There is an implicit conversion from integer into bool. Integer value 0 converts to false. All other values convert to true.