val % 2

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
}
That's just an alternative format for "if()" statements. This is the equivalent to:
1
2
3
4
if(val % 2)
{
      res = "odd";
}


'res' being variable name for the std::string that you declared on Line 10.
Okay, so what about the (val %2). How does this catch "odd" numbers. If i put in
if val = 5, the results would be

if (5%2)
{
res = "odd"
}

How does this catch odd numbers?
Last edited on
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.
Topic archived. No new replies allowed.