5. if and for Statements
So far we have been using a computer as nothing more but an advanced calculator. As you already know, computers are far more versatile than calculators are. This chapter will demonstrate the ability of computers to perform conditional execution, which is one of the things calculators usually cannot do.
Let us start out by writing a program that will read in one number from standard input and print out a message telling us whether the given number is positive or not. A message in question could be "This number is positive" or "This number is not positive".
A mechanism called conditional execution
can be used to select the message to be printed out. In the C++ language there
is a special statement for performing conditional execution: the if
statement. Here is a program that performs the required task by employing an if
statement:
#include <iostream> using namespace std; int main() { double number=0; cout << "Type in a number: "; cin >> number; if (number > 0) cout << "This number is positive!" << endl; else cout << "This number is not positive!" << endl; }
When this program is run (that is, when started), the user is asked to input a number first. Then, the program will print out a message telling whether the number typed in is positive or not.
Type in this program into your IDE and execute it at least two times! Try it by inputting a positive number and then by inputting a negative number. |
This example has shown that by using
an if
statement we can control whether some statements get executed or
not, depending on the given condition. An if
statement is executed in the
following manner: first, a condition following the word if
inside
parentheses (i.e. round brackets) is checked. If the condition is true, then
the immediately following statement is executed. On the other hand, if the
condition is false, then the immediately following statement is not executed,
but the statement following the word else
is executed.
We can also say that an if
statement controls whether the given sub-statements will be executed or not. In
our program, there are two cout
sub-statements. Only the sub-statements should be terminated by semicolons.
An if
statement is not required to have an else
part. What this means is that an
if
statement can take any of these two shapes:
if (<condition>) <action> | if (<condition>) <action> else <alternative_action> |
where <action>
can be either a
statement or a statement block and
<alternative_action>
can be either a statement or a statement block, too.
To give you an example of an if
statement controlling the execution of statement blocks, we will slightly
modify the previous program:
if (number > 0) { cout << "This number is positive!" << endl; cout << "In other words, it is greater than 0." << endl; } else cout << "This number is not positive!" << endl;
The action part of this if
statement is a statement block: in case you have forgotten, a statement block
is a sequence of statements enclosed by a pair of braces (i.e. curly brackets).
Therefore, should the condition of this if
statement be true, the entire statement
block will get executed.
With this in mind, let us move up a notch and solve a slightly harder problem now. Instead of checking whether a number is positive or negative, let us check whether a given number is between 10 and 20. Clearly, such a number has to satisfy two requirements: firstly, that it is greater than 10, and secondly, that it is less than 20.
Using conventional mathematical notation we could write both of these conditions like this:
10 < number < 20
Unfortunately, a condition like this will not work correctly in C++.
So, we have to separately state both conditions and then conflate them into a bigger, compound condition
using a logical operator called 'and'. There is nothing really mysterious about
this operator 'and': it joins two conditions into a bigger one. In C++, this
operator 'and' is written using two identical symbols, as '&&
'.
For demonstration, here is an if
statement checking whether a given
number is between 10 and 20:
if (number>10 && number<20) cout << "This number is between 10 and 20!" << endl; else cout << "This number is not between 10 and 20!" << endl;
You can read the condition inside
this if
statement as: "If number
is greater than 10 and number
is less than 20". The operator 'and' produces truth only when
both conditions it is joining are true.
Another frequently used logical operator in
C++ is the operator 'or', written as two vertical lines (||
). The
operator 'or' produces truth when either one of conditions it is joining is
true.
We present you with a program that demonstrates how these logical operators may be used:
#include <iostream> using namespace std; int main() { double dayOfWeek=0; cout << "Type in an ordinal number of a day of the week (1-7): "; cin >> dayOfWeek; if (dayOfWeek>5 && dayOfWeek<8) cout << "Great, it's weekend!" << endl; else cout << "We're in the working part of the week!" << endl; if (dayOfWeek==5) { cout << "It's Friday!" << endl; cout << "The weekend starts tomorrow!" << endl; } if (dayOfWeek<1 || dayOfWeek>7) cout << "You've typed in an invalid number!" << endl; if (dayOfWeek!=7) { cout << "Today is not Sunday." << endl; cout << "There are still " << 7-dayOfWeek << " days remaining till the end of the week." << endl; } else { cout << "It's Sunday." << endl; cout << "Tomorrow is Monday." << endl; } }
Type in this program in your IDE and execute it several times in order to fully test out its functionality for different days of the week.
Here is an example of what you might get by running this program:
Type in an ordinal number of a day of the week (1-7): 5 We're in the working part of the week! It's Friday! The weekend starts tomorrow! Today is not Sunday. There are still 2 days remaining till the end of the week.
Let us now analyze this program step by step:
if (dayOfWeek>5 && dayOfWeek<8)
The condition of this if
statement checks whether dayOfWeek
is during weekend by
testing if dayOfWeek
is greater than 5 and less than 8, using the logical operator
'and'.
if (dayOfWeek==5) { cout << "It's Friday!" << endl; cout << "The weekend starts tomorrow!" << endl; }
The condition of this if
statement tests whether dayOfWeek
is Friday by testing whether dayOfWeek
equals 5. Once again, here we have a case where an if
statement controls the execution of the following statement block. Also, note
that this if
statement is not followed by an else
part.
In the C++ language, to test equality you must use two consecutive symbols for equality (== ). The authors of the language have chosen this somewhat unusual manner of checking for equality since the single equals symbol had already been used up for the assignment operation!
|
if (dayOfWeek<1 || dayOfWeek>7) cout << "You've typed in an invalid number!" << endl;
In order to make this program easier to understand we had to make some sacrifices: for example, this program will not work perfectly if you decide to be mischievous and type in a number less than 1 or greater than 7.
This statement contains a compound condition created by using a logical
operator 'or'. You can read this if
statement as: "If the day of
the week is less than 1 or greater than 7"
if (dayOfWeek!=7)
This statement checks whether the given day
of the week is not Sunday. '!=
' is an operator that tests for inequality, which is the exact
opposite of the operator '==
' which tests for equality. You can read this statement as: "If
the day of the week is different from 7"