Monday, December 26, 2011

Features Of Iostream.h


Features Of Iostream.h
It is will known that C++ is a tool for Object oriented programming (OOP). In order to handle the various object oriented features of a program, it is essential to have robust input and output facilities. Most of the object oriented programs handle three items: objects, message passing and optional parameters with the massage from the outside world. C++ provides a new way to perform the input and output operations called iostream method.
   The standard header file input and output stream (iostream.h) contains a set of small and specific general purpose functions for handling input and output data. The I/O stream is a sequence of following characters written for the screen display or read from the keyboard. The standard input and output operations in C++ are normally performed by using the I/O stream as cin for input and cout for output. The Borland C++ uses iostream.h for most stream related operations. The following are the list of various stream related header files to be included for input and output processing for different versions of the C++ compiler.
C++ compilers
Header Files To Be Included
Borland C++
Turbo C++
Microsoft Visual C++
Zortech C++
UNIX C++ (AT&T)
iostream . h,    ios .h, iomanip . h
iostream . h, ios .h, iomanip . h
ios . h, istream . h, ostream . h and streamb . h
stream . h
stream . h
   In this book, discussions on stream operations are limited only to the Borland C++ and Turbo C++ compilers. The C programming language comes with an extensive library of functions for handling input and output but it cannot add new format specifier to printf/ scanf functions. C++ supports input and output of numbers, characters and character strings more conveniently then C.

(i) Ios.h   The ‘ios’ correspond to input and output streams (hence io). The definitions based on ‘istream’ correspond to input streams and those based on ‘ostream’ to output streams. C++ allows three types of stream classes, namely,
      istream
      ostream
      iostream
(ii)  Istream  The istream consists of input functions to read a streams of characters from the keyboard.
(iii) Ostream  The ostream consists of output functions to write a character onto the screen.
(iv) 1Ostream  the iostream supports both input/output stream of functions to read a stream of characters form the keyboard and to display a stream of objects onto the video screen.
   In fact, C++ dopes not have built-in input and output functions for handling input and output of data from the outside world, but it supports different kind of stream related header files for providing these facilities. The stream library is a hierarchy of classes. The streambuf  class is the basis of all streams. It defines the basic characteristics of  buffers that hold characters for input and output. The ios class is derived from streambuf. It defines the basic formatting and error control capabilities used in streambuf. The ios is a virtual base class for the classes istream (input stream) and ostream (output stream). The iostream (input/output stream) class is derived from both istream and ostream.

Keyboard and Screen I/O
(a)   Cout   The cout is used to display an object onto the standard device, normally the video screen. The insertion operator (the double less the sign <<) is used along with the cout stream.

        The general syntax of the cout stream is,
                        Cout << variable 1 << variable 2 <<.....<< variable n;
For example, the following are certain valid cout member function usage in C++
(1)
      int x  = 123;
      float y  =  - 45 . 67;
      cout << x << y ;
The output will be  123   - 45 . 67
(3) Use of different data types freely on one line is permitted.
      int x  = 123;
      float y  =  - 45 . 67;
      cout  <<    x  = << x << ‘\t’ << “ y = “ << y;
The output will be x =123  y = - 45 . 67
(4) The cout stream is used to display different data types.
/ / cout is used to display different data types
#includ <iostream.h>
Void main ( )
{
   int num = 3 ;
   cout  << “ number = “ << num << “\n”;
   char  ch  = ‘a’;
   cout  << “ character = “ << ch <<  ‘\n’;
   float fa = - 34 . 45;
   cout  <<  “ real number = “ <<fa << “\n”;
}
Output of the above program
    number = 3
    character = a
    real number = - 34 . 450001
(b)  Cin  The cin is used to read a number, a character or a string of characters from a standard input device, normally the keyboard. The extraction operator (the double greater then sign >>) is use along with the cin operator.
     The general syntax of the cin is
                      cin >> variable 1 >> variable 2 >> …variable n;
For example, the following are certain valid cin member function usage in C++.
     int a,b;
     float f1, f2;
     char c1,c2;
(1)
     cin >> a >> b >> f1 >> f2 >> c1 >> c2 ;
(2)
     cin >> a >> b:
     cin >> f1 >> f2 ;
     cin >> c1 >> c2 ;
(3)
     cout << “ enter two integers \n” ;
     cin >> a >> b ;
     cout << “ enter two floating point numbers \n” ;
     cin >> f1 >> f2;
     cout << “ enter any two characters \n” ;
     cin >> c1 >> c2 ;

PROGRAM
A program to read any two numbers through the keyword and to perform simple arithmetic operations (i.e.; addition, subtraction, multiplication and division) and display the result using cin and cout functions.

/ / using cout stream
#includ <iostream.h>
Void main (void)
{‘
   int a, b, sum, sub, mul, div;
   cout << “ Enter any two numbers” << endl;
   cin >> a >> b;
   sum = a+b;
   sub = a-b
   mul = a*b;
   div = a/b;
   cout << ‘ a = “ << a << “ b = “ << b << “ sum = “;
   cout << sum << endl;
   cout << ‘ a = “ << a << “ b = “ << b << “ sub = “;
   cout << sub << endl;
   cout << ‘ a = “ << a << “ b = “ << b << “ sum = “;
   cout << mul << endl;
   cout << ‘ a = “ << a << “ b = “ << b << “ sum = “;
   cout << div << endl;
}

Output of the above program

      Enter any two numbers
10       20
 a = 10 b = 20 sum = 30
 a = 10 b = 20 sub =  -10
 a = 10 b = 20 mul = 200
 a = 10 b = 20 div  = 0

(c) Cerr and clog  In addition to the function cout, C++ provides other functions of  the class ostream called cerr and clog. They are used to redirect error messages to other devices. The output of cerr is unbuffered, while the output of clog is buffered. The use of the above functions are illustrated below.

    / / using cerr and clog
    #include <iostream.h>
   void main ( )
   {
       cout << “ My name is Komputer ! using cout \n”;
       cerr  << “ many greetings to you ! using cerr \n”;
       clog << “ helloo, computer ! using clog \n”;
   }

Summary of C++ I/O streams
Stream
Meaning
cin
cout
cerr
clog
Keyboard input (stdin)
Screen output (stdout)
Standard error device output (stderr)
Buffered output of standard error (stderr)


  


Saturday, December 24, 2011

Simple C++ program


SIMPLE C++ PROGRAMS
Suppose we would like to display the massage “My name is Komputer, Many greetings to you” on the video screen.
   #include <iostream.h>
   void main ( )  / /  program heading
   {   / / begin
        count  << “My name is Komputer, Many greetings to you”;
   }  / /   end
   The function main ( ) must be placed before the begin statement. It invokes other functions to perform its job. The { symbol or notation is used as the begin statement. The declaration of variables and the type of operations are placed after begin statement. The end statement is denoted by the symbol ‘}’. In C++, the semicolon (;) serves the perpose of a statement terminator rather then a separator.
Statement are terminated by a semicolon and are grouped within braces {…}. Most statements contain expression, sequences of operators, function calls, variable and constants that specify computation.
Variable and function names are of arbitrary lengths and consist of upper and lower case letters, digits and underscore and they may not start with a numeral. All C++ keywords are written in lowercase letters.
Any statement or function within comments are not executable and they are ignored by the compiler. The comments are specified in the following way.
The declaration of the comment statement in the old C style is
/ *  this is a test  * / 
Type any alphanumeric character or statement or function inside the back-slash followed by the symbol  *  (multiplication operator) and should be repeated for termination.
    /*  this is a test
                   program by ravic
                             computer */
The above alphanumeric characters will be ignored by the compiler and is treated as a comment line or remark statement.
      /*    void maim ( )
     {
             cout  <<  “ this is a simple test  \”;
     {
      */
Any executable statement will also be treated as a comment if it is followed by and terminated by the characters / * and * / respectively. The following is the procedure for declaring comments in C++ style.
    The comments may appear anywhere and should begin with the comment delimiter / /.
    For example,
            / / this is a test
            / / this is a new C++ style of remark statement
   There are two advantages of using the comment statement. One, it is easy to understand the variables used in the source program and the other is that it helps in debugging or in tracing the variable by other users.
   The skeleton of a typical C++ program structure is given below:
           program heading
          begin
                    type or variable declaration
                   statement of operation
                  results
        end
   The symbol back-slash (\) followed by a lower case n is used for line feed or a new line. In C++, it is considered as a single character. For Example,
   \n   stands for newline or line feed
A program without using a new line character in the cout stream statement is
    #include <iostream.h>
     void main (void)
     {
         cout   <<    My name is Komputer  “;
         cout   <<    Many greethings to you   “;
     }
Output of the above program
   My name is Komputer    Many greetings to you

Wednesday, December 21, 2011

Statements


STATEMENTS
A statement in a computer program carries out some action. There are three type of statements used in C++; they are expression statement, compound statement, and control statement.

(i)   Expression statement  An expression statement consists of any valid C++ expression followed by a semicolon. The expression statement is used to evaluate a group of expressions.
    For example,
          x = y;  / / the value of y is copied to variable x
          sum = x+y / / the value of x is added with the value of y
                            / / and then assign to the variable sum     
(ii)  Compound statement   A group of valid C++ expression placed within a { and } statement is called a compound statement. The individual statement may be of an expression statement, a compound statement or even a control statement. Note that the compound statement is not completed with a semicolon.
     For example,
         {
                  a = b+c
                  x = x*y
                  y = a+x
         }
(iii) Control statement   The control statement is used for the program flow and to check the conditions of the given expression or a variable constant. The keywords of the control statements are normally a predefined or reserved words and programmer may not use them a ordinary variables.
  For example,
    (1)
          if   (a >b)   {



                                     
          }
   (2)
          while   (condition is becoming true)   {
        


                          
         }

Declaration of Variables


DECLARATION OF VARIABLES
In C, all variable must be declared before defining any executable statement in a program, but C++ allows declaration of the variables before and after executable statements. A declaration is a process of naming of the variables and their corresponding data types in C++.

 Usually, a declaration part is placed after the beginning statement and sometimes, some of the global variables can be defined or declared outside the program. (More derails of global variable are given in chapter 4, “Function and program structures”). A declaration consists of a data type followed by one or more variable names, ending with a semicolon.
    A variable is an object that may take on values of the specified type. The variable must be declared by specifying the data type and the identifier.

The general format of the variable declaration is
     data-type  identifiersl,  id2,. . . idn;
For example,
(1)
     char ch;
     where ch is a character data type.
(2)
      short int x,y;
      where x, y  are short integer data type and hole data size of 16 bits in length.
(3)
      long int x1 ;
      where xl is a long integer data type whose maximum size is 32 bits in length.
(4)
     unsigned int limit ;
     where limit is a variable and it has been declared as an unsigned integer data type.

Tuesday, December 20, 2011

Summary Of C++ Operators


SUMMARY OF C++ OPERATORS
Operator
                Meaning
     Assoclativity
: :
[ ]
( )
.
->
Scope operator
Array element reference
Function call
Structure or class member reference
Point to structure or class member reference




Left to right
!
~
++
--
-
type
new
delete
*
&
sizeof
Logical negation
One’s complement
Incrementer
Decrementer
Unary minus
Type conversion
New operator
Delete operator
Pointer reference (indirection)
Address operator
Size of object






Right to left
*
/
%
+
-
Multiplication
Division
Modulus
Addition
subtraction
Left to right
<< 
>> 
Left shift
Right shift
Left to right
<=
>=
Less than
Less than or equal to
Greater than
Greater then or equal to

= =
! =
Equality
Inequality
Left to right
&
^
|
Bitwise and
Bitwise XOR
Bitwise or
Left to right
&&
| |
Logical AND
Logical OR
Left to right
? :
Conditional statement
Left to right
= += -= *=
/= %= >>=
<<= &= ~= | =
Assignment operators
Left to right
,
 Comma operator
Left to right

Sunday, December 18, 2011

Type Conversion


TYPE CONVERSION
In certain situations, some variables are declared as integer but sometimes it may be required to get the result as floating point numbers. The type conversion is to convert  the set of declared type to someother required type. It is easy to convert values from one type to another type in a C++ program.
   For example,  assume that the following type has been declared
          int   x ;
          float  y ;
The question now arises whether, for example,
          x = y;
Where x is an integer type and  y is a floating point type, is a valid assignment.
The answer  to this question is in affirmative, but we should be aware that truncation will take place. This happen most often between float and double, and between int and char, since converting between float and int or double and int involves cutting off all the decimal places. Conversion can be carried out in two ways,
  • Converting by assignment
  • Using cast operator
(a) Converting by assignment  It is a usual way of converting a value from one data type to another by using the assignment operator (equal to sign).
   For example,    assume that the following type has been declared.
             int   x ;
           float  y ;
The question now arises whether

                x = y;

where x is an integer type and y is a floating point data type, a valid assignment statement or not. This means that we can convert a value from one type to another just by assigning a float variable’s value to a double value variable, a char variable’s constant to an int variable or an int variable to a float variable.
    For example,

        int  x,y,z;
       float a,b,c;
       double devalue;
       x = 10 ;
       a =  3546879.908
       dvalue = 3546879.908
       b = x;
       y = a;
       z = dvalue;

   The first one is an integer value assigned back to floating point number. In the second example, the float variable is assigned back to the integer variable, and in the third, the double value is assignment to the float variable.
   In C++, converting by assignment operator is not recommended to the programmer, as it will truncate the frational or real parts and one may not get the desired results. To avoid this, there is a special way of converting one data type to the other, by using the cast operator.
(b)  Cast operator  Converting by assignment operator is carried out automatically but one may not get the desire result. The cast operator is a technique to forcefully convert one data type to the other. The operator used to force this conversion is known as the ‘cast operator’ and the process is known as ‘casting’.
  The cast operator takes on the format.
          (cast-type) expression;
or
           cast-type ( expression);
As an example, to force a floating point number to an integer, we could use the following.
result = (int) (19.2 / 4) ;
or
result = int (19.2 / 4) ;

the cast operation (int)  cast not only the 19.2 but the entire expression. Thus, results value 4, rather than the entire quotient 4.8. The cast operator takes precedence over most other operations.
     To demonstrate the use of the cast operator, let us consider the following example:
          char ch ;
          int  x,y,z;
          float abc;
          x = (int) ch;
  where ch is a character  variable and force to convert the integer data type
          abc = (float) (y*z) ;
where the expression (y*z)  is an integer data type and force to convert as a floating point number.



Saturday, December 10, 2011

C++ operators


C++ OPERATORS
The different types of C++ operators and their usage are explained in the following sections. In C++, there are some unusual operators used to perform the task of logical decision making, unlike the other higher level languages.

C++ operators    -      Arithmetic operators
                                         
                            -       Assignment operators
                        
                            -       Comparison and logical      -      Relational
                                                            operators     -      Equality        
                                                                                -      Logical
                            -       Bitwise logical operators    
                                                                                              
                                         
                            -       Special operators     -     Unary operators                                  
                                                                           Ternary operators
                                                                           Comma operators
                                                                           Scope operators
                                                                          New and delete
                                                                          Other operators


Arithmetic Operators
Arithmetic Operators are the basis and common operations performed using any computer programming. Normally, these operators are considered as basic operators and known as binary operators as they require two variables to be evaluated. For example, if we want to multiplier two numbers, one has to enter or feed the multiplicand and the multiplier. That is why it is considered as a binary operator. In C++, the arithmetic operators used are as follows:

Operators
Meaning
+
-
*
/
%
addition
subtraction
multiplication
division
modulo (remainder of an integer division)
   The operators  / (slash) for division deserved a special attention. If we divided an integer by another integer, we obtain an integer value.
  39/5  = 7
  If in the division x/y at least one of the operands x and y is of floating point type, the subtraction and multiplication. For the letter operations the value of the result is not seriously affected by the type of operands.
    For example,
    4 + 3 = 7              (integer type)
    4.0 + 3.0 =7.0      (floating point)
  x_integer / y_integer  =  result_integer
  x_integer / y_ float  =  result_ float
  x_ float / y_integer = result_ float
  x_ float /y_ float =  result_ float
  39/7.0 = 5.57
  39.0/7.0 = 5.57
  39.0/7 = 5.57
  39.0/7.0 = 5.57
The result of the division obtained by the / operator is called the quotient. Integer division has another interesting result, namely the remainder, obtained by the operator %.
   For example,
    39 % 5 gives 4 , since 39 = 7*5+4
Expressions  An expression is a collection of data object and operands that can be evaluated to a single value. An object is a constant, variable, or any other expression.
  The most general form is,
                   objectl expression object2
The result is a new data object.
For example,
    2+3 evaluates   5
    3-7 evaluates   -4
Note that the use of the blanks has no effect on the evaluation of the expression. The parentheses are used to improved readability of the program and also to avoid user errors. That means, the evaluation should be carried out as per the precedence rules defined in the C++ compilers.
     Arithmetic operators as per precedence:
            ( )     for grouping the variables
             -          (unary for negative number)
             * /      (multiplication and division)
             + -  (addition and su8btraction)
  For example, if the following expression is not properly grouped using parentheses then the computer will evaluated as per the precedence.
                  
                  x + y * x – z               where   x=5,       y=6   and    z=8
                  5 + (6 * 5) – 8
                  (5 + 30) -8
                  35 – 8
                  27
                                               the result is27 
Suppose, if we intended to evaluate the above expression as (x+y) * (x-z) then the parentheses will be evaluated because it has the highest priority and the result will be different from the previous expression.
      (5+6) * (5-8)
      11 * -3
       -33

Assignment Operators
An assignment operator is used to assign back to a variable, a modified value of the present holding.
Operators
                                           Meaning
=

+=


-=


*=


\=


%=


>>=

<<=

&=

|=

~=
Assign right hand side (RHS) value to the left hand side (LHS)

Value of LHS variable will be added to the value of RHS and assign in back to the variable in LHS

Value of LHS variable will be subtracted from the value of LHS and assign in back to the variable in LHS

Value of LHS variable will be multiplied by the value of RHS and assign in back to the variable in LHS

Value of LHS variable will be divided by the value of RHS and assign in back to the variable in LHS

The remainder will be stored back to the LHS after integer division is carried out between the LHS variable and the  RHS variable

 Right shift and assign to the LSH 

Left shift and assign to the LHS

Bitwise AND operation and assign to the LHS

Bitwise OR operation and assign to the LHS

Bitwise complement and assign to the LHS



  The symbol = is used as an assignment operator and it is evaluated at the last. Remember that equal to (=) is an operator and not an equation maker and hence, it can appear anywhere in place of another operator. The following are valid C++ statements.
a = b = c+4;
c = 3* (d = 12.0/x);
For example,
   x  += y is    equal    to x= x+y
   x   -= y is    equal    to x = x-y;

Comparison and Logical Operators
For program flow, the comparisons as well as the logical operators are required. The com parison and logical operators can be grouped into three. They are relational operators, equality operators and logical operators.
Operators
                     Meaning
<=
>=
==
!=
&&
| |
!
Less than
Greater than
Less than or equal to
Greater then or equal to
Equal to
Not equal to
Logical AND
Logical OR
Not

(a) Relational operators   Relational operators compare values to see if they are equal or if one of them is greater then other and so on. For program flow, the comparators and the logical operators are essential Relational operators in C++ produce only a one or a zero result. These are often specified as “true” or “false” respectively, since these are the only two values possible. The following operators are used to perform the relational operations of the two variables or expressions.
Operators
                     Meaning
<=
>=
Less than
Greater than
Less than or equal to
Greater then or equal to


The relational operators are represented in the following syntax,
         expressionl relational_operator expression2
The expressionl will be compared with expression2 and depending upon the relation like greater then, greater then or equal to and so on, the result will be either “true” or “false”
   For example,
Expression
Result
3 > 4
6 <= 2
10 > -32
(23*7) >= (-67+89)
false
false
true
true
(b) Equality operators  The following operators are used to check the equality of the given expression or a statement. These operators are normally represented by using the two keys, namely, “equal to” by the operator == and “not equal to” by !=. Not that the single “equal to” sign is considered as an assignment operator in C++. Proper care must be taken while using these operators.
Operators
        Meaning
= =
! =
Equal to
Not equal to
  Like the relational operators, the equality operators also produce the result, either “true” or “false”, depending on the condition used in a program. The following examples show the usage of equality operators.
    For example,  a = 4, b = 6, and c = 8
              Expression            Result
              a = = b                   false
              (a*b)  ! = c          true
              ‘s’  = = ‘y’               false

(c) Logical operators  The logical operators && and | | are lower in precedence then the relational operators < and >, which in true are lower than + and -. The operator && is higher in precedence than the operator | |. In some other languages, the logical operators are placed higher than the relational operators, which require parentheses.

Operators
        Meaning
&&
| |
!
Logical AND
Logical OR
Not
(i) logical AND   A compound expression is true when two conditions (expressions) are true. To write both condition, the operator && is used in the following manner,
                     expressionl && expression2
  In the two expressions, the conjunction must be integers. The char data are converted to integer and are thus allowed in the expression.
  The result of logical operators are :
Situation
  Result
true && true
true && false
false && true
false && false
  true
  false
  false
  false

   





For example,
       a = 4, b = 5, and c = 6
       (a < b)  && (b < c)
       (4 < 5)  && (5 < 6)
      true && true
             true
(ii) Logical OR similar to the logical AND is the logical OR, which has the form;
              expressionl | |  expression2
   and evaluates to true if either expressionl or expression2 is true.
           
The result of logical OR operators are:


Situation
Results
true | | true
true | | false
false | | true
false | | false
true
true
true
false
For example,
   a = 4, b = 5 , and c = 6
   (a < b ) | | ( b > c )
   (4 < 5 ) | | ( 5 > 6 )
    true | | false
          true
  
  In the logical OR operator, if one of the expression is true, then it yields true.
(iii) Logical negation operators   A logical expression can be changed from false to true or from true to false with the negation operator !.
    The result of logical negation operators are
  
Situation
Results
! (true)
! (false)
false
true
The general form of the expression
                  ! (expression)
Depending on the condition of the expression, i.e., whether it is true or false, it will complement the result.
   For example,
   a = 4, b = 5, and c = 6
(1)
     !   (a < b ) | | ( c > b )
     !   (4 < 5 ) | | ( 6 > 5 )
     !   ( true)   | | true
     false  | | true
             true
This expression evalutes to true.
(2)
     !   ((a < b ) | | (b > c))
     !   ((4 < 5) | | (5 > 6))
     !   (true     | |    false)
     !   (true)
          false       
  The above expression evaluates to false.
   The negation operator has a higher level of precedence then && and | |. Parentheses are usually necessary to reduce unwanted or unexpected results. Since the logical AND has a higher precedence over the logical OR, care should be taken to use parentheses wherever required.
    For example,
                   expressionl | | expression2 && expression3 | | expression4
In the computer the above will be evaluated as
              expressionl |  |( expression2 && expression3)  | | expression4
Suppose it is intended to evaluated the above compound expression as
             (expressionl | | expression2)  &&  (expression3 | | expression4 )
then, it is advisable to use parentheses to avoid undesirable results.
   For example,
   a = 4, b = 5, and c = 6
(1)
     (a < b) | | (b > c)  &&  (a  >b) | | (a > c)
     (4 < 5) | | ( 5 > 6)  &&  ( 4 > 5) | | ( 5 > 6)
      true | | false && false | | false
      true | | (false && false) | | false
      true | | false | | false
      true | | false
           true
  The logical And has a higher precedence over the logical OR and that is why the above expression evaluates to true.
(2)
      ( (a < b) | | (b > c) ) && ( (a >b) | | (a > c))
      (   (4 < 5) | | ( 5 > 6) ) && (   (  4 > 5 ) | | ( 5 > 6) )
       (true | | false) && (false | | false)
       true && false
             false
To avoid unpredicted or undesirable result it is better that the parentheses are used. For those who are familiar with FORTRAN or PASCAL, the following comparison between the notations for some operators may be helpful.
         
           FORTRAN      PASCAL    C++
                =                       : =            =
           .EQ.                     =              = =
           .NE.                     <>            ! =
           .LT.                      <              <
           .GT.                      >              >
           .LE.                       <=           <=
           .GE.                      >=            >=
           .AND.                    and           &&
           .OR.                      or             | |
           .NOT.                    not             !
            / /                        div             /

Bitwise Logical Operator
There are certain situations wherein bitwise operations are to be performed, and this is possible in C++. The following operators are used for the bitwise logical decision making. Normally, most of the high level programming languages does not support the bitwise operations. The bitwise operators are one of the salient features of C++. The following operators can be performed using bitwise operators:
·        bitwise AND
·        bitwise OR
·        bitwise exclusive OR
·        bitwise left shift
·        bitwise right shift
·         bitwise complement
Operator
Meaning
   &
   ^
   |
   >>
   <<
   ~
Bitwise AND
Bitwise exclusive OR (XOR)
Bitwise inclusive OR
Bitwise left shift
Bitwise right shift
Bitwise complement

(a) Bitwise complement   The complement operator ~ switches all the bits in a binary pattern, that is, all the zeroes become ones and all the ones become zeros. The complement of  a pattern is often useful in signaling and controlling other devices where several different signals may be complementary to each other. The following example show how the bitwise complement works:
Variable
Value
      Binary Pattern
    x
  ~x
    y
  ~y
   23
  132
   ff
  00
    0001 0111 (8 bits)
    1110 1000
    1111 1111
    0000 0000
(a)   Shift operations The shift operations take binary patterns and shift the bits to the left or right, keeping the same number of bits by dropping shifted bits off the end and filling in with zeroes from the other end. C++ provides two types of shift operations, left shift and right shift.
(i)                 Left shift  The<<operator is used for left shifting.
Variable                Value               Binary Pattern
x                              33                     0010 0001 (8 bits)
x << 1               - the bit pattern of the x value is left shifted once.               
x = 33                and the bit pattern is 0010 0001
x << 3                the bit pattern of the x value is left shifted by thrice.
     0 0 1 0 0 0 0 1
0   0 1 0 0 0 0 1 0
0   1 0 0 0 0 1 0 0
1   0 0 0 0 1 0 0 0
The resultant bit pattern will be
                     0 0 0 0 1 0 0 0
(ii)  Right shift  The right shift >> operator is used for right shifting.
     For y = 41, the bit binary pattern is 0010 1001
     For y >> 3, the bit pattern of the y value is right shifted by thrice.
           0 0 1 0 1 0 0 1
           0 0 0 1 0 1 0 0     1
           0 0 0 0 1 0 1 0     0
           0 0 0 0 0 1 0 1     0
The resultant bit pattern will be
                  0 0 0 0 0 1 0 1
(c) Bitwise logical operators  The following are the bitwise logical operators.
  • bitwise
  • bitwise OR
  • bitwise exclusive OR
(i) Bitwise AND   The bitwise AND operation will be carried out between the two bit patterns of the two operands. For example,
Variable
Value
Binary Pattern
   x
   y
   x & y
   a
   b
   a & b
   5
   2
   0
   6
   3
   2
   0101
   0010
   0000
   0110
   0011
   0010
  To generate a l bit in the result, bitwise AND need a one in both numbers. Masking bits can be done using AND. The most useful part of the bitwise operations is a bitwise AND. Normally, it is called a mask operator and one may select the particular pattern as either a one or a zero and it select certain specific bits and ignores the others.
(ii)  Bitwise OR    The bitwise OR operations are similar to the bitwise AND and the result is l if any one of  the bit value is l. The symbol | represent the bitwise OR.
   For example,
Variable
Value
Binary Pattern
   x
   y
   x | y
   a
   b
   a | b
   5
   2
   7
   6
   1
   7
  0101
  0010
  0111
  0110
  0001
  0111 









(iii)  Bitwise exclusive OR   the bitwise exclusive OR will be carried out by the notation^. To generate a l bit in the result, a bitwise exclusive OR needs a one in either number but not both.
Variable
Value
Binary Pattern
   x
   y
   x ^ y
   a
   b
   a ^ b
   5
   2
   7
   6
   3
   5
  0101
  0010
  0111
  0110
  0011
  0101 









All the bitwise operators may appear with the assignment operator just like the arithmetic operators discussed earlier.

Expression         Meaning
n >>= 1               n = n >> 1
                            n will be shifted right by 1 and than assigned back to     
                            variable n         
a <<b                   a = a << b
                          the content of the a will be shifted left by the content of     
                          b and the assigned back to a
x &= 4              x = x & 4
i  ^= 4           x = x & 4
j  |= 5            j = j | 5
 Special Operators
There are some special operators used in the C++ language to perform particular type of operation. The following operators are considered as unary operators in the C++ language.

(a)  Unary operators   The unary operators require only a single expression to produce a line. Unary operators usually precede their single operands. Sometimes, some unary operators may be followed by the operands such as incrementer and decrementer. The most common unary operation is unary minus, where minus sign precedes a numerical constant, a variable or an expression.

     The following operators are the unary operators in C++:]

Operator
   Meaning
*

&
-
!
~
++
--
type
sizeof
Contents of the storage field to which a pointer is pointing ( refer chapter 6)
Address of a variable (refer chapter 6)
Negative value (minus sign)
Negation ( 0.if value # 0, l ,if value =0)
Bitwise complement
Incrementer
Decrementer
Forced type of conversion
Size of the subsequent data type or type in byte
(i)                 Pointer operator (*)  The pointer operator is used to get the content of the address operator pointing to a particular memory element or cell.
(ii)          Address operator(&)  The address operator & is used to get the address of the other variable in an indirect manner. The pointer operator (*) and the address (&) are explained in Chapter 6 on “pointers.”
(iii)         Size of operator  The sizeof operator is used to give the direction to the C++ compiler to reserve the memory size or block to the particular data type which is defined in the structure type of the data in the linked list. This operators are explained in chapter 7 on “structures, Unions and fields.”
(iv)        Incrementer and decrementer  Two special operators are used in C++, namely, incrementer and decrementer . These operators are used to control the loops in an effective manner.
Incrementer: The ++ symbol or notation is used for incrementing by 1.
    For example,
       ++i; is equal i = i+l;
       i++; is equal to i = i+l;
  There are two type of incrementers: prefix incrementer (++i) and postfix incrementer (i + +). For the time being, let us take it that they can be used according to a programmer’s liking but there are some special condition under which these incrementers are used very particularly.

  In prefix incrementer, first it is incremented and then the operations are performed. On the other hand, in the postfix incrementer, first the operations are performed and then it is incremented. However, the result of the incremented value will be the same in both the causes.
     For example,
           i = 7;
           x = ++I;
           x = i++;
  After execution, the value of x will be set to 8.
Decrementer:  The decrementer is also similar to the incrementer. The – symbol or notation is used for decrementing.
   For example,
       --i  is equal to i = i-l
       i-- is equal to i = i-l;
   In this also there are two types of decrementers, prefix decrementer ( --i ) and postfix decrementer ( --i ).
(v)    Cast operator  There are situations,. Where some variable are declared as integers but sometimes it may be required to get the result as floating point numbers. The type provides a specific and a special way for converting one data type to the other using a cast operator.
(b)   Ternary operator (?:)  C++ includes a very special operator called the ternary or conditional operator. It is called ternary because it uses expressions. The ternary operator acts like a shorthand version of the if-else construction. The general format of the ternary operator is:
     expressionl ?expression2 : expression 3
Which results in either expression2 or expression3 is evaluated. The conditional operator is used in place of a single if-else to make an assignment.
  For Example  
       if  ( value % 2 == 0 )
             even = true
       else
             even = FALSE;
This can be written as
       even = (value % 2 == 0 ) ? TRUE : FALSE ;
Another example would be to find the large of two number,
        if (first > second)
            max = first ;
      else
            max = second;
This can be written as
            max = ( first > second ) ? first : second ;
(c)  Comma operator  C++ uses the comma in two ways. The first use of comma is as a separator in the variable declaration.
      int a,b,c;
      float  x,y,z;
Another use is as an operator in an expression for loop. It is explained in detail in the chapter 3 on “Control statements”.

(d)  Scope operator(::) The double colon : : is used as the scope resolution operator in C++. The scoping operator is also used in a class member function definition. The scope operator can also be used to differentiate between member of base classes with identical names. It is explained detail in the chapter 8 on “Classes and objects”.
(e) New and delete operators  in traditional C, the dynamic memory allocations and deallocations are handled through library functions such as malloc, alloc, calloc and free routines. C++ defines a new and delete operators.
(f) Other operators
   (i) Parentheses for grouping expressions
   (ii) Membership operators
Parentheses for grouping expressions ()  The precedence and associativity of each operator determines whether it takes effect before or after the next operator in an expression. Often, it is more convenient control this order of evaluation. When parentheses are put around an element of an expression, the element evaluates before anything outside the parentheses.
    For example,
    (a+b)* c wpuld cause the addiotion to be performed the multiplication, whereas a+b*c would cause the multiplication to be performed.

Membership operator  There are several kinds of variables used in C++, containing a set of values, membership operator are used, which are represented as []       ->