• Unit 11:EXPRESSIONS AND OPERATORS IN C++ LANGUAGE

    Key Unit Competency
    By the end of the unit, you should be able to apply expressions and operators in C++ programming.

    Unit Outline
    • Expressions and operators.
    • Classification of C++ operators.
    • Classification of C++ expressions.

    Introduction
    To write expressions that do not corrupt computer memory or return invalid results, you need to understand operators used in C++ programming language. This unit is related to the section on operators and expressions discussed earlier under the unit on introduction to programming. The unit also serves as a continuation to the previous unit on introduction to C++ programming. To begin with, we discuss in details operators used in C++ such as assignment, arithmetic, relational, logical, bitwise, and special operators. Later, we demonstrate how to form primary to complex expressions using C++ operators.

    11.1 Expressions and Operators
    In mathematics, the term expression refers to a sequence of operators and operands that specifies relational or mathematical computation. An operator is a sign (e.g. +, -), or keywords, while an operand is numeric value manipulated by an operator.

    In programming context, an operator is a symbol or keyword that instructs a compiler to evaluate mathematical or logical expressions. In addition to mathematical operators, most programming languages support special operators some of which are English-like keywords. Given that C++ is a system programming language, most of its operators are special symbols available on a standard keyboard. This makes the language more portable, and internationally accepted because its syntax does not rely a lot on natural languages like English.

    11.2 Classification of C++ Operators
    Given that operators, operands and expressions go hand-in-hand, in every section we demonstrate how to apply an operator on operands using simple expressions.

    11.2.1 Arithmetic operators
    The most basic mathematical signs are the arithmetic operators which include addition
    (+), subtraction (−), multiplication (×), and division (÷). In C++, the same operators are used but multiplication and division operators are replaced with asterisk (*) and forward slash (/) respectively. Table 11.1 below gives a summary of the five arithmetic operators supported in C++.

    Observation on the table above shows that the only unusual operator in arithmetic is the modulus (%) symbol. In C++, the operator is used to return remainder of an integer division. For example:

                             remainder=7%4; //returns 3
                             test = 16%4; returns 0.

    The five arithmetic operators are binary operators because they take two operands. For example, the expression 8 + 7 contains a binary operator (+) and two operands, i.e., 8 and 7. The following program shows how to use of arithmetic expressions in C++ whose output is shown in Fig 11.1.

    11.2.1.1 Procedure rule
    Similar to BODMAS rule in mathematics, C++ uses precedence rule to evaluate arithmetic
    expressions: The precedence rule from the highest to the lowest is as follows:

    For example, in the following expression:

                                 k = a * ((b + c)/d);

    1. Operators in expressions contained within parentheses are evaluated first. Parentheses are said to be at the “highest level of precedence.” In cases of nested parentheses, the innermost pair of parentheses are applied first; in this case (b+c) is evaluated first.
    2. Multiplication and division operations are applied next. If an expression contains several multiplication, division and modulus operations, operators are evaluated from left to right. This is because multiplication, division and modulus are said to be on the same level of precedence.
    3. Addition and subtraction have the lowest precedence. If an expression contains several addition and subtraction operations, the operators are applied from left to right.

    Activity 11.1: Precedence rule
    1. In groups, discuss how the precedence rule can be applied to determine the value of X in the following expression:

                                   X = 23 + 5 + (84* 9) + 6 / 3;

    2. What are the possible values of X if the precedence rule is not applied?
    3. Study the sample code below and identify an expression that replaces content of amount variable with product of quantity and price. The output is shown in Fig. 11.2.

    4. Rewrite the following mathematical expression into a C++ assignment statement:
    ax2 + bx + c.

    11.2.2 Assignment operators
    The assignment operator that resembles equals to (=) causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the operator. For example, the following statement assigns the integer value 5 to the variable named fruit:
                                                    fruit = 5;
    The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, result of an operation or any combination of these. The most important rule when assigning is the right-to-left rule: Assignment operation always takes place from right to left, and never the other way round. The following statement is invalid!
                                                 5 = students;

    Activity 11.2: Assignment operator
    Study the program code below in which variables a, b and c are initialized with values 7, 9 and 10 respectively as shown in Fig 11.3. Determine the values printed by each of the cout statements if the value of a is 12 and b is 15.

    11.2.3 Compound Assignment Operators
    C++ has a unique way of combining arithmetic and assignment operators compound operators typically referred to as self-assigned operators. The most commonly used self-assigned operators are conditional addition (+=), subtraction (-=), division (/=), multiplication (*=), and modulus (%=). Those used with other operators such as >>=, <<=, &=, ^=, |=) are left for class discussion. Table 11.3 gives a summary of the five self-assigned operators.

    11.2.4 Increment and decrement operators
    In C++, increasing a value by 1 is referred to as incrementing while decreasing it by 1 is decrementing. C++ supports a unary (++) operator as a shortcut to incrementing a value by 1 and decrementing (--) by 1. Note that the term unary means that the operator takes only one operand. For example, the following statements increases and decreases value of count by 1 respectively:

                              count++; // equivalent to count=count+1.
                              Count--; // equivalent to count=count-1.

    The statements can also be expressed using self-assigned operators as follows:

                             count += 1;                    count -= 1;

    One characteristic of ++ and -- operators is that they can be used as prefix and suffix. This means that, an operator can be written either before the variable e.g. ++count or after it as in, count++. The prefix increments the value, and then fetch it while postfix fetches the value first, then increments the original. For example, if x is 5 and you write:

                                                      int a = ++x;

    the statement increments x to 6, and then fetches the value to assign it to a. The resulting value of a is 6 and that of x is also 6. If, after doing this operation, you write:

                                                     int b = x++;

    the statement fetches the value in x. i.e., 6 and assigns it to b, then it goes back to increment x. Thus, the new value of b is 6, and that of x is 7.

    Activity 11.3: Increment and decrement operators
    Assuming orange = 15, banana = 35 and isombe = 13, clients= 3. Demonstrate how you would increment and decrement each item by 1?

    11.2.5 Relational operators
    There are six relational operators supported in C++: equals (==), less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), and not equals (!=). Like arithmetic operators, relational operators are also binary operators because they act on two operands e.g. 5>3 to return true or false.
    Table 11.4 shows summary of relational operator in their order of precedence from highest to lowest.

    NB: In C++ the single (=) sign is used as an assignment operator while (==)is used as the equality sign.

    Activity 11.4:Relational operator
    Study the following program and determine the output after execution of statements consisting of relational expressions. Note that, in C++, evaluation of relational and logical expressions returns 1 for true or 0 representing false.

    11.2.6 Logical operators
    In C++, there are three logical operators used to form complex relational conditions. These are: && (AND), || (OR), and ! (NOT) also called negation. Whereas the && and || operators are binary, ! is a unary operator that takes only one operand on its right. Consequently, the operator negates the value or expression on its right to return opposite Boolean value. Table 11.5 gives a summary of the three operators.

    Activity 11.5: Logical operators
    Study the following program and determine the output after execution of the statements consisting of a mixture of relational and logical expressions.

    11.2.7 Bitwise operators
    Unlike other operators mostly used to manipulate decimal (base 10) numbers, bitwise operators are used to manipulate binary numbers. Table 11.6 gives a summary of bitwise operators supported by C++ namely: AND (&) , inclusive OR ( | ), exclusive OR ( ^ ) one’s complement (~), binary left shift <<, and binary right shift.

    To illustrate how the operators &, | and ^ are used, we take two variables p and q. The columns p&q, p|q, and p^q in Table 11.7 shows the result of binary three expressions:

    To apply Bitwise operators on decimal numbers, each number must first be converted
    into binary form. For example, assuming two variables A and B have 60 and 13 respectively, we perform binary AND, inclusive OR, exclusive OR and one’s complement as follows:

    Activity 11.6: Bitwise operators
    1. Using C++ expressions, distinguish between logical operators, and bitwise operators for AND, OR and NOT.
    2. Study the table 11.8 below and state the values returned by evaluating binary expressions p&q, p|q and p^q.

    11.2.8 Conditional/Ternary Operator
    The conditional operator represented by a question marks and colon (?smile is the only ternary operator in C++ that takes three operands. The operator evaluates an expression returning a value if the expression after (?) is true, or the expression following (smile if the condition returns false. The general format of the statement is:

                          condition ? result1 : result 2;

    If condition on the left of (?) sign is true, the expression returns result 1, otherwise if the condition returns false, the expressions returns result 2. For example, the following statement displays 10, because 7 is not less than 5;

                                        cout<< 7 < 5 ? 4 : 10; //displays 10

    NB: The conditional operator and the IF...ELSE selection works exactly the same.
    The only advantage is shortened code hence saving compile time.

    Activity 11.7: Conditional operators
    Identify the value displayed on screen after evaluating by the the following
    expressions:

    11.2.9 Miscellaneous Operators
    C++ supports other miscellaneous operators such as sizeof, cast [egg], comma [,],
    address of [&], and scope resolution operator [::].

    11.2.9.1 The size of operator
    The sizeof operator is an inbuilt function that accepts one parameter and returns the
    size in bytes. For example, the following statement assigns 8 to memsize because a
    double has 8 bytes:
                                   memsize = sizeof (double);

    11.2.9.2 Address of operator [&]
    The address of (&) operator is said to be overloaded operator because it can be used
    for more than one operations. When applied on binary operands, it is interpreted by
    the compiler as a bitwise & (AND) operator. But when the symbol is followed by
    a variable as shown in the following statement, it returns memory address allocated
    to the variable:
                                        int location = &distance;

    The statement assigns memory address of distance to location which can be formatted
    and displayed in hexadecimal format as follows:

                                    cout<<setbase(16)<<location;

    11.2.9.3 Cast [egg] operator
    Type casting operator represented with brackets () converts (casts) a value from one data type to another. This is achieved by preceding the expression to be converted by the new type enclosed between parentheses (()) or using functional notation. For example, if distance is a float, it can be casted to an integer as follows:

                                    float distance = 3.14;
                                    approx_dist = (int)distance; //C-type casting
                                    approx_dist = int(distance); //functional notation

    NB: In C++, casting a variable declared as double or float to int results in loss of
    precision due to loss in floating-point part. In the above example, the value
    assigned to approx_distance is 3!

    11.2.9.4 Comma [ , ] operator
    The comma (,) operator separates two or more expressions where only one expression
    is expected. The result of the comma-separated list is the value of the last expression.
    For example, the following expression assigns 3 to b first, then assigns b+2 to a, so
    that a becomes 5 and b holds 3:

                              a = (b=3, b+2);

    11.2.9.5 Scope resolution [::] operator
    The scope resoultion operator represented by two consecutive colons is used to identify and disambiguate similar identifiers used in different scopes. The operator is used to identify a member of a namespace or class. For example, if using namespace declaration is omitted in a C++ program, you can use:: to access cout as follows:
                               std::cout<<“I Enjoy Programming!\n”;

    11.2.10: Operator precedence in C++
    When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. In C++, the precedence rule is an established order in which an expression consisting of mixed operators is executed. Just like in BODMAS, the order of precedence can be changed by use of parenthesis. In summary, Table 11.9 gives precedence of the operators discussed in this section in order of the highest to the lowest.

    Assessment Exercise 11.1
    1. Define the following terms as used in C++ programming:
    (a) Expression
    (b) Operand
    (c) Operator
    2. Giving example, differentiate between postfix and prefix operators.
    3. Using sample codes, discuss five main categories of operators used in C++ Programming.
    4. Explain the design goal that motivated the use of special characters as operators
    in C++ programming language.
    5. Assuming y has a value of 20, and x has 8. What would happen if a programmer
    writes a statement to compare whether y is equal to x but instead writes:
    y = x ;
    6. Write the following mathematical expression as a C++ assignment statement.
    y = ax3 + bx + 7
    7. Perform bitwise AND, inclusive OR and one’s complement on the following
    variables:
    (a) Binary: p =1111111, q = 110011.
    (b) Decimal: x = 25, y =50.
    (c) Hexadecimal: m= DB, n = A2.
    8. Between arithmetic, and relational operators, which category has higher precedence in C++. Give a table of summary on the order of precedence in the two categories.

    11.3 Classication of C++ Expressions
    Depending on the type of operator used on one or more operands, expressions can
    be classified into several categories based on complex or side effect. Remember
    that, an expression is a sequence of operators and operands used for one or more of
    these purposes:
    • Computing a value from one or more operands.
    • Generating “side effects” such as modifying variables.
    In C++ programming, expressions may be classified into primary; postfix, unary,
    binary, conditional; constant, and type casting expressions.

    11.3.1 Primary expressions
    A primary expression is the most basic expression from which more complex expressions are built. Therefore, a primary expression can be as simple as having a single character or simple increment expression as shown below:

                          120; // numeric constant
                            ‘g’; // character constant
                         (x + 1 ); //increment expression

    11.3.2 Postfix expressions
    Postfix expressions consist of primary expression in which operators like ++ follow a primary expression. For example, if C=0, and index =1, the following are postfix expressions that increment their values by 1:

                             C++; //returns 1, and index++ //returns 2

    11.3.3 Unary (Prefix) Expressions
    A unary operator is placed on the left of an expression of only one operand. Such operators include address of (&), unary plus(+), unary minus (-), logical not (!), bitwise negation [~], increment [++], decrement [--], and sizeof. The following are examples of unary expressions.

                       --6; //returns 5
                    ++5; //returns 6
                !(101100110); //returns 010011001

    Note that arithmetic signs + and – can be used as unary operators. The result of the unary plus operator (+) is the positive value of its operand, while that of unary negation operator (–) produces the negative of its operand. For example, if x = 5, then;

                               +x; //returns 5; and -x //returns -5

    11.3.4 Binary Expressions
    Binary operators act on two operands in an expression. The main categories of binary
    operators are multiplicative (*, / and %), additive ( +,-), shift (<<, >>), relational (<, >, <=, >=, ==, !=), Bitwise & and |, logical && and ||, assignment (=) and compound assignment, as well as the comma operators. For example, the following are binary expressions:
                        sum = x + y;
                        ans =7!= 8; //returns true
                        y = a + k * (x * (x + 7));

    11.3.5 Ternary Expressions
    A conditional operator is a ternary operator that takes three operands. For example, the sample code below tests if i is greater than j. Since i has 3 and j has 5, the first condition returns false hence the program prints “5 is greater”:

                              int i = 3,j = 5;
                            cout<<(i>j?i:j)<<“is greater.”;

    11.3.6 Constant expressions
    Since a constant value cannot be modified, C++ provides keyword const to enable programmers write expressions that enforce this constraint. The following C++ code contains an expression that declares size as a constant. The program then calculates and prints the product :

                           int main (){
                            const double unitcost = 11.0;
                            double amount= 0.0;
                          int quanitity = 30;
                              amount = unitcost * quantity;
                                cout<<“Total.”<< amount<<endl;
                                       return 0;}

    11.3.7 Type casting expressions
    Type casting expressions are statements with explicit type conversions. By default
    C++ syntax defines conversions between its fundamental types (int, char, float, double,
    and char). This type of conversion that is automatically handled by the compiler
    is referred to as implicit type conversion. For example, the following assignment
    statements implicitly converts values from one type to another.
                            int main (){
                            int inum;
                            long lnum1, lnum2;
                            lnum1=inum;
                             lnum2=inum * lnum2;
                                      return 0;}

    In the following program, area is converted from float to double. This is because the compiler automatically converts area to data type with the highest precision in the expression. In this case, the display is 8 bytes for a double instead of the 4 bytes used to store float.

                                int main() {
                                const double PI = 3.142;
                                float area, radius 3.5;
                                 area = PI * radius*radius;
                                  cout<<“ Mem Size:”<<sizeof(area)<<endl;
                                      }

    You can also specify type conversions when you need more precise control of the conversions applied. This is achieved by using cast operator () within which is the type the operand is to be casted to. For example, the above code can be modified to force the area to be demoted to an integer value which leads to loss in precision:
                            int main() {
                            const double PI = 3.142;
                            float area, radius 3.5;
                            area = int(PI * radius*radius);
                            cout<<“Mem Size:”<< sizeof(area)<<endl;
                             }


    Activity 11.8: Expressions and operators
    1. In C++ expressions, operators such as +, and -, can be overloaded such that their meanings depend on context of use. Using examples, explain how each of the operators can be used in a unary and binary expressions.
    2. Using sample expressions, differentiate between binary expressions and tertiary expressions in C++ programming.

    Assessment Exercise 11.2
    1. Differentiate between a “statement” and an “expression” as used in programming.
    2. Using sample code, demonstrate how unary expression differs from binary and unary expressions.
    3. Identify the output of the expression in the following C++ code snippet:
                         int main (){
                        int x=10;double y=3.5;
                       float product =0.0;
                       product = x * y;
                     cout<<product<<” “<<sizeof(product);
                       return 0;}

    Unit Test 11
    1. Define the following terms as used in C++ programming:
    (a) Operator precedence. (b) Self-assigned operator.
    2. Differentiate between prefix expression and postfix expressions.
    3. State two advantages of using special keyboard symbols as operators in C++
    instead of English keywords.
    4. Differentiate between bitwise inclusive ( | ) OR, and XOR (^).
    5. To reference storage of a variable in main memory, two operators, namely size of and address of (&) may be used. Using sample code, differentiate between the two operators.
    6. With aid of a table on ASCII character set, write a program that prints integer equivalent of alphabetic characters typed in lowercase and uppercase on the keyboard. Note that although the declaration should be of type char, the output should be of integer type.
    7. Using a table, classify arithmetic, relational, assignments and bitwise operators in order of precedence starting with the highest.
    8. Write C++ program that calculates and outputs surface are and volume of a sphere.
    9. Write a C++ program that calculates and displays alternative roots of a quadratic equation:
    root = ax2 + bx + c
    10. Study the program given below and identify the correct output:
    #include <iostream>
    int main() {
    using namespace std;
    float num1, num2;
    cout << “Enter first number: “;
    cin >> num1;
    cout << “Enter second number: “;
    cin >> num2;
    cout << “num1 = “ << num1 << “; num2 = “ << num2 << endl;
    cout << “num1 + num2 = “ << num1 + num2 << endl;
    cout << “num1 - num2 = “ << num1 - num2 << endl;
    cout << “num1 * num2 = “ << num1 * num2 << endl;
    cout << “num1 / num2 = “ << num1 / num2 << endl;
    return 0;
    } //end main

    11. Identify synthax errors in the following program and rewrite to make it complete:

    #include <iostream>
    u#include <iostream>
    using namespace std;
    int main() {
    int dec1 = 2, dec = 4;
    double num1 = 2.5, num2 = 5.0;
    cout>>dec1<<“+“<<dec2<<“=“<<dec1+dec2<<end;
    cout<<num1<<“+“<<num2<<“=“<<num1+num2<<end;
    cout>>dec1<<“-“<<dec2<<“=“<<dec1-dec2<<end;
    cout<<num1<<“-“<<num2<<“=“<<num1-num2<<end;
    cout>>dec1<<“\“<<dec2<<“=“<<dec1\dec2<<end;
    cout<<num1<<“\“<<num2<<“=“<<num1\num2<<end;
    } //end main


    Unit 10:INTRODUCTION TO C++ PROGRAMMINGUnit 12:CONTROL STATEMENTS IN C++