Sunday, 5 May 2013

Conditional structure: if and else

The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement
Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is
false, statement is ignored (not executed) and the program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:
if (x == 100)
cout << "x is 100";
If we want more than a single statement to be executed in case that the condition is true we can specify a block
using braces { }:
if (x == 100)
{
cout << "x is ";
cout << x;
}
We can additionally specify what we want to happen if the condition is not fulfilled by using the keyword else. Its
form used in conjunction with if is:
if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and only if not- it prints out x is
not 100.
The if + else structures can be concatenated with the intention of verifying a range of values. The following
example shows its use telling if the value currently stored in x is positive, negative or none of them (i.e. zero):
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
Remember that in case that we want more than a single statement to be executed, we must group them in a block
by enclosing them in braces { }.

No comments:

Post a Comment