Statements that specify the order in which actions are executed are called control statements. C++ statements in a program execute one after the other in the order they are written (also known as sequential execution) unless there is a direct instruction to act otherwise. All the programs we have used so far included sequential execution which is one of types of control statements. There are however other ways in which a program can execute a statement other than the next in the line. Enabling this to happen is known as transfer of control. Transfer of control includes other two forms of control statements. They include selection statements and repetition statements.
Selection Statements
There are three types of selection statements namely, if, if….else and switch statements.If Selection Statement
The if selection statement perform an action if a set condition is correct but if the condition is false the program skips the action and execution continues with the rest of the statements. An if statement is written with a key if followed by a condition enclosed in braces and then a statement to be executed when the condition is correct. If more than one statements are to be executed, it is advisable to enclose them in curly brackets. Below is an example of an if statement.
#include<iostream> using namespace std; void CurrentAge( int herAge) { if (herAge>=21) { cout<<"At "<<herAge<<" , she is old enough to get married "<<endl; } } int main() { int Age=25; CurrentAge(Age); cout<<"Good enough she has a fiancé"<<endl; } | At 25 , she is old enough to get married Good enough she has a fiancé |
If you change change Age in main to 20 the program will skip execution of CurrentAge() and print directly the next statement "Good enough she has a fiancé".
If...Else Selection Statements
The if...else selection statement makes the program to perform one action if the set condition is correct or to perform another action if the condition is false.
If you notice our example in the if statement above could have been given another option in cases where the age is below 21. The program could have been allowed for example to indicate that the girl is below 21 and therefore not mature enough to get married. In either case, whether above or below 21,the program would tell us the marriage potential of the girl. This is where the if...else comes in handy. The if...else statement is written by stating first the <if>statement followed by an else statement. We will use the example of our girl to print for the condition below 21 as follows;
If you notice our example in the if statement above could have been given another option in cases where the age is below 21. The program could have been allowed for example to indicate that the girl is below 21 and therefore not mature enough to get married. In either case, whether above or below 21,the program would tell us the marriage potential of the girl. This is where the if...else comes in handy. The if...else statement is written by stating first the <if>statement followed by an else statement. We will use the example of our girl to print for the condition below 21 as follows;
#include<iostream> using namespace std; void CurrentAge( int herAge) { if (herAge>=21) { cout<<"At "<<herAge<<", she is old enough to get married "<<endl; } else { cout<<"At"<<herAge<<", she is below 21 and so she is young to get married "<<endl; } } int main() { int Age=20; CurrentAge(Age); cout<<"This is my opion as her parent "<<endl; } | Output Scenario one Age=22 At 22, she is old enough to get married This is my opion as her parent Output Scenario two Age=20 At 20, she is below 21 and so she is young to get married This is my opinion as her parent |
The if and if...else statements can be nested to allow for more checks and control of the program flow. As we saw in the if….else example above, the result of the condition had an interpretation in both ways when false or correct. Many times however you find that there are more possibilities that a condition resulting in yes and no would not be appropriate. Nested if and else statement allow testing various possibilities in a program.
Consider a situation where our girl at 18-20 can still get married but with permission from the parent. Consider also that at 21 and above, she is mature enough to marry with or without permission from her parents. Under these scenarios we have about three conditions to test. One, we need to know if she is below 18 and in that case she is under age for marriage. Secondly, if she is 18 plus but below 21 then she can get married with permission of her parents. Lastly, if is she is 21 plus then she is free to get married with or without the permission. Below is an example of nested if and else statements from these scenarios.
#include<iostream> using namespace std; void CurrentAge( int herAge) { if (herAge>=21) { cout<<"At "<<herAge<<", she is old enough<< to get married "<<endl; } else { if(herAge>=18 && herAge<=20) { cout<<"Yes at "<<herAge<<", she can get married but with permission of her parents "<<endl; } else { cout<<"No at "<<herAge<<", she is so young to get married "<<endl; } } int main() { int Age=17; CurrentAge(Age); cout<<"This is my opinion as her parent "<<endl; } | Output scenario one: Age=25
At 25, she is old enough to get married
This is my opinion as her parent
Output scenario two: Age=20 Yes at 20, she can get married but with permission of her parents This is my opinion as her parent Output scenario three: Age 17 No at 17, she is so young to get married This is my opinion as her parent |
Note the use of curly brackets in the nested else statements. The first else refers to a situation if the first if is false. After the first if condition is determined to be false, then it is time for this else to execute. As it executes two nested condition inside its body are tested. The nested if statements checks whether the girl is in the range of 18 to 20 and then the nested else statement tests for whether the girl is below 18. Blocks are used to ensure that each condition is provided with an appropriate statement to execute. The curly brackets also help the program determine the scope of each condition.
Other Selection Control Statements
Conditional Operator ?:
The conditional operator (?:) is another form of a double selection statement. It also allows for performing one action when a condition is true and another when the condition is false. The conditional operator is a ternary operator because it takes three operands. The first operand is a condition, the second is the action to be performed if the action is true and the third is the action to be performed if the action is false. A full statement of the conditional operator is known as the conditional expression. A conditional expression is written as follows
condition ? Action when true : action when false; |
Using again the example of our girl and talking the possibility that she is mature to get married at 21 plus and young below that age, we can use the conditional expression as follows;
#include<iostream> using namespace std; void CurrentAge( int herAge) { int age=herAge; cout<<"At "<<age<<", she is " <<((age>=21) ? "old enough to marry" : "able to marry if she gets permission of her parents "); } int main() { int Age=18; CurrentAge(Age); cout<<"\nThis is my opinion as her parent "<<endl; } | Output: Age 25
At 25, she is old enough to marry
This is my opinion as her parent
Output: Age 18 At 18, she is able to marry if she gets permission of her parents This is my opinion as her parent |
Please take note of points where the ? and : are placed. Mind also about the use of the quotation marks in the statements to printed if the condition is right or false.
Switch Statement
The switch statement is used for multiple selections in C++. It performs many possible actions holding for a particular condition. With the switch you can perform different actions using a condition for each. The switch statement contains two elements, controlling expression, the case label and default case. switch compares the controlling statement (which can also be an expression) with the case values and then performs an action corresponding with a particular case. The switch statement is written as follows.
switch(controlling expression)
{
case a:
action;
break;
case b:
action;
break;
.
.
.
Default:
Action;
break;
}
After every action a break statement is made to inform the compiler of the end of thecase in question. If the break statement is not including the program will consider all that falls a particular case to be actionable until reaches the end of the switch.
A default case is included to provide for the alternative action in case the program is not able to find a case label that matches with a controlling expression. At times the values provided could fall outside the tested conditions and you want the user the get information relating such a value. In case there is no match and no default case the program will continue to the first statement after the switch without any action and this could lead to unintended outcome.
We use again the example of a girl. If she is 21 she is mature to marry, at 18 she requires the permission of her parents, at 17 she is approaching marriage age but not ready yet and at 15 she is so young to even consider marriage. Our default case is any age not included in our four areas we are testing.
We use again the example of a girl. If she is 21 she is mature to marry, at 18 she requires the permission of her parents, at 17 she is approaching marriage age but not ready yet and at 15 she is so young to even consider marriage. Our default case is any age not included in our four areas we are testing.
#include<iostream> using namespace std; void CurrentAge( int herAge) { int age=herAge; switch (age) { case 21: cout<<"At "<<"age<<", she is old enough to get married "<<"endl; break; case 18: cout<<"Yes at "<<"age<<", she can get married but with permission of her parents "<<"endl; break; case 17: cout<<"Although at "<<age<<" she is approaching 18, still she is not ready for marriage married. "; break; case 15: cout<<"No at "<<age<<", she is so young to get married "<<endl; break; default: cout<<"The age of "<<age<<", cannot be used to determine the status of the girl. "; break; } } int main() { int Age=18; CurrentAge(Age); cout<<"This is my opinion as her parent "<<endl; } | Output: case 21
At 21, she is old enough to get married
This is my opinion as her parent
Output: case 18 Yes at 18, she can get married but with permission of her parents This is my opinion as her parent Output: case 17 Although at 17 she is approaching 18, still she is not ready for marriage married. This is my opinion as her parent Output: case 15 No at 15, she is so young to get married This is my opinion as her parent Output : Default The age of 10, cannot be used to determine the status of the girl. This is my opinion as her parent |
You can include the values included in the outputs to test the program yourself.
Repetition control statements
A repetition statement (or the looping statements or loops) enables the program to repeat an action as long as a particular set condition remains true. Its form goes as follow, “As long as you are at school, I will continue to pay your allowances”. This means that the action of paying you allowances will be done over and over again on condition that you go to school, but if you finish or drop out of school, you will have to fend for yourself. There are three types of repetition (loop) statements. They include the while,do.....while and for loop statementswhile Repetition Statements
The while loop statements allows the program to perform a particular action while a set condition is true. In the case of our going to school example, the while statement can be stated as “while you go to school, I will pay your allowances”. Now this statement gives you the ability to determine how much you will earn while you go to school. Let us assume that going to school begins from nursery through secondary to completing university with a bachelor’s degree. Now consider that years of schooling are 3, 7 , 5 and 3 for nursery, primary, secondary and university education respectively . We also assume that you get your allowances on school term basis which an equivalent of three months. So in all you have 18 years of schooling resulting into 72=(18*12/3) terms for earning your allowances.Let us say that each term you will be paid US$ 100 and this pay will remain constant until the end of the school time. With this information we can use the while loop to calculate for the total allowances you will get during entire school time. A while loop is written as follows
while(condtion) { statements to execute; }
First we need to break down the example. We know the terms you will spend at school (i.e terms=72). And we also know how much you will earn each term (pay=100). So we can use the while statement as follows.
#include<iostream> using namespace std; int totalAllowance(int schoolTerms, int allowances) { int terms=schoolTerms; int pay=allowances ; int totalPay=0; int t=1; // T is a specific term of the 72 while(t<=terms) { totalPay=totalPay+pay; //add the allowance for each term to the total t++; //increament the term by one } return totalPay; } int main() { int terms=72; int pay=100; cout<<"The total allowance for your school time is US$ " < <totalAllowance(terms,pay)<<endl; return 0; } | The total allowance for your school time is US$7200 |
do..while statement
The do....while loop allows for executing an action at least before a condition is tested. To enable the loop automatically execute its statement at least once, the while condition is put at the end instead of the beginning. The loop executes its body before the condition is tested. So whether condition is true or false, the loop will execute at least once. The do...while statment is written as follows;
do { statement to execute at least once } while ( condition ); In a do...while statement, a semi-colon must be included at the end of the while statement. In the example of getting allowances while you go to school, we can say that we are assure of your going to school at least the first time. We are however not sure that you will continue till the end. So we modify the example to allow you earn your allowance the first time you go to school. The subsequent allowances will depend on whether you keep at school or not.
#include<iostream> using namespace std; int totalAllowance(int schoolTerms, int allowances) { int terms=schoolTerms; int pay=allowances ; int totalPay=0; int t=1; // T is a specific term of the 72 do { totalPay=totalPay+pay; //add the allowance for each term to the total t++; //increament the term by one } while(t<=terms); return totalPay; } int main() { int terms=72; int pay=100; cout<<"The total allowance for your school time is US$" <<totalAllowance(terms,pay)<<endl; return 0; } | The total allowance for your school time is US$7200 |
for loop statement
The for loop is another form of repetition statements in C++. The for loop provides for the beginning of the condition, the limit of the condition and updates after every execution. The for loop takes the following form;
for ( starting point; limiting condition; update )
{
Code to execute while the condition is true
}
The stating point can include an initialized control variable either declared internally or using an already existing variable. Any expression however that evaluates to a value can also be used. The limiting condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The update section modifies the control variable by way of increasing or decreasing it to the next level before a next repetition takes place. A semicolon separates the three elements of the for loop condition. It is possible to have an empty section for each of three of them. A semicolon must be provided even if the section is empty. An empty section is evaluated as true and the loop will repeat until something else stops it. Using our example of allowances while going to school, we can write the for loop as follows;
#include<iostream> using namespace std; int totalAllowance(int schoolTerms, int allowances) { int terms=schoolTerms; int pay=allowances ; int totalPay=0; // T is a specific term of the 72 for (int t=1; t<=terms; t++) //t++ increaments the term by one { totalPay=totalPay+pay; //add the allowance for each term to the total } return totalPay; } int main() { int terms=72; int pay=100; cout<<"The total allowance for your school time is US$" <<totalAllowance(terms,pay)<<endl; return 0; } | The total allowance for your school time is US$7200 |
Four important conditions must always be remembered when dealing with loops.
- The control variable to be used in the loop condition
- The initial value of the variable
- The continuation condition within which the loop should repeat execution
- The increment (or decrement) condition by which the control variable is modified every time a repetition is made
PREV:Introduction function templates and recursion | NEXT:Other form of Transfer |