Understanding Control Structures in C++
Understanding Control Structures in C++
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 by our program, when and under which circumstances.
With the introduction of control structures we are going to have to introduce a new concept: the compound-statement or block. A block is a group of statements which are
separated by semicolons (;) like all C++ statements, but grouped together in a block enclosed in braces: { }:
Most of the control structures that we will see in this section require a generic statement as part of its syntax. A statement can be either a simple statement (a simple
instruction ending with a semicolon) or a compound statement (several instructions grouped in a block), like the one just described. In the case that we want the statement
to be a simple statement, we do not need to enclose it in braces ({}). But in the case that we want the statement to be a compound statement it must be enclosed between
braces ({}), forming a block.
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:
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 { }.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a
common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes
method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle
has already stopped.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
[Link]("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
The following switch statement contains several case clauses and one default clause. Each clause contains a function call and a break statement. The break statements
prevent control from passing down through each statement in the switch body.
If the switch expression evaluated to '/', the switch statement would call the function divide. Control would then pass to the statement following the switch body.
char key;
case '*':
printf("Enter an arithmetic operator\n"); multiply();
scanf("%c",&key); break;
If the switch expression matches a case expression, the statements following the case expression are processed until a break statement is encountered or the end of the
switch body is reached. In the following example, break statements are not present. If the value of text[i] is equal to 'A', all three counters are incremented. If the value of
text[i] is equal to 'a', lettera and total are increased. Only total is increased if text[i] is not equal to 'A' or 'a'.
char text[100]; case 'A':
int capa, lettera, total; capa++;
case 'a':
// ... lettera++;
default:
for (i=0; i<sizeof(text); i++) { total++;
}
switch (text[i]) }
{
The following switch statement performs the same statements for more than one case label:
/**
** This example contains a switch statement that performs
** the same statement for more than one case label.
**/
In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different
computations or actions depending on whether a programmer-specified condition evaluates to true or false (see boolean datatype). Apart from the case of branch
predication, this is always achieved by selectively altering the control flow based on some condition.
In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or
"conditional construct" are preferred, because these terms all have distinct meanings.
If-Then(-Else)
The if-then construct (sometimes called if-then-else) is common across many programming languages. Although the syntax varies quite a bit from language to language,
the basic structure (in pseudocode form) looks like this:
If (condition) Then
(statements)
Else
(statements)
End If
When an interpreter finds an If, it expects a boolean condition - for example, x > 0, which means "the variable x contains a number that is greater than zero" - and
evaluates that condition. If the condition is true, the statement block following the Then is executed. Otherwise, the execution continues in the following block - either in
the Else block (which is usually optional), or if there is no Else block, then after the End If.
After either the block after the Then or the block after the Else has been executed, control returns to the point after the End If.
In early programming languages - and in particular, in some dialects of BASIC in the 1980s - an if-then statement could only contain GOTO statements. This led to a hard-
to-read style of programming known as spaghetti programming. As a result, structured programming, which allowed (virtually) arbitrary statements to be put in statement
blocks inside an if statement, gained in popularity, until it became the norm.
Else If parts
By using Else If, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other
statements will be skipped. The statements of the final Else will be executed if none of the conditions are true. This example is written in the Ada programming language:
If expressions
Many languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not
statements (which just perform an action).
As a ternary operator
In C and C-like languages conditional expressions take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:
This means that conditions can be inlined into expressions, unlike with if statements, as shown here using C syntax:
//Invalid
my_variable = if(x > 10) { "foo" } else { "bar" };
//Valid
my_variable = (x > 10)?"foo":"bar";
To accomplish the same as the second (correct) line above, using a standard if/else statement, this would take more than one line of code (under standard layout
conventions):
if (x > 10) {
my_variable = 'foo';
}
else {
my_variable = 'bar';
}
Switch statements (in some languages, case statements) compare a given value with specified constants and take action according to the first constant to match. The
example on the left is written in Pascal, and the example on the right is written in C.
Pascal: C:
switch (someChar) {
case someChar of case 'a': actionOnA; break;
'a': actionOnA; case 'x': actionOnX; break;
'x': actionOnX; case 'y':
'y','z':actionOnYandZ; case 'z': actionOnYandZ; break;
end; default: actionOnNoMatch;
}
Conditional Statement Syntax
This section describes the syntax of conditional statements used by the MsiEvaluateCondition function and the action sequence tables. For more information, see,
Examples of Conditional Statement Syntax.
Item Syntax
value symbol | literal | integer
comparison-
< | > | <= | >= | = | <>
operator
term value | value comparison-operator value | ( expression )|
Access Prefixes Operator Meaning
>< TRUE if left string contains the right string.
<< TRUE if left string starts with the right string.
The following table shows the prefixes to use to access >> TRUE if left string ends with the right string.
various system and installer information for use in
conditional expressions. Bitwise Numeric Operators
Symbol type Prefix Value The following table shows the bitwise numeric
Installer property (none) Value of property (Property) table.
Environment variable % Value of environment variable.
operators in conditional expressions. These operators
Component table key $ Action state of the component. can occur between two integer values.
Component table key ? Installed state of the component.
Feature table key & Action state of the feature. Operator Meaning
Feature table key ! Installed state of the feature. Bitwise AND, TRUE if the left and right integers have any bits in
><
common.
Logical Operators << True if the high 16-bits of the left integer are equal to the right integer.
>> True if the low 16-bits of the left integer are equal to the right integer.
The following table shows the logical operators in Feature and Component State Values
conditional expressions, in order of high-to-low
precedence. The following table shows where it is valid to use the
feature and component operator symbols.
Operator Meaning
Not Prefix unary operator; inverts state of following term.
And TRUE if both terms are TRUE. Operator <state> Where this syntax is valid
Or TRUE if either or both terms are TRUE. $component- In the Condition table, and in the sequence tables, after the
action CostFinalize action.
Xor TRUE if either but not both terms are TRUE.
In the Condition table, and in the sequence tables, after the
Eqv TRUE if both terms are TRUE or both terms are FALSE. &feature-action
CostFinalize action.
Imp TRUE if left term is FALSE or right term is TRUE.
In the Condition table, and in the sequence tables, after the
!feature-state
CostFinalize action.
Comparative Operators In the Condition table, and in the sequence tables, after the
?component-state
CostFinalize action.
The following table shows the comparison operators
The following table shows the feature and component state values used in
used in conditional expressions. These comparison conditional expressions. These states are not set until MsiSetInstallLevel is called,
operators can only occur between two values. either directly or by the CostFinalize action.
Operator Meaning State Value Meaning
= TRUE if left value is equal to right value. No action to be taken on the feature or
<> TRUE if left value is not equal to right value. INSTALLSTATE_UNKNOWN -1
component.
> TRUE if left value is greater than right value. Advertised feature. This state is not
INSTALLSTATE_ADVERTISED 1
>= TRUE if left value is greater than or equal to right value. available for components.
< TRUE if left value is less than right value. INSTALLSTATE_ABSENT 2 Feature or component is not present.
<= TRUE if left value is less than or equal to right value. Feature or component on the local
INSTALLSTATE_LOCAL 3
computer.
Substring Operators Feature or component run from the
INSTALLSTATE_SOURCE 4
source.
For example, the conditional expression "&MyFeature=3" evaluates to True only if MyFeature is changing from its current state to the state of being installed on the local
computer, INSTALLSTATE_LOCAL.
Note that you should not depend upon the condition $Component1=3 to check whether Component1 is locally installed on the computer. This can fail if Component1 is
installed by more than one product. After Component1 has been installed locally by Product1, the installer evaluates the condition $Component1=3 as False during the
installation of Product2. This is because the installer determines the version of the component using the component's key path and marks the component for installation if
its version is greater than or equal to the installed component.
if(Condition) Statement;- If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:
Otherwise: if…else -The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can
use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer
an alternate statement in case the user provides another answer.
The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:
Therefore, the program will examine a Condition. This condition can be a simple expression or a combination of expressions. If the Condition is true, then the program
will execute the Statement.
There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:
If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if
the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. Here is an example:
The center of any imperative programming language is control structures. Although Perl is not purely an imperative programming language, it has ancestors that are very
much imperative in nature, and thus Perl has inherited those same control structures. It also has added a few of its own.
As you begin to learn about Perl's control structures, realize that a good number of them are syntactic sugar. You can survive using only a subset of all the control
structures that are available in Perl. You should use those with which you are comfortable. Obey the "hubris" of Perl, and write code that is readable. But, beyond that, do
not use any control structures that you do not think you need.
Blocks
The first tool that you need to begin to use control structures is the ability to write code "blocks". A block of code could be any of the code examples that we have seen
thus far. The only difference is, to make them a block, we would surround them with {}.
Anything that looks like that is a block. Blocks are very simple, and are much like code blocks in languages like C, C++, and Java. However, in Perl, code blocks are
decoupled from any particular control structure. The above code example is a valid piece of Perl code that can appear just about anywhere in a Perl program. Of course, it
is only particularly useful for those functions and structures that use blocks.
Note that any variable declared in the block (in the example, $var) lives only until the end of that block. With variables declared my, normal lexical scoping that you are
familiar with in C, C++, or Java applies.
Nested if Statement - the if statement may itself contain another if statement is known as nested if statement.
Syntax: if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;
The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true. Condition 1 is tested first and then
condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to
the corresponding else statement.
Sample Code
1. #include <stdio.h> //includes the stdio.h file to your program 6. scanf ("%d %d %d", &a, &b, &c) //Read variables a,b,c,
2. main () //start of main function
3. { 7. if (a > b) // check whether a is greater than b if true then
4. int a,b,c,big //declaration of variables 8. if (a > c) // check whether a is greater than c
9. big = a // assign a to big
5. printf ("Enter three numbers") //message to the user
10. else big = c // assign c to big 13. else big = c // assign c to big
11. else if (b > c) // if the condition (a > b) fails check whether b is 14. printf ("Largest of %d, %d & %d = %d", a,b,c,big) //print the
greater than c given numbers along with the largest number
12. big = b // assign b to big
15. }
In the above program the statement if (a>c) is nested within the if (a>b). If the first If condition if (a>b)
If (a>b) is true only then the second if statement if (a>b) is executed. If the first if condition is executed to be false then the program control shifts to the statement after
corresponding else statement.
Sample Code
1. #include <stdio.h> //Includes stdio.h file to your program 10. rem_100 = year % 100 //find the remainder of year by 100
2. void main () // start of the program
3. { 11. rem_400 = year % 400 //find the remainder of year by 400
4. int year, rem_4, rem_100, rem_400 // variable declaration
12. if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0)
5.
6. printf ("Enter the year to be tested") // message for user 13. //apply if condition 5 check whether remainder is zero
14. printf ("It is a leap year. \n") // print true condition
7. scanf ("%d", &year) // Read the year from standard input.
15. else
8. 16. printf ("No. It is not a leap year. \n") //print the false condition
9. rem_4 = year % 4 //find the remainder of year by 4
17. }
The If else construct: The syntax of the If else construct is as follows:-
The if else is actually just on extension of the general format of if statement. If the result of the condition is true, then program statement 1 is executed, otherwise program
statement 2 will be executed. If any case either program statement 1 is executed or program statement 2 is executed but not both when writing programs this else statement is
so frequently required that almost all programming languages provide a special construct to handle this situation.
1. #include <stdio.h> //include the stdio.h header file in your program 7. if (num < 0) // check whether number is less than zero
2. void main () // start of the main 8. printf ("The number is negative") // if it is less than zero then it is
3. { negative
4. int num // declare variable num as integer
9. else // else statement
5. printf ("Enter the number") // message to the user 10. printf ("The number is positive") // if it is more than zero then the
given number is positive
6. scanf ("%d", &num) // read the input number from keyboard
11. }
if Statement: - The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow of program
execution.
if (condition)
statement;
The statement is any valid C’ language statement and the condition is any valid C’ language expression, frequently logical operators are used in the condition statement.
The condition part should not end with a semicolon, since the condition and statement should be put together as a single statement. The command says if the condition is
true then perform the following statement or If the condition is fake the computer skips the statement and moves on to the next instruction in the program.
Example program
1. # include <stdio.h> //Include the stdio.h file 6. scanf ("%d", &number) // read the number from standard input
2. void main () // start of the program
3. { 7. if (number < 0) // check whether the number is a negative number
4. int numbers // declare the variables 8. number = -number // if it is negative then convert it into positive
The above program checks the value of the input number to see if it is less than zero. If it is then the following program statement which negates the value of the number is
executed. If the value of the number is not less than zero, we do not want to negate it then this statement is automatically skipped. The absolute number is then displayed
by the program, and program execution ends.
Most of the programming languages use control structures to control the flow of a program. The control structures include decision-making and loops. Decision-making is
done by applying different conditions in the program. If the conditions are true, the statements following the condition are executed. The values in a condition are
compared by using the comparison operators. The loops are used to run a set of statements several times until a condition is met. If the condition is true, the loop is
executed. If the condition becomes false, the loop is terminated and the control passes to the next statement that follows the loop block.