I need explanation on the code snippet

I succeeded in converting a C# sharp function to C++ and the code executed successfully. I however can't seem to understand and explain the block of code below especially the initialization of 'a' and 'n' and also the nested if constructs.



int isEvens(int n)
{
int a = n % 10;
n = n / 10;
if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8)
{
if (n == 0)
{
return 1;
}
else
{
return isEvens(n);
}
}
else
{
return 0;
Please edit your post to include code tags (the <> format on the right).

You're also missing some }.
Thanks for your response salem c. I will do that ASAP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int isEvens(int n)
{
int a = n % 10;
n = n / 10;
if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8)
{
if (n == 0)
{
return 1;
}
else
{
return isEvens(n);
}
    }
else
{
       return 0;
}
}
It's also nice to have some indentation as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int isEvens(int n)
{
  int a = n % 10;
  n = n / 10;
  if (a == 0 || a == 2 || a == 4 || a == 6 || a == 8) {
    if (n == 0) {
      return 1;
    } else {
      return isEvens(n);
    }
  } else {
    return 0;
  }
}


> int a = n % 10;
> n = n / 10;
Well if your input number is 1234, then a is 4, and n becomes 123.

Recall that in C, integer division truncates towards zero.

The recursive function is basically examining each digit of your number.
It actually determines whether all digits are even.

Note that % is modulus, i.e. it returns the remainder.
More ways to express the same:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool isAllEven( int n )
{
  const int last = n % 10;
  const int rest = n / 10;
  if ( last % 2 ) {
    // digit is odd
    return false;
  } else {
    // is even
    if ( rest == 0 ) {
      // ... and the "first" digit
      return true;
    } else {
      return isAllEven( rest );
    }
  }
}


1
2
3
4
5
6
7
8
9
10
11
bool isAllEven( int n )
{
  while ( n ) {
    const int last = n % 10;
    if ( last % 2 ) {
      return false;
    }
    n = n / 10;
  }
  return true;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

bool isAllEvens( int n )
{
   return to_string( n ).find_first_not_of( "-02468" ) == string::npos;
}


int main()
{
   for ( int n : { -987, -444, 0, 124, 666, 999, 2048 } ) cout << n << '\t' << boolalpha << isAllEvens( n ) << '\n';
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

bool isEvens( int n )
{
   return n % 2 ? 0 : !n || isEvens( n / 10 );
}


int main()
{
   for ( int n : { -987, -444, 0, 124, 666, 999, 2048 } ) cout << n << '\t' << boolalpha << isEvens( n ) << '\n';

}
Last edited on
You're allocating memory to check if an integer has any odd decimal digits?
Topic archived. No new replies allowed.