Conditional Statement (if...else
)
In programming, the conditional statement is responsible for the selection. The conditional statement allows you to change the execution of a program depending on the input data.
General view of the conditional operator
if ( condition ) // header if...else statement
{
... // block "if" - operators that are executed,
// if the condition in the header is true
}
else
{
... // block "else" - operators that are executed,
// if the condition in brackets is false
}
Rules of C++ Program Design (code style)
There is no uniform requirement for the placement of curly braces. The opening curly bracket can be placed on the same line as the operator. It is possible to form the operator as follows, which will not affect the result of program execution in any way.
if ( condition ) {
...
}
else {
...
}
To improve the readability of the code, we will use the Allman's style, where the opening curly bracket is placed on a new line and the closing one also on a new line, so that it is below the opening one.
Operators within curly brackets
{}
are written in this case with a shift of 4 spaces to the right (2 spaces are better for large nesting) relative to the curly brackets to make it easier to read and understand the program code.
How the Conditional Statement Works (if...else
)
If the condition is true |
If the condition is false |
|
|
If the logical condition after the if is true , then
- the code inside {} after if is executed
- the code inside {} after else is skipped |
If the logical condition after the if is false , then
- the code inside {} after if is skipped
- the code inside {} after else is executed |
Remember!
1.
if ... else
-
it's one operator! Therefore, no other operators can be between the bracket ending the "
if
" block (
}
) and the
else
.
2. There is never a condition after the word
else
. A condition is placed only after the word
if
. The
else
block is executed when the condition after the
if
is
false
.
3. If there is only one operator in the
if
block or in the
else
block, the curly brackets can be omitted.
4.
A condition is an expression to which we can say whether it is true
(i.e., satisfied) or false
(i.e., not satisfied).
The condition uses signs of logical operators:
Operator |
Meaning |
Example |
== |
Is Equal To |
8 == 7 is false |
!= |
Not Equal To |
8 != 7 is true |
> |
Greater Than |
8 > 7 is true |
< |
Less Than |
8 < 7 is false |
>= |
Greater Than or Equal To |
8 >= 7 is true |
<= |
Less Than or Equal To |
8 <= 5 is false |
5.
In the programming C++, any number not equal to zero is a true
condition, and zero is a false
condition.