Optimization?

My code is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//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 <iostream>
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!
1
2
3
4
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:

1
2
3
4
5
6
7
8
9
10
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

1
2
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.