• Unit 12:CONTROL STATEMENTS IN C++

    Key Unit Competency
    By the end of the unit, you should be able to use control statements in C++ program to implement branching and iterations.

    Unit Outline
    • Sequence control structures.
    • Selection statements.
    • Looping control statements.
    • Jump control statements.

    Introduction
    Control structure refers to a block of statements that determine the flow of control, or order in which program statements are executed. The flow of control in a program can be examined at three levels – expression level, statement level, and program level. In the previous unit, we examined flow of control within expressions, which is governed by precedence rule. In this unit, we move a step higher by looking at statement level flow of control implemented using sequence, selection, and iteration control statements.
    This unit serve as a bridge to the next unit in which we discuss the highest level of control among program units known as procedures or functions. In this unit, we begin by reviewing of sequence control structure in which program statements are executed in the order they appear on the program. Later, we demonstrate how to write program statements that alter the flow of control using conditional logic.

    12.1 Sequence Control Structure
    Sequence control structure is a simple flow of control in which statements are executed in the order they are written. So far, most of the C++ programs we have discussed are sequential in that, statements are executed in the order they appear in the program. For example, below is a sample program implemented using sequence control structures. The program execution starts by reading two numbers (num1 and num2), and then displays the value of each number before swapping (interchanging) them. The last two cout statements display the values of num1 and num2 after swapping them as shown on the output screen.
                              #include<iostream>
                               using namespace std;
                               int main(){
                               int num1, num2, swap;
                               cout<<”Enter first number: “;

                              cin>>num1;
                              cout<<”Enter second number: “;
                              cin>>num2;
                              cout<<” Numbers before swapping: “<<endl;
                              cout<<”1. First Number =”<<num1<<endl;
                              cout<<”2. Second Number =”<<num2<<endl;
                              cout<<”\n”; //insert blank line
                              swap=num1; //assign value of num1 to swap
                               num1=num2; //replace num1 with num2 value
                              num2=swap;
                              cout<<” Numbers after swapping: “<<endl;
                                cout<<”1. First Number =”<<num1<<endl;
                                 cout<<”2. Second Number =”<<num2<<endl;
                                  return 0;
                                            }

    The output screen shown in Fig. 12.1 shows the values of each number before and after swapping:

    Activity 12.1: Sequence Control Structure
    Consider the following programming problem:
    Three integer values 50, 78, and 45 are to be placed in the three variables namely
    max, mid, and min. Write a sequential program that swaps the three numbers to
    display them in ascending order.

    12.2 Selection Control Structure
    Situations arise whereby a program need to carry out a logical test, and then take an alternative action depending on the outcome of Boolean test. A Boolean test is an expression that uses relational operators; like = (equal to), > (greater than), < (less than), >= (greater than or equal to) and <= (less than or equal to) and three logical operators namely AND, OR and NOT. For example, consider a program to test if x is greater than 20 (x > 20). In such a case, if a user enters a value of x, it is compared against 20 and the program returns true or false depending on the outcome. Generally,
    C++ supports four types of selection control statements that includes if, if... else,
    nested if, and switch.

    12.2.1 The if control statement
    The if selection is a control statement that performs an action if the condition is true,
    or skips the action if the condition is false. This conditional logic can be implemented
    in C++ using the general syntax on the left.This general syntax is an implementation
    of flowchart section shown on the right.

    For example, suppose the school administration decides to reward students whose examination score is 80% and above. This logic of if selection can be implemented in C++ using the following syntax in which the condition to test if score is greater or equal to 80 is enclosed in parentheses.

                            If (score>=80){
                            cout <<“Reward<endl;
                                }

    To further demonstrate how the if ... selection works, the following program prompts the user to enter a score. Once the statement is encountered, the score is compared against 80 in the boolean expression (score >=80). If score is above 0, the program prints Excellent otherwise nothing happens.

                         #include <iostream>
                           using namespace std;
                            int main() {
                                 int score;
                                    cout << “Enter mean score:”;
                                    cin>>score;
                                   if (score>= 80) {
                                          cout<<”Excellent\n”;
                                                 } //end if
                                            return 0;
                                                    }

    Fig 12.2 shows the output screen after running the program


    Activity 12.2: if selection statement
    Using C++, write a program that prompts a user to enter a student’s mean score in
    Computer Science. If the score is above 50%, the program should display “Pass”.

    12.2.2 The if… else selection
    The if…else selection is conditional logic that specifies the action to be performed if the condition is true, or an alternative the action is false. In C++, if...else selection can be represented using the general syntax on the left. This general syntax is an implementation of flowchart segment shown the right.


    The following program demonstrates use of if..else by modifying the previous program of rewarding students. If the score is above 80%, the program displays “Reward” otherwise, the message “No reward” is displayed.

                           ifelse
                           #include <iostream>
                             using namespace std;
                                  int main() {
                                    int score;
                                      cout << “Enter mean score:”;
                                             cin >> score;
                                      if (score >= 80) {

                                              cout << “Reward\n”;
                                                       } //end if
                                        else {
                                        cout << “No reward\n”;
                                                        } //end else
                                                   return 0;
                                                       } //end main
    Fig. 12.3 is a sample display when the program is run.


    Activity 12.3: if ... else selection statement
    The following algorithm represents a program that prompts the user to enter two numbers
    x and y. The program then divides x by y. To avoid division by zero error, if the value of y is 0, the program should display an error message “Sorry: cannot divide by zero”.

    BEGIN
              PRINT “Enter 2 numbers X and Y”
              READ x, y
              IF y = 0 THEN
                         PRINT “Error : Division by zero”
       ELSE
                         result = x/y
                       PRINT X, Y, Quotient
               END IF
    END

    12.2.3 Nested if..else control statement
    The nested if…else selection is a conditional logic that tests for multiple alternatives by placing if…else statements within another if…else statement. The general syntax of nested if statement can be expressed as shown on the left. This an implementation of a flowchart segment shown on the right


    For example, the following program uses compound conditional logic in nested if selection to assign grade depending on average mark entered by the user.


    Fig. 12.4 shows a sample output of grade assigned once the user enters 67 as the score.


    Activity 12.4: Nested if selection statement
    In athletics, runners are awarded medals depending on position as follows: position
    1: gold; position 2: silver and position 3: bronze. The rest of the runners are not
    awarded any medal but receives appreciation message saying “Thank you for your
    participation”. Using nested if...else statements, write a C++ program that determines
    the medal to be awarded to runners depending on time each athlete touches the finish
    line.
    12.2.4 Switch... case selection
    Similar to nested if selection, switch... case control statement is used to choose from several alternatives. Within the switch are actions (cases) associated with a constant value that must be evaluated before the statements within each case are executed. The syntax of the switch -- case selection is shown below and is demonstrated using the flow chart next to it:


    The switch in the first line is a reserved word that evaluates the condition in the
    parenthesis. For example, in:
           switch (grade);
    If the value is equivalent to constant case ‘A’, the program evaluates the statement
    under case A and exits. If the grade value happens to be ‘B’ the next case is evaluated.

    If no block under case evaluates to true, the statements following default i.e. “Invalid
    grade” is executed. The following is a sample implementation of switch selection that assigns comment based on grade obtained.


    Activity 12.5: Switch selection statement
    Write a C++ program that assign medals to athletes based on the following conditions;
    1. If position 1, award Gold
    2. If position 2, award Silver
    3. If position 3, award Brown
    4. If the position is not 1,2 and 3, display “no award”

    Assessment Exercise 12.1
    1. Define the term selection in relation to program control structures.
    2. State four types of selection control statements used in C++.
    3. Differentiate between nested if and switch selection statements.
    4. In what circumstance does selection depend on decision?
    5. List three factors you would consider when choosing selection controls statement
    in C++.
    6. Write a program that would enable the user to enter student marks in three
    subjects. The program should calculate mean marks and determine whether the
    student has passed if the pass mark is 50%.

    12.3 Looping Control Statements
    If a programming language does not provide means of repeating execution of program statements, programmers would be required to state every action in sequence, which is a waste of time and memory space. Primarily, C++ provides three types of looping control statements: while, do... while, and for.
    The while and for control statements are pretest types of loop because they test the
    condition before executing statements within the zero or more times. On the other
    hand, the do ... while loop is a post-test loop that executes the body of the loop at
    least once before testing the condition. Apart from the three control statements, C++
    also supports a special kind of loop known as recursion discussed in the next unit
    and recursive functions.

    Activity 12.6: Looping control structure
    Assume that the school administration requires you to write a program that calculates
    cumulative sum and average score of five students. To calculate the sum, the program
    repeatedly reads each student mark, and finally calculates average once the score of
    the last student is entered. In groups, design an algorithm for solving the problem,
    and then implement it using C++ language.

    12.3.1 The while loop
    The while loop is used if a condition has to be met before the statements within the loop are executed. Therefore, this type of loop uses a pre-test condition to determine if whether are to be executed zero or more times. In general, the while loop can be represented as follows:


    The following program executes statements in the while loop if the value entered by the user is less than one. For example, if the number is 10, the list is decremented by 1 as long as the condition (n>0) remains true. The algorithm of the program can be represented using a flow chart as shown next to the program code.


    If the user enters 5 as the largest number, the sample output is shown in Fig. 12.6.


    Consider a microfinance known as Tusadie Savings Society that pays 5% bonus on shares exceeding 100,000, and 3% on shares above 50,000. However, no bonus is paid if a member has shares below 50,000. The program below may be used to compute bonus for fifteen members.


    The sample output shown in Fig. 12.7 demonstrates the behaviour of the program once the user enters 80000,7800 and 12000 as shares for three members.


    12.3.2 The do... while Loop
    The do ...while loop is similar to while loop, only that the statements in the body of the loop are executed at least once. This is because the condition is tested after execution of the statements, granting at least one execution of statement even if is the condition is false. The general syntax of do...while loop is as follows:


    The following program executes statements within the do ...while loop at least once even if the value entered by the user is less than zero. If the number entered is 10, the list is decremented by 1 as long as the condition (n>0) remains true.


    The following flowchart shows graphical representation of an algorithm used to create the program:


    Fig. 12.8 shows a sample output after the user enters 7 as the largest number. Note that the number is decremented after every loop to 1 when the alert Fire is printed!


    To demonstrate further how the do...while works, consider a real case in which gross
    salary of employees of Kigali Bookshop is based on basic salary, bonus, experience
    and monthly sales as follows:
    (a) Employees who have worked for the company for more than 10 years receive additional pay of 10%.
    (b) Monthly bonus is at rate based on monthly sales worth 250,000 as outlined in the following table:


    The following is the program implemented using C++ to calculate each employee’s gross salary depending on years of experience and sales.



    Fig 12.9 shows the output from the program. Note that to get the output, nested if has also been used to test the years of experience and bonus given.


    12.3.3 The for Loop
    The for loop is designed to perform a repetitive action with a counter that is initialised and increased after each iteration. The for --loop is similar that of the while loop except that the incrementing or decrementing of the counter is done within the for statements as follows:

                                   for(initialization; condition; increment){
                                                statements;
                                           }

    For example, the following C++ code snippet is for a program that displays numbers from 0 to 10;

                       for(int index=0; index<=10; index++){
                           cout<< index <<endl;
                                 }

    The code segments works as follows:
    1. Declares and initialises index of integer type to 0. Most often, a control can be a single character like i or x.
    2. Sets a boolean condition to be checked e.g. index <=10. If the value returned is true, execution enters into the body of the loop, otherwise the program skips the loop.
    3. Executes the statements within the loop. This can be either a single or a block of statement enclosed in braces { }.
    4. Increments the index by 1 (index ++) and tests the condition again before entering
    the loop. If the value of index is greater than 10, the program exits the loop.
    The following program demonstrates how to use the for loop. The program lists
    numbers 0 to 10, followed by the message “Fire!”.

                          #include <iostream>
                             using namespace std;
                             int main () {
                             for (int count=1; count <= 10; count++
                                                 ) {
                             cout<<count<<endl; //display 1 to 10
                             cout<< "Fire!"<<endl;
                                     } //end for
                                 return 0;
                                      }

    The for loop output shown in Fig. 12.10 shows how the value of index is incremented and then printed on the screen.


    A for loop can also be used to count downwards from the upper limit to the lower limit using the syntax:

                              for(initialization; condition; decrement){
                                    statements;
                                                 }

    For example, in the previous program, the upper limit 10 can be tested against the lower limit 1 print number in descending order using the following statements.

                                   for(index=10; index>=1, index--)
                                     cout<<index<<endl;
                                                {
                                                 statements;
                                                          }

    12.3.4 Nested Loops
    A loop inside another loop is known as nested loop. In C++, you can insert any type of loop inside the body of another loop. For example, you can insert a for, while or do-while loop inside another for loop as shown in the program segment below:

                      for (int i=0;i<rows; i++){
                             for(int j = 0;j<cols;j++)
                                   cout<<letter;
                                       cout<<"\n";
                                       }//end outer for

    In this case, the inner loop is executed for every execution of the outer loop. The program below accepts a character as input, formats the characters into rows and columns and then displays the output as shown in Fig. 12.11.


    Fig. 12.11 below shows a sample output from the program when the user keys in 4 rows, 4 columns and a character R as input.


    Assessment Exercise 12.2
    1. Define the term iteration control statements as used in structured programming.
    2. State three types of looping control statements used in C++ programming.
    3. Differentiate between while and do-while looping statements.
    4. List three advantages of looping using looping control over sequential flow of
    control.
    5. Write a sample C++ code segment that demonstrates implementation of the
    following control structures:
    (a) Do...While. (b) For loop.
    6. Write a program that would be used to display odd integers between 1 and 200.

    12.4 Jump Control Statements
    Sometimes it is desirable to exit or skip some statement inside a selection or loop construct. This is achieved in C++ by use of jump statements such as break, continue, goto, and exit().

    12.4.1 The break statement
    The break statement is a keyword used in the while, for, do…while and switch control statements to cause immediate exit from the body of the loop or selection. For example, once a break statement is encountered in the following loop, control is transferred to immediate statement following the loop:

                      int main(){
                                 int count;
                                 for (count = 1; count <= 10; ++count ) {
                                     cout << count << “ , “;
                                                if ( count == 5 )
                                                break; // skip count if its 5

                                } //end for loop
                              cout << “The loop exits at:”<<count<<endl;
                              return 0;
                                       } //end main

    Fig. 12.12 shows how the break statement inside the if conditional logic forces the program to exit the loop once 5 is encountered.


    Activity 12.7: Looping control statements
    Write a C++ for a program used to find sum and average of twenty positive integers
    entered by user. If the input is negative, the program should exit from the loop and
    display the cumulative and average.

    12.4.2 The continue statement
    The Continue statement is used in repetition statements to cause the program to
    skip the remaining statements in the body of the loop to test the condition. The only
    common thing between the break and continue is that both use if selection to specify
    the jump condition. For example, the program below prints values between one and
    ten except 5:


    Fig. 12.14 shows a simple output in which 5 is skipped in the list. This is because the loop skips to test the condition even if 5 is encountered.


    12.4.3 The goto Statement
    The goto statement was used in early days of programming to specify the line the program should jump to. Like many structured programming languages, C++ sparingly uses goto for transfer of control. A goto jump in C++ is accomplished by writing the goto reserved word followed by the label of destination statement. A label is just a name followed by a colon (smile as follows:

                                 badloop: index++
                                 if (index < 5){
                                 goto badloop;
                                             }

    To demonstrate how the goto statement works, the following program segment uses the goto keyword and if selection to implement a loop. To start with, the initial value of index (0) is tested against five (5). The condition causes the goto statement tojump to the label or exit the selection construct if the value of index is 5.

    #include <iostream>
    use namespace std;
    int main(){
    int index = 0;
    label: index ++; //increment index
    cout<<”Current index is:”<<index<<endl;
    if(index < 5){
    goto label; //jump to label
    }
    cout<< “Last index is:”<<index<<endl;
    return 0;
    }

    Fig. 12.13 shows a sample output from the program. Note that value of index is incremented by the statement index++


    Because a goto statements can cause jumps to any location in your program, indiscriminate use of the statement can be a source of program bugs that may be hard to debug. Our advice is to use goto when absolutely necessary or completely avoid using it!

    12.4.4 Exitegg Statement
    The exit() statement is an in-built function in C++ used to terminate a loop or program execution prematurely. For example, exit(1) statement in the following program causes the program to terminate before the statement “You’ll never see Me!” is displayed:


    Fig. 12.14 shows a sample output from the program in which the statement following the exit() statement is never displayed!


    Activity 12.8: Break, continue and exit()
    1. Write a C++ program that tests if the given number is prime number. The logic should use a loop and break statements to test the use input.
    2. Write a program that accepts numbers starting from zero. If the number is less than zero, the program should print an error message and stop reading the
    numbers. Otherwise, if the number is greater than 100, the program ignores the number and executes the next iteration.
    3. Write a program that accepts characters or special symbols as input and formats that output as a pattern such as shown below:


    Assessment Exercise 12.3
    1. Explain three types of jump control statement used to exit from a loop or selection statement.
    2. Explain why it is not good programming practice to use the goto control statement.
    3. Differentiate between break and continue statements.
    4. Explain what happens when an exit () statement is used in a program.
    5. Identify two circumstances in which the exit () statement may be used.
    6. Write a program to demonstrate the use of continue and go to jump statements.

    Unit Test 12
    1. Differentiate between if, and if..else statements in C++.
    2. Write a sample program showing the general flow of the following control structures:
    (a) Nested for.                    (b) do ...while.
    3. Using a while loop, write a C++ program that would be used to display 50 numbers in descending order.
    4. Write a program that would enable the user to enter student marks. The program should
    then determine and display the grade based on grading criteria used by your school.

    5. Write a program in C++ that prompts for n numbers, accumulate the sum and then computes the average. The program should display sum and average formatted to 2 decimal places.
    6. Write a program that reads temperature in degree celsius at least once a day in every week. The computer should convert recorded values into Fahrenheit and then calculate the average weekly temperature.
    7. Nkosha deposited FRW 2 million in a bank at a fixed rate of 8% per annum for a period of five years. Write a program that calculates and outputs principal amount and interest for a period of seven years. The program should display amount rounded to nearest whole numbers
    8. Malaika took a loan of FRW 200,000 from a commercial bank at 12% interest payable
    in four years. Write a program that would keeps track of monthly repayments, and interest after four years. The program should display amount payable in each year.
    9. Although the goto statement is an obsolete control in modern programming, the statement is sparingly used in some programming languages. Explain circumstances that necessitate its use in C++ programming.
    10. Study and give the output of the following program.










    Unit 11:EXPRESSIONS AND OPERATORS IN C++ LANGUAGEUnit 13:FUNCTIONS IN C++ PROGRAMMING