Hi,
If the user enters 5, then the function returns
false
. That is, it
will return false, not
maybe. On line 13 the expression in the
if
statement becomes false, so the execution jumps to line 15, and line 16 produces the output.
Not sure what you mean by the concept of "connected". C++ code consists of statements and expressions. There are various type of statements, but here we are dealing with a function call and two
if
else
statement. An expression evaluates to a value. With an if statement, the expression
number % 2 == 0
is a
conditional expression, that is, it
evaluates to the
concept of true
or
false
, which is the 1 or zero
arbwok mentioned. Technically, zero is
false
,
any other value is
true
. If the expression is true, the code immediately after the if statement (and before the
else if
, or an
else
). Otherwise, if there is an
else if
statement, it's condition is checked, and it's code in the braces is executed. If none of the
else if
statements are true, then the
else
statements are executed.
When line 27 is encountered, that value
replaces the expression in the if statement on line 13. That is what
return
means
One thing I would change with the code:You call the function with the
argument val
, but the function receives a
parameter number
. I like to name them something similar, so it's obvious they are the same thing, or more accurately they have the same value.
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 36 37 38 39
|
#include <iostream>
using namespace std; // this is ok for now, but not recommended
// function declaration
bool isEven(int number); // It's easier to understand if the parameters have
// identifiers ( a name for the variable)
// we don't have to have const here,
// but apart from that, the function declaration and definition have to be the same
int main()
{
int number = 9999; //always initialise to something, even though we get input straight away
cout << "Enter an integer and I will tell you if it is even or odd: \n";
cin >> number;
if (isEven(number)) // calling the function "isEven", with argument number
// the return value determines what happens next
{ //always use braces, even if there is only 1 statement
cout << val << " is even.\n"; // if true this line is executed
}
else {
cout << val << " is odd.\n"; // if false, this line is executed instead
}
}
// function definition
bool isEven(const int number) // number is the parameter, a copy of the argument. It's const because we are not
// going to change it in the function
{
bool status = false; // always initialise to something
if (number % 2 == 0) { // conditional expression evaluated
status = true;
}
else {
status = false;
}
return status;
}
|
Good Luck !!