Functions

closed account (G3AqfSEw)
I need to define a function is_even that takes an integer argument x and returns the bool value true when x is even and false otherwise. I don't need cout in my code, just return the appropriate value. *using C++
I am stuck and I need help using bool

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int is_even (int x);
bool even = true;
if (x%2==0)
{
   return even;
}
1
2
3
4
bool is_even(const int & x)
{
    return x%2==0 ? true : false;
}
x % 2 == 0 will return a boolean; true if x divides 2 evenly(x is even) or false otherwise(x is odd). Thus,
1
2
3
4
bool is_even( int x )
{
    return x % 2 == 0;
}

is all you need.
Pay attention to the details:
1
2
3
4
5
6
7
8
// this is a declaration:
int is_even (int x);

// this is a definition:
bool is_even( int x )
{
    // body of the function's implementation
}



Your code had:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> // not needed for this function
using namespace std; // not needed for this function

int is_even (int x); // mere declaration

bool even = true; // a global variable

if ( x%2==0 ) // not allowed in global scope
{
   return even;
}
// What if the number is odd?
// Should a function, that promises to return a value, return some value in that case? 
Topic archived. No new replies allowed.