Thursday, December 24, 2015

Chapter 3 - Operators in C++

                                
LET’S LEARN

INTRODUCTION
TYPES OF OPERATORS
 1. Arithmetic Operators
 2. Unary Operators
          Increment operator (++)
          Decrement operator (- -)
          Unary Plus Operator (+)
          Unary Minus Operator (-)
          sizeof() Operator
          Explicit Type Casting Operator
          Bitwise Complement Operator (~)
 3. Assignment Operator
 4. Compound Assignment Operators
 5. Relational (Comparison) and Equality Operators
 6. Logical Operators
          && (AND) Operator
          || (OR) Operator
          ! (NOT) Operator
 7. Conditional Operator ( ? : )
 8. Comma Operator
 9. Scope Resolution Operator
 10.   Address & Pointer Operators
 11.   Bitwise Operators
OPERATOR PRECEDENCE
CHAPTER EVALUATION EXERCISE


INTRODUCTION TO OPERATORS

Operators are characters or signs that represent mathematical or logical operations. Eg: + - / % > =

To calculate the final result, operators use one or more values called operands. Operands are data values or data holders (variables) that can be operated upon or manipulated by an operator. Eg: 14, 24 are operands in the expression 14+24

Operators and Operands work together to form an expression. Expression is a sequence of operands and operators that specifies a computation. Eg : a=42,  2+2 , a=b+c, a<b etc are expressions.

y + 12 = 28
Expression
y + 12 = 28
Operators 
+ =
Operands
12, 28, y
Variable
y


Operators in C++ are broadly classified into 3 "categories":

Unary Operator  - work with one operand
Binary Operator - work with two operand’s
Ternary Operators - conditional operators that work with 3 operand’s




TYPES OF OPERATORS

Operators in C++ can be of 10 different "types". Let’s quickly discuss each one of them.

1.   Arithmetic Operators

Arithmetic Operators are binary operators that support arithmetic operations. The five arithmetic operations supported by C++ language include: addition(+), subtraction(-), multiplication(*), division(/), and Modulo (%).

The first 4 corresponds to their respective mathematical operators. The Modulo/Mod operator is used to find remainder of the division between two values. For example, in the expression a = 11%3, variable a will contain value 2, since the remainder after dividing 11 by 3 is 2.

2.   Unary Operators

Unary Operators work with one operand and includes ++, --, + (unary plus), - (unary minus), ~ (bitwise complement), ! (not), sizeof() and Typecast.


Note : “!” or the Logical NOT Operator is discussed under Logical Operators.

Increment operator (++) is a unary operator that increases the value stored in a variable by 1. This is equivalent to +1. Increment operators can be pre-increment (++a) or post-increment (a++).

  • A pre-increment operator (prefix) is used when the value within an expression is to be incremented first, and then assigned to an operand. For example:
       If a=5, then b=++a would result in a=6, b=6

  • A post-increment operator (suffix) is used when the value within an expression is to be assigned to an operand first, and then incremented. For example:
       If a=5, then b=a++ would result in a=6, b=5

Decrement operator (- -)  is a unary operator that decreases the value stored in a variable by 1. This is equivalent to -1. Decrement operators can be pre-decrement (- -a) or post-decrement (a - -).

  • A pre-decrement operator (prefix) is used when the value within an expression is to be decremented first, and then assigned to an operand. For example:
       If a=5, then b = - -a would result in a=4, b=4

  • A post-decrement operator (suffix) is used when the value within an expression is to be assigned to an operand first, and then decremented. For example:
       If a=5, then b = a-- would result in a=4, b=5

Unary Plus Operator (+) assigns positive value to an operand of any numeric type. This operator has been preset as default for all numeric types. Eg: +3

Unary Minus Operator (-) negates or assigns negative value to an operand of type integer, floating-point or decimal. Eg: -3

  sizeof() Operator  is a unary operator that returns the size of a data type or variable in Bytes. It accepts one parameter, which is either a data type or a variable. 

Example: b = sizeof (char) ;

Above example will assign the value 1 to variable b because the size of data type char is One Byte. The value returned by sizeof is a constant, so it is always determined before program execution.

  Explicit Type Casting Operator  is a unary operator that allows to convert one data type into another data type. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the "new data type" enclosed between parentheses.

     int i ; 
     float f = 3.14 ;
     i = (int)f ;

In the above example, float number 3.14 is converted to an integer value 3, after typecasting. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the typecast expression: 
i = int(f) ;

Bitwise Complement Operator (~) also called the One’s Complement Operator, is a unary operator that is used with numeric operand types for inverting each  bits of its binary representation (0 to 1 and 1 to 0). The result of the operation is a bitwise complement (inverse of the binary representation) of the operand. For example:


Decimal
Binary
Bitwise Complement (~)
3
0000 0011
~ 3 = 1111 1100
3.   Assignment Operator

The assignment operator (=) is  a binary operator that  assigns a value on Right Hand Side (RHS) to a variable on the Left Hand Side (LHS). 
Example: a = 5 ;

Here, an integer value 5 is put into memory location (variable) named a. The  LHS part of assignment operator (=) is known as the lvalue (left value) and the RHS part is known as the rvalue (right value). The lvalue has to be a variable whereas the rvalue can be a constant, a variable, the result of an operation or any combination of these. The most important rule when assigning is the right-to-left rule. The assignment operation always takes place from right to left, and never the other way. For example lets consider: a = b ;


This expression assigns the value contained in variable b (the rvalue) to variable a (the lvalue). If a had some previous value, it gets lost.


PROGRAM 7: Declare 2 variables a, b with values 10, 4 respectively.  Assign b to a. Change b to 7. Print final values of a, b.
#include <iostream>
int main ()
{
  int a, b;
        
  a = 10; b = 4;       
  a = b; b = 7; 
       
  std::cout << "a:";
  std::cout << a;
  std::cout<< "\n";  
  std::cout << "b:";
  std::cout << b;

}

Output

a:4
b:7

A property that C++ had started over other programming languages is that the assignment operation can be used as the rvalue (or part of the rvalue) for another assignment operation. For example:

p = 3 + (q = 9) ;
is equivalent to:
q =  9 ;
p = 3 + q ;

This means, first assign 9 to variable q, then compute 3 + 9 and then put the result 12 into variable p.

The following chain expression is also valid in C++:
a = b = c = 14 ;
It assigns 14 to all the three variables a, b and c.
4.   Compound Assignment Operators

Compound Assignment Operators are binary operators that are used for quick coding purposes on variables with existing values. It includes the following operators: +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=

For example, if m=2, n=3 then m+=n means:
m = m+n  or  m = 2+3
Final values of m and n become:
m = 5, n = 3




PROGRAM 8: Write a program to assign a=5, b=5, c=5. Add 3 to ‘a’. Divide ‘b’ by 2. Multiply ‘c’ with the value obtained by subtracting ‘b’ from ‘a’. Print the final value of ‘c’ (make best use of compound assignments).


#include <iostream>
int main()
{
   int a,b,c;
   a=b=c=5;
   c*=((a+=3)-(b/=2));

   std::cout << "a=" << a;
   std::cout << "\nb=" << b;
   std::cout << "\nc="<<c;

 }


Output



a=8

b=2
 c=30


  
5.   Relational (Comparison) and Equality Operators

Relational and Equality operators are binary operators that are used to compare and check two expressions. The result is a Boolean value (true or false, 1 or 0). Relational and Equality operators include: <, >, <=, >=, = =, !=, <=>

Here are some examples:
Instead of using only numeric constants, we can also use any valid expression, including variables. Suppose that a=2, b=3 and c=6, then
= operator is an assignment operator. It assigns the value on its right side to the variable at its left side. Eg: p = 8;

== operator is the equality operator. It compares whether operands or expressions on both sides of it are equal to each other. Eg: 5==5 returns true.

In the expression (b=2) == a, we first assigned the value 2 to b and then compared it to a (which already has value 2). The final result is true.


Note: The 3-way comparison operator also called the spaceship operator and represented by <=>, takes two values a, b and determines if a<b, a=b, or a>b in a single operation. It is a new inclusion in C++20 and is used in preprocessor based instruction sets (part of machine language coding). Eg: Checking real numbers (a real number is <=> ZERO).



6.   Logical Operators

Logical (boolean) operators are used to check conditions between operands or expressions. Logical operators can be unary or binaryThere are 3 Logical operators: && (AND), || (OR),  ! (NOT ). It responds to the computer as a TRUE or FALSE value. In C++, TRUE value is represented by 1 and FALSE value by 0. 

Eg: if AGE >=18 && AGE<=25 then print NAME

(the statement prints candidate names between age group 18 and 25)

&& (AND) Operator
The && operator is a binary operator that checks conditions where both the operands (or expressions) have to be satisfied. If both the conditions are TRUE, 1 is returned otherwise 0 is returned. If any one condition goes wrong (FALSE), then final result will be FALSE. The following list shows result of && Operator for 2 conditions (operands) a and bIf both a, b are TRUE, then a && b is TRUE, else all other conditions are FALSE.










Note: AND operator functions like multiplication.

False AND False = False

  0      *      0     =  0

True AND True  = True

  1      *      1    =   1

False AND True  = True

   0      *      1    =   0

True AND False   = True

   1     *       0     = 0


|| (OR) Operator


|| operator is a binary operator that checks conditions where any one of the  operands/expressions have to be satisfied. If any one condition is TRUE, 1 is returned otherwise 0 is returned. The following list shows result of || operator for 2 conditions (operands) a and b. If either a, b are TRUE, then a || b is TRUE, else the condition is FALSE.











Note: OR operator functions like addition.

False OR False = False

   0    +     0    =  0

True OR True   = True

   1    +    1     = 2 (or >0)

False OR True   = True

   0    +    1      = 1

True OR False   = True

   1    +    0      = 1


Check these expressions:





! (NOT) Operator

! operator is a unary operator that checks for one condition that is located to its right and then inverts the value. If condition is satisfied (TRUE), it gives FALSE value and if condition is not satisfied (FALSE), it gives TRUE value. For example:







7.   Conditional Operator

The conditional operator is a ternary operator that evaluates an expression having one condition and 2 possible results. If the result is TRUE, then result 1 is executed otherwise result 2 is executed. It is used with a combination of 2 operators namely ? and :

Syntax for using a conditional operator is:

   condition ? result1 : result2

If condition is satisfied (or true) the expression will return result1, else result2 will be returned.









PROGRAM 9:Print the biggest among 2 numbers using conditional operator.



#include <iostream>
int main ()
{
  int a,b,c;

  std::cout<< "Enter first number: ";
  std::cin>>a;
  std::cout<< "Enter second number: ";
  std::cin>>b;

  c = (a>b) ? a : b;

  std::cout << "Biggest number is: "<<c;
}


Output



Enter first number: 28

Enter second number: 24

Biggest number is: 28


8.   Comma Operator

We have seen how comma (,) has been used as a separator ( eg: int a, b; ). Comma can also be used as an operator. Comma operator is a binary operator that is used to join together 2 or more expressions whose operations will be executed in a sequence. In the following code:
j=(k=3, k+=2);
3 is first assigned to k,
next the value of k is incremented by 2,
then value of the final expression on RHS is assigned to LHS.

So finally, variable ‘j’ would contain the value 5 while variable ‘k’ would also contain value 5.

PROGRAM 10: Using comma operator, assign b=5, then use compound assignment b*= 4. Assign the above 2 comma operated expressions to a. Print values of a, b.

Again, using comma operator assign b=5, then compute b*4, assign c=12. Assign the above 3 comma operated expressions to a. Print values of a,b,c.

Check the difference between working of above two expressions.


#include <iostream>

int main()
{
   int a, b, c;
   a=(b=5, b*=4);

   std::cout << "a=" << a<<"\nb="<<b;

   a=(b=5, b*4, c=12);

   std::cout << "\na=" << a<<"\nb="<<b<<"\nc="<<c;

}

Output


a = 20
b = 20
a =  12
b = 5
c = 12



9.  Scope Resolution Operator
The scope resolution operator, represented by :: is both a unary and binary operator. It is used to extend the accessibility and override the characteristics of variables, functions, class and objects stored globally for use in local area of a program.
Eg: std::cout<<”Hello”;

Here, std is the namespace (area) containing the cout global object, where purpose of the cout object is to provide output stream. Now, please refer to Chapter 1, Program 1, Method1/Method2 and check the difference between using/not-using the scope resolution operator.

PROGRAM 11: Declare an integer variable n as local & global variable with different values. Print both the values of n.
 

 

#include <iostream>

int n = 15;

int main ()     

{

  int n = 9;

  std::cout<<”Local value of n = ”<<n<<”\n”;

  std::cout<<”Global value of n = ”<<:: n;

}

 


Output


 Local value of n = 9 
 Global value of n = 15 



10.   Address & Pointer Operators

& operator or address operator is a unary operator. It is also called the "Address of" operator. It points to the address of a variable.

* operator or pointer operator is a unary operator. It is also called the "Value at" operator or the "Indirection" operator. It points to the value stored within a particular memory address.

For example :

     &n     
gives address of the memory location whose name is ‘n’
* (&n)    
gives value stored within memory address specified by &n


PROGRAM 12: Declare “i” as integer variable and “p” as pointer to integer. Assign value 20 to i. Print the value of “i” normally and by pointer operator. Also print address location of variable “i” by address operator and pointer.

 

#include <iostream>

int main ()    

{

   int i, *p;  // declare i and pointer p of data type integer

   p=&i;  // assign memory address of i to pointer p

   i=20;

   std::cout<<"Normally i = "<< i <<"\n";

   std::cout<<"By pointer operator i = "<< *p <<"\n";

   std::cout<<"Memory location of i by address operator = "<< &i <<"\n";

   std::cout <<"Memory location of i by pointer = "<< p <<"\n";

}

 


Output


Normally i = 20
By pointer operator i = 20
Memory location of i by address operator = 0x6ffe04
Memory location of i by pointer = 0x6ffe04










11. Bitwise Operators

A bitwise operator processes each bit of the binary value of an operand. There are 6 bitwise operators: AND (&), OR (|), NOT(~), XOR (^), Right Shift (>>), Left Shift (<<).

In the byte format (8-bit), the decimal number 1 is represented as a string of binary digits 0000 0001 while number 5 is represented as the string 0000 0101. Bitwise operators act on each bit within the string of binary digits representing a number.

Refer to the table below, where p = 10 (0000 1010 in binary) and q = 4 (0000 0100 in binary).


Operator
Meaning
Example
Explanation of example
p = 10 (0000 1010)
q = 4  (0000 0100)
&
(Bitwise AND)
if BOTH bits are 1 then result is 1 else its 0
p & q = 0 (0000 0000)
 0000 1010 &
 0000 0100
 ------------
 0000 0000
|
(Bitwise OR)
if ANY bit is 1, result is 1 else 0
p | q = 14 (0000 1110)
 0000 1010 |
 0000 0100
 ------------
 0000 1110
~
(Bitwise NOT)
negate/invert all bits
~p = -11 (1111 0101)
 ~ 0000 1010
   ------------
   1111 0101
^
(Bitwise XOR)
if ONLY one of the bit is 1, result is 1 else 0 (1^1=0)
Suppose,
a = 5 ( 0000 0101)
b = 3 ( 0000 0011)
Then
a ^ b = 6 (0000 0110)
Note: a | b = 7 (0000 0111)
 0000 0101  ^
 0000 0011
 ------------
 0000 0110
>> 
(Bitwise right shift)
shift each bit towards right
p >> 1 = 5 (0000 0101)
(Shifts every bit by 1 position to right)
 0000 1010 >> 1
 ------------
 0000 0101
<< 
(Bitwise left shift)
shift each bit towards left
p << 2 = 40 (0010 1000)
(Shifts every bit by 2 positions to left)
 0000 1010 << 2
 ------------
 0010 1000


































Example code (Bitwise left shift):

a=2;
std::cout<<"a = "<<(a<<3);

Output:
a = 16



OPERATOR PRECEDENCE


Operator precedence is the rule followed by programming languages in deciding the priority of operations in an expression having multiple operators. Eg: In the expression 5+2*9 the multiplication operator (*) is given top priority, followed by the addition operator (+). Hence the expression 5+2*9 would evaluate to 23.

However, precedence levels of operators can be restructured by grouping them using parenthesis (round brackets). Grouping defines the precedence order in which operators are evaluated in an expression. For example, the expression 5+2*9 gives 23. After grouping it to (5+2)*9, the answer would be 63.

From greatest to lowest priority, the order of operator precedence follows the rules as specified in the chart:


           


PROGRAM 13 (Brain Teaser Program): Develop a simple billing system for the Kerala House Restaurant. Items sold: Egg Porota (Rs. 80), Kerala Meals (Rs. 100). If customer is student, then discount = 50%, else discount = 25%. GST of 18% after discount, has to be added as tax.

Challenge: Use compound assignment operator, scope resolution operator, ternary operator, comma operator and preprocessor directives wherever necessary.

#include <iostream>

#include <string>

using namespace std;

int discount = 25;

 

int main ()    

{

  #define EP 80 // Egg Porota

  #define ML 100 // Kerala Meals

  #define gst .18 // 18% GST

  

  int fcode, scode, pcode;

  int discount = 50;

  float cost=0, tot=0, tax=0, price;

  string s;

 

  cout<<"### Food Code ### \n\nEgg Porotta: 1 \nKerala Meal: 2";

  cout<<"\n\nEnter Food Code: ";

 

  cin>>fcode;

 

  s = fcode == 1 ? "Egg Porota" : "Kerala Meals";

   

  cout<<"\nEnter 1 for Student (else any number): ";

  cin>>scode;

 

  cost = ((fcode == 1 ? cost+=EP : cost += ML), price=cost, (scode == 1 ? cost-=(cost*discount)/100 : cost-=(cost*::discount)/100));

 

  tax = cost*gst;

  tot = cost+tax;

 

  cout<< "\nItem Name        : "<< s;

  cout<< "\nItem Price       : Rs. "<< price;

  cout<< "\nDiscounted Price : Rs. "<< cost;

  cout<< "\nTax (GST)        : Rs. "<< tax;

  cout<< "\n-------------------------------";

  cout<< "\nTotal Cost       : Rs. "<< tot;

 

}


Output (screenshots of all the 4 conditions can be referred here)


CHAPTER EVALUATION EXERCISE


A) Choose the most appropriate answer (1 mark)

1. ! (NOT) is a _____________ operator.

(a) logical      (b) type casting  (c) assignment (d) pointer

2. A variable is a/an ____________

(a) operator    (b) operand        (c) expression  (d) keyword

3. Ternary operator generally works with ____________ operands.

(a) one           (b) two               (c) three           (d) none

4. sizeof(float) would return ____________ bytes.

(a) 1               (b) 2                   (c) 4                (d) 8

5. If a 4-bit binary is 1010, then its bit-wise complement is ____________

(a) 0101          (b) 1100              (c) 1011        (d) 1111

6. For expression (a=3)=(b=9)=(c=5) what would be a, b, c ?

(a) 3, 9, 5       (b) 3, 3, 3             (c) 5, 5, 5      (d) syntax error

7. If a=b=c=2, the expression c = (a=b--) results in ____________ values for a,b,c

(a) 2,2,2          (b) 1,1,1              (c) 1,1,2         (d) 2,1,2

8. If a=5, b=10, c=4, the expression a+=((b/=a)*(c%=2)) results in ____________ values for a,b,c.

(a) 19,12,4       (b) 5,2,0              (c) 5,0,0        (d) 24,12,2

9. Among logical operators ____________ is a unary operator.

(a) AND            (b) OR                 (c) NOT        (d) a,b,c

10. ____________ operator joins any number of expressions and executes them in sequence.

(a) Comma         (b) Ternary        (c) Logical       (d) a,b,c

11.  What will be m, n for these two conditions:

int m=4 ;
m = ++m + ++m;

int n=4 ;
n = n++ + n++;


(a) 10, 8             (b) 10, 10          (c) 9, 12         (d) 12, 9

ANSWERS

1) a    2) b    3) c    4) c    5) a    6) c    7) d    8) b    9) c    10) a    11) d 


B) Fill in the blanks (1 mark)

1. 15 % 6 = ____________

2. ____________ returns the size of a data type in Bytes.

3. "(double)i" performs ____________ operation.

4. One's complement of decimal 2 is ____________

5. ____________ is the bitwise right shift operator.

6. What is value of "a" for ternary expression 10==10 ? a=28 : a=45

7. std::cout makes use of ____________ operator.

8. ____________ operator points to memory address of a variable.

9. In an expression with multiple operators ____________ defines the precedence in which operators are evaluated.

10. If a = 12 (0000 1100) then bitwise operation (a<<3) gives 8-bit binary value ____________

ANSWERS

1)   3                                 2)   sizeof operator                  3)  typecast
4)   1101                           5)   >>=                                 6)  28
7)   scope resolution           8)   address (&)                       9)  grouping
10) 0110 0000 (96)


C) State whether True or False (1 mark)

1. In the expression 10i+2j, 'i' is operand and also a variable.
2. Pre decrement operator is a suffix.
3. (float)j and float(j) execute same operation.
4. One’s Complement Operator is represented by ~
5. The expression, (9<7 || 12>9) evaluates to boolean TRUE.

ANSWERS

1) True          2) False          3) True          4) True          5) True

D) Short answer questions (5 marks)


1. What are operators, operands and expressions.
2. Differentiate between increment and decrement operators.
3. List all arithmetic and bitwise operators in compound assignment.
4. Brief on scope resolution operator.
5. What is operator precedence? Give an example.

E) Subjective questions (10 marks)

1. Describe any 5 types of operators with relevant examples.
2. What is a bitwise operator? Explain any 3 bitwise operators with examples.

No comments:

Post a Comment