Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

* Complete the recursive function even() that returns true when a number is even

ID: 3722617 • Letter: #

Question

* Complete the recursive function even() that returns true when a number is
even.
* Do not use %
* Compile and run exercise3.cpp

Below is the code, you simply have to fill in where it states to fill in the code. After the answer I would appreciate an explanation of some kind as I am struggling to grasp these concepts.

#include <iostream>

#include <stdexcept>

using namespace std;

bool even(int n){

if(n == 0){

/* CODE HERE */

}

if(n == 1){

/* CODE HERE */

}

if(n < 0){

/* CODE HERE */

}

else{

/* CODE HERE */

}

}

int main(){

int n[] = {0, 1, 3, 4, -7, -100};

int length = sizeof(n) / sizeof(*n);

  

for(int i = 0; i < length; i++){

try{

cout << "even(" << n[i] << ") = ";

cout << (even(n[i]) ? "true" : "false") << endl;

}

catch(exception& e){

cout << endl;

cout << "Error: " << e.what() << endl;

}

}

return 0;

}

Explanation / Answer

#include <iostream>

#include <stdexcept>

using namespace std;

// if n&1 == 1 then it is an odd number

// else it is an even number

bool even(int n){

if(n == 0){
/* CODE HERE */
return true;
}

if(n == 1){

/* CODE HERE */
return false;

}

if(n < 0){

/* CODE HERE */
return even(n&1);

}

else{

/* CODE HERE */
return even(n&1);
  
}

}

int main(){

int n[] = {0, 1, 3, 4, -7, -100};

int length = sizeof(n) / sizeof(*n);

  

for(int i = 0; i < length; i++){

try{

cout << "even(" << n[i] << ") = ";

cout << (even(n[i]) ? "true" : "false") << endl;
  
}

catch(exception& e){

cout << endl;

cout << "Error: " << e.what() << endl;

}

}

return 0;

}