### Optimization?

My code is:
 ``1234567891011121314151617181920212223242526272829303132333435`` ``````//Title: Set6Exercises //Author: MacLeight //Date: 21 October 2012 //Write a function called OddCheck that takes one integer as an argument. //The function should return a 1 if the number is odd and a 0 if it is even. #include using namespace std; int OddCheck ( int iNum ) { int iCheck = iNum % 2; if (iCheck == 0) iCheck = 0; else if (iCheck != 0) iCheck = 1; return iCheck; } int main (void) { int iNum = 0; cout << "Enter a number to check." << endl; cin >> iNum; cout << OddCheck (iNum) << endl; return 1; }``````

Is there a better way? More concise, easier to read, anything?

Thanks!
 ``1234`` ``````bool OddCheck ( int iNum ) { return iNum % 2; }``````

This returns 0 (false) if iNum is even (4%2 = 0 ==> false) and 1 (true) otherwise. Maybe rename the function to be more clear (is_odd, IsOdd, isodd)
Last edited on
Indeed, the second part of this exercise was to use a boolean string. What i wrote before reading your response was:

 ``12345678910`` ``````bool OddCheck ( int iNum ) { bool iCheck = iNum % 2; if (iCheck == false) iCheck = 0; else if (iCheck == true) iCheck = 1; return iCheck;``````

But yours is better. Thanks!

You're welcome

Extra tip: you should note that your IFs are redundant. false and true just mean 0 and 1. So you're checking

 ``12`` ``````if(iCheck == 0) iCheck = 0;``````

but if iCheck is already 0 there's no need to reset it to 0
Topic archived. No new replies allowed.