Friday, December 25, 2015

Chapter 2 - Variables and Data Types


 LET’S LEARN

INTRODUCTION

C++ VOCABULARY AND GRAMMAR

1. C++ Character Set

2. C++ Tokens

(a) Identifiers

(b) Keywords

(c) Data Types

         How are Variables connected to Data Types ?

         What is a Data Type ?

            (i) Primitive Data Type

            (ii) User Defined Data Type

            (iii) Derived Data Type

          SYMBOLIC CONSTANTS


INTRODUCTION

Data is the known or assumed facts that collectively lead to creation of information. Hence, Data is the basic unit of any information. When data is processed, we get useful information. So, Information is processed data.

Programming languages are used by developers to input data, process it, and provide useful output as information. The task of processing data is accomplished by executing a sequence of precise instructions called a program. Hence, Program is a set of instructions given to the computer in order to perform a specific task.

 

Program instructions are based upon predefined symbols and words that the operating system can understand according to some strictly followed guidelines known as syntax rules (grammatical rules).

 

Both raw-data (e.g. 14, 18) and processed-data (e.g. 14+18) have to be placed in memory location for being processed, stored or retrieved. Memory locations where data can be temporarily placed for being processed are called variables. The value of a variable can be changed and is identified by its name. Memory locations where static data (whose value cannot be changed) are placed for being processed, are called constants. 


The type (category) of value placed in a variable is known as data type. Different data types include characters, strings, numerals, decimals etc.





C++ VOCABULARY AND GRAMMAR

 

C++ programming language has its own vocabulary and grammar classified as Character Sets and Tokens. The C++ compiler understands instructions written in C++ programming language, translates it into machine readable form and then executes it as the required functionality.

1. C++ Character Set

Character Set includes the characters and symbols that a C++ program can understand and are grouped to form the commands, expressions, words, statements and tokens for the C++ coding language.

The characters that can be used in C++ are grouped into the following four categories:

Letters        Digits          • White spaces       Special characters

 

Letters

Letters are alphabetical characters represented by “A … Z” or “a … z”. C++ is case sensitive (upper case & lower case letters are considered different).

 

Digits

Digits are numeric characters represented by 0 to 9. They are used to represent numeric values and to assign numeric data to the C++ tokens.

 

White Spaces

White spaces are used to separate words, but are prohibited between characters of keywords and identifiers. It includes blank space, horizontal tab, carriage return and New line Form feed. The compiler ignores white spaces unless they are part of a string constant.

Special Characters

Special characters are used in C++ to create Arithmetic statements ( +  -  * / ), Relational statements ( <   <=   >  >=   == ) , Assignment statements ( = ), Logical statements (  &&   ||  !  ) etc.




 







 

Words are a collection of reserved keywords and standard identifiers. Eg: int, cout

Keywords are predefined words that are used to identify operations and data descriptions. They cannot be redefined. Eg: return, int, switch

Standard identifiers are predefined words that belong to the C++ standard library and have special meaning for the C++ compiler. It can be redefined. Eg: cout, main

Try below given code (just for reference):

int cout=1; int main=2;

std::cout<<"cout = "<<cout;

std::cout<<"\nmain = "<<main;

Statements are one or more program instructions given to the C++ compiler. Each statement ends with a semicolon. It includes variable declarations and expressions.

Eg: std::cout<< "Hello Good Day";

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

Operands are data values or data holders (variables) that can be operated upon or manipulated. Eg: 10 + 2 = y; Here 10, 2, y are operands and + = are operators. Remember that y is a variable.

Expression is a sequence of operands and operators that specifies a computation process. Eg : a=42,  2+2 , a=b+c, a<b etc.

Commands are basic units of instructions given to the C++ compiler. Eg: #include, cout,  int, char, for, while

 


2. C++ Tokens

Tokens are the smallest individual units of C++ program. It is similar to independent words and punctuations found in a passage of text. There are 3 types of tokens: Identifiers, Keywords and Data Types.

Types of Tokens

(a) Identifiers

An identifier is a sequence of one or more letters, digits or underscore character that are used to represent variables, constants and functions in a program. Neither spaces nor punctuation marks or symbols can be part of an identifier. It cannot start with a decimal number. C++ identifies uppercase & lowercase alphabets as separate characters. Use of two sequential underscores ( __ ) is reserved for C++ implementation & standard libraries. Identifiers should not match any keyword used by the C++ language because this will confuse the compiler during translation process.

Variable : Storage location in memory where values can keep changing.

Constant: Storage location in memory having fixed value.

Function: A group of instructional statements that perform a defined task.

 (b) Keywords

Keywords are predefined words that are used to identify operations and data descriptions. They cannot be redefined and hence, they cannot be used as names for the program variables or other user-defined program elements. Eg: return, int, switch

List of common Keywords:



How are Variables connected to Data Types ?

A computer program needs to memorize/store certain values for input/output operations, calculations, processing and storage. These values (data) are stored in computer’s memory, based on the allocated memory space that is predefined for different datatypes within the C++ memory-management-system. The memory allocation in our computer systems are basically organized in Bytes.

 

In C++ the minimum amount of memory that we can manage is a byte. A byte can store relatively small amount of data such as one single character or a small integer (generally an integer between 0 and 255). Eg: char, short int.

 

However, the computer can handle large data by grouping several bytes. Groups of bytes manage memory allocations for accommodating larger and different types of values. For Eg:


int allocates 2 Bytes,

long int allocates 4 Bytes,

double allocates 8 Bytes.


Declaring & Initializing Variables: In order to use a variable in C++, we must first declare it, specifying which data type it would store. The declared variable can then be assigned with an initial value.

Variable declaration is the process of declaring memory space for storing value of a specific data type.

Variable initialization is the process of assigning appropriate values to an already declared variable.

 

Syntax for declaring a  Variable

 

 datatype variablename1, variablename2, ... ;

 

Example:   int age, mark ;


 Syntax  for initializing a Variable with Value

 

datatype variablename = initial value;

 

Example:   int age =18, mark = 75;


Variables can be declared at any place in the program. A variable of specific data type can be converted into another data type. This process is called type castingDynamic initializing of variables is also possible.

Type Casting is the process of converting one variable type into another.

Example: (float) a/b, where a and b are integers.

Dynamic initialization is the method of initializing a variable by an expression instead of a constant.  This type of initialization is done at run-time.

Example:  float fAverage = fSum + 5 ;


What is a Data Type ?

The type (category) of value placed in a variable is known as data type. Different types of data that can be stored in computer memory include characters, strings, numerals, decimals etc.

Different Data Types in C++

(i)                Primitive (Basic or Built-in)

(ii)              User-defined

(iii)            Derived

 

(i) Primitive Data Type

They are built-in data types of the C++ programming language. Here is a list of the basic data types in C++, as well as the range of values it can accommodate.




 






The size and range of basic data types depend on the architecture of the computer system being used to compile and execute the C++ program. The values shown in the chart corresponds to most 32-bit systems.

 

(ii) User Defined Data Type

 

It is any built-in data type or collection of data types, which can be named/renamed by the user. User-defined data types include typedef, struct, union, enum and class.

 

An example (typedef): In order to store integer numbers (1, 2, 3…), we use the data-type int and declare it in C++ program as int a, b; which means a, b are variables that can store integer values. Now look at this declaration statement:

 

typedef int NUMBERS;

 

This means that you can now use the term NUMBERS instead of int. So, the declaration:

int a, b;

can now also be written as

NUMBERS a, b;

 

As per above typedef definition, NUMBERS will represent data type ‘int’ thereby declaring ‘a‘ and ‘b’ as integers.

 

Note: Can you guess the datatype of string ? (refer to Program 4 below)

 

(iii) Derived Data Type

Derived data types is made up of simpler data types and hence contain multiple primitive data types. Arrays, Functions and Pointers are examples of derived data types. (You will learn more on arrays, functions, pointers in upcoming chapters)

 


Array is a collection of consecutive memory locations that store values of same data type and are identified by a common name.

 

Function is a group of instructional statements that together perform a specific task.

 

Pointer is used to store the memory address of another variable.

 

SYMBOLIC CONSTANTS

Symbolic constant is used to give an explanatory name to any constant value. Its advantage is that, if you want to change the value of a symbolic constant, you just need to make the edit at one location instead of making changes at all places in the program where it’s used. Symbolic constants can be declared by any of the following methods:

(a) #define, #undef (preprocessor macro definitions)

(b) const keyword

(c) enum keyword

 For Example: #define  iMax 20

           or,       const int iMax = 20;

           or,       enum { iMax = 20 };

           hence, iMax + 10 = 30

           iMax can be used instead of 20. iMax is a constant.

 

Program 3: Write a program to accept First Name of a person and wish that person by his/her name. Use data type “char”.

  

 

#include <iostream>

int main()

{

        char a[20];

        std::cout << "Type your First Name (then Press enter key): ";

        std::cin >>a;

        std::cout << a << " Have a Nice Day";

}

 

Output


Program 4: Above program can be modified using getline() of the “string” class. (We will learn in detail about the string class in chapter 6)


 

#include <iostream>

#include <string>

using namespace std;

int main()

 

{

        string s;

        cout << "Type your First Name (then Press enter key): ";

        getline(cin,s);

        cout << s << " Have a Nice Day";

 

}

OUTPUT


 

 

Program 5: Accept 2 numbers and find their sum, product and quotient.

(In this program, “Typecast” feature prints exact quotient value. Try to find reason for values of variables e, p, q. Can you guess the use of “\n” )


 

#include <iostream>

int main()

{

  int a, b, c, d, e;

  float p, q;

  std::cout << "Enter 2 numbers: ";

  std::cin >> a >> b;

  c=a+b;

  d=a*b;

  e=a/b;

   p=a/b;

  q=(float)a/b; // example of Typecast

  std::cout << a << " + " << b << " = "<< c << "\n";

  std::cout << a << " * " << b << " = "<< d << "\n";

  std::cout << a << " / " << b << " = "<< e << "\n";

  std::cout << a << " / " << b << " = "<< p << "\n";

  std::cout << a << " / " << b << " = "<< q;

}

 

Output



 




Program 6: Print the answer to this question “Which month and year is it?” Use preprocessor directives to define a month and year.

 

 

#include <iostream>

int main()

{

  #define month "December"

  #define year 2020

  std::cout << "This is "<<month<<" of "<<year;

}

 

Output


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.