Monday, September 29, 2008

Control Structure

A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done to perform our program.

With the introduction of control sequences we are going to have to introduce a new concept: the block of instructions. A block of instructions is a group of instructions separated by semicolons (;) but grouped in a block delimited by curly bracket signs: { and }.

Most of the control structures that we will see in this section allow a generic statement as a parameter, this refers to either a single instruction or a block of instructions, as we want. If we want the statement to be a single instruction we do not need to enclose it between curly-brackets ({}). If we want the statement to be more than a single instruction we must enclose them between curly brackets ({}) forming a block of instructions.

Conditional structure: if and else

It is used to execute an instruction or block of instructions 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 on the next instruction after the conditional structure.

For example, the following code fragment prints out x is 100 only if the value stored in variable x is indeed 100:

if (x == 100)
cout << "x is 100";

If we want more than a single instruction to be executed in case that condition is true we can specify a block of instructions using curly brackets { }:

if (x == 100)
{
cout << "x is ";
cout << x;
}

We can additionally specify what we want that happens 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 out on the screen x is 100 if indeed x is worth 100, but if it is 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 present value stored in x is positive, negative or none of the previous, that is to say, equal to 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 we want more than a single instruction to be executed, we must group them in a block of instructions by using curly brackets { }.



Source : Cplusplus.com

No comments: