if(expression) statement; else statement;
First let's look at the expression.
C++ expressions
In control structures, an expression is anything that evaluates to either
true or false. As we have seen, there are two definitions of truth and
false. The first and older one is that 0 (zero) is false and any non-zero
integer is true. The other one is the use of bool variables which have
the values true or false. The integer definition is more
flexible and is used in many ways. So we will look at that in more detail.
We have seen that the assignment operator has a value. If you have the
expression, a=b, then the value of the expression is b. In an
if statement,
if(a=b) cout << "true";
will print true if the value of the expression is true. Since the value
of a=b is the value of b, this expression is true if b is non-zero. The
fact about assignment is used often in C++ to set a value and check it
at the same time. A simple example is to save the value of an expression
and check the value. If we subtract one variable from another, we can save
the value and do something special.
if( (c=a-b) > 1)
cout << "a and b are more than
one apart" << c << endl;
The expression part subtracts b from a and copies the value to c. Since the value of the assignment is the right hand side, we then check the value stored in c with 1 and if it is greater than 1, we print the message.
There are a number of comparison operators in C++
Operator | Meaning |
= | assignment |
== | comparison |
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to> |
!= | not equal |
These all assume that the values being compared are
integers or floats or can be treated as a number. There are also a number
of logical operators.
Operator | Meaning |
&& | and |
|| (2 vertical bar characters) | or |
! (exclamation point) | not |
These can be combined in many ways.
int a, b,c;
if ( (a < 6) && (b > 7) )
cout << "case 1 " << endl;
if ( (a < 6) || (b < 7) )
cout << "case 2 " << endl;
if ( ( (a < 6) && (b < 7 ) || ( (c -b < a) &&
!c ) )
cout << "case 3 " << endl;
It is important to remember that in these cases,
we use the fact that zero is false and anything else is true. Typically
the value of a comparison operator is either 0 or 1.
Also be careful, there is a big difference between
&& and &.
The single ampersand means do a bit wise logical and.
It is important to be careful about the use of the
braces in an if statement. First a little general discussion of scoping
and code blocks and then some if statement problems.
Scoping and code blocks
Variables in computer languages can have their visibility controlled. If you imagine a program as a room, variables and other objects can be seen from some parts of the room and not others. There are two general kinds of scoping, local and global. Consider this little program.
int real_global;
int main() {
int pretty_global;
}
The variable real_global is visible, that means it can be read or written from all parts of the program. The variable pretty_global can only be used inside the main function. For now, this is the same thing. We will see later that these are different. C++ allows the user to create variables inside any code block. A code block is any group of statements between two curly braces {}. Variables created inside a code block are local to that code block and are not visible outside it.
Now some if statement problems. Consider this if statement.
if(a<b)
if(a == b)
cout << "a
== b" << endl;
else
cout << " a > b" << endl;
cout << "all done" << endl;
What does this do if a = 3 and b = 4?
It prints
a > b.
all done
This is because the else is attached to the closest if and indentation
and white space has nothing to do with it.
Now, what if a = 4 and b = 3? It prints
all done.
This is because if there are no braces, then there is only one statement that is part of the block after the if or the else. To fix this, we use braces to make it clear to the compiler what we mean. This is like using parenthesis to make the meaning of expressions clear.
if(a<b) {
if(a == b)
cout << "a == b" <<
endl;
}
else
cout << " a > b" << endl;
cout << "all done" << endl;
If you want more than one line of code in the statement part of an if statement, use braces. Some people always put braces on both the if and else blocks even if there is only one line. This is because it is common to find you have to add something to one of these blocks as the program development progresses and a common mistake is to just add the statement, forgetting that the compiler doesn't notice the indentation.
Loops
The if statement allows us to choose between two
pieces of code to execute. Some times we want to repeat the same piece
of code several times. These are called loops. The first loop structure
we will look at is the while loop.
The structure looks like
while(expression) statement;
The statement part can be one or more actual statements. So, if there is one statement, it looks like
while (a < b)
cout << a << endl;
If there are several statements
while( a<b) {
cout << a << endl;
a += 3;
} // end while
The evaluation of the expression is done at the top of the loop, so if the expression is false, it won't run the loop even once.
Do loops
These are much like while loops, only the evaluation
is done at the end. The general form is
do statement; while (expression);
The statement is done at least once since we don't check until the bottom of the loop.
For loops
For loops are for running a loop a fixed
number of times. The form is
for(expr; expr2; expr3)statement
The first expression is the initialization. Examples include i=0, int i=6. The second expression is the test expression. If it is true, then we do this time through the loop. The third expression is the increment. It is commonly i++.
Digression
The ++ operator is a unary increment operator. It is a kind of shorthand in C++ for incrementing by one. For example, i++ means the same thing as i=i+1. But it is an expression rather than a statement. There is a subtly to its evaluation that will come up later. There is also a -- operator.
For example,
for(int i=0; i < 10; i++)
cout << i << endl;
This starts by creating an i variable and setting
it to 0. Since 0 < 10, we run the body of the loop and 0 is printed.
Then we do the increment and i becomes 1. We check again and 1 is <
10 so we print 1. and so on. After we print 9, i is incremented to 10.
10 is not less then 10 so we don't do the body of the loop. So this prints
0-9. This loop is equivalent to the while loop
int i = 0;
while (i < 10) {
cout << i << endl;
i++;
} // endwhile
You can leave off parts of the for loop. For example, if we already have a variable counter used for something and now we want to use it a loop variable, we can skip the initialization.
for( ; counter < 20; counter++)
We could also leave off the increment is we were doing different increments
for (; counter < 20;) {
if (counter == 15)
counter *= 2;
else
counter++;
} // end
We can even leave off the comparison if we have another way to exit the loop. We can also combine several loops together This will loop changing i and j at the same time.
for(int i = 0, int j = 10; i< 10, j > 0; i++,j--) {
cout << i << " " << j << endl;
}
Infinite loops
Sometimes you want a loop that runs forever. This
is done differently for different kinds of loops
for(;;) { cout << "forever" << endl;}
while(true) { cout << "forever" << endl;}
do { cout << "forever" << endl;| while(true);
Getting out of a loop
Now that your stuck in a loop, you can get out a
couple of ways. The best way is to do a break. So in a forever loop
while(true) {
if( X < 25) break;
} // endwhile
This will stop if X = 25. This works on the other loops as well.
You can skip to the next iteration by using
the continue statement.
The continue will go back to the top of
the loop. in a while or do, this cause the expression to be evaluated.
In a for loop it causes the increment to be done.