Tuesday, 30 September 2014

2. Data types, Operators, Expression

Chapter : 2
Data types, Operators, Expression

  • Character set, tokens, identifiers, keywords
  • Data types
  • Variables, reference variable, constants
  • Operators, operator precedence and associativity
  • Dynamic initialization of variable
  • Expressions and qualifiers
  • The iostream.h file
  • cin and cout operators
  • Cascading of operators


Programming language is a set of rules, symbols, and special words used to construct programs. There are certain elements that are common to all programming languages. Now, we will discuss these elements in brief.                                                                                                  

Character set :    Character set is a set of valid characters that a language can recognize.

Letters
A-Z, a-z
Digits
0-9
Special Characters
Space  +  -  *  /  ^  \  ()  []  {}  =  !=  <>  ‘  “  $  ,  ;  :  %  !  & ? _  #  <=  >=  @ 

      Tokens  :     A token is a group of characters that logically belong together. The programmer                                     can write a program by using tokens. C++ uses the following types of tokens.
               
                                   Keywords, Identifiers, Operators, Literals, Punctuates.

      Identifiers  :   Symbolic names can be used in C++ for various data items used by a                 programmer in his program. A symbolic name is generally known as an identifier. The identifier is a sequence of characters taken from C++ character set. The rule for the formation of an identifier (Variable names) is:
1.      An identifier can consist of alphabets, digits and/or underscores.
2.      It must not start with a digit
3.      C++ is case sensitive that is upper case and lower case letters are considered different from each other.
4.      It should not be a reserved word.

       Keywords  : These are some reserved words in C++ which have predefined meaning to compiler  called keywords. It is discussed in previous section.
       Keywords are reserve words whose meaning is already known to compiler.
       Following is list of keywords in c++

asm
else
private
Template
auto
enum
protected
try
Break
extern
public
typedef
case
float
register
union
catch
for
return
unsigned
char
friend
short
virtual
class
goto
signed
void
const
If
sizeof
volatile
continue
inline
Static
while
default
int
Struct

delete
long
Switch

do
new
this

double
operator
throw



      Data Types In C++ : 
"     A data type defines which kind of data will store in variables and also defines memory storage of data" 
      C++ supports a large number of data types. The built in or basic data types supported by C++ are integer, floating point and character. 



       Built In Data-Types :  These data types are provided by system
       Derived Data-Types :  These data types are derived from built in data types
       User Define Data-Types :  these data types are created by user as per there requirements

       Some commonly used data types are summarized in table along with description

Type
Description
int
Small integer number
long int
Large integer number
float
Small real number
double
Double precision real number
long double
Long double precision real number
char
A Single Character


        Integer  :    (int, long int, short int)
       These data type holds numeric values which are without decimal point, they can be positive or  negative.
        Example : 12, -23, 14

int
          1. int keyword is used for integers.
          2. It takes two bytes in memory.
          3. The range of int is -32768 to 32767
          4.  We use long int to stored long range integer numbers
          5. Long int takes 4 bytes in memory.
          6. The range of long int is -2147483648 to 2147483648

               Data type                Bytes               Range  of values 
          int                                2                -32768 to 32767
          long int                        4                 
-2147483648 to 2147483648

      Floating Point :   (float, double)
      These data types holds numeric values which contains decimal point, they can be positive or negative
      Example : 12.34, -56.78, -90.09


              Data type                Bytes         Decimal places         Range  of values 
        float                          4                        6                         
3.4E -38 to3.4E+38
        double                      8                        15                        
1.7E - 308 to1.7E +308

     Character :
A keyword char is used for character data type.
This data type is used to represents letters or symbols.
A character variable occupies 1 byte on memory.
Example : ‘A’, ‘z’, ‘#’, etc.

Variables  :
        A variable provides us with named storage that our programs can manipulate.
      
       Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

      The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive.
  

           Syntax for variable declaration :
                                                                    Data_Type  Variable_Name;

           Example :         int a, b, c;
                                    float f;
                                    double balance;
                                    char ch;
          Variable Initialization :    assigning value to the variable is known as variable initialization
           Example :                   
o   int a = 20;    (Here we initialize variable at the time of declaration)
o   char ch;
                        ch = ‘A’;       (Here we first declare variable then initialize it)           


       Reference variables :   A reference variable provides an alias (alternative name) for a previously defined variable. For example:
       int total = 100;
       int &t  = total;

      It means both total and t are same

       cout<<total;
       cout<<t;
      Will return same value;
      We use & operator to show reference.
      & is reference operator not addressing operator.
      If we made any change in value of t then it reflects it in total

      Constants  :

A variable which does not change its value during execution of a program is known as a constant variable. 

Any attempt to change the value of a constant will result in an error message. A constant in C++ can be of any of the basic data types, const keyword can be used to declare constant as shown below:

const float PI = 3.1415;

The above declaration means that PI is a constant of float types having a value 3.1415.
Examples of valid constant declarations are:

         const int RATE = 50;
        const float PI = 3.1415;
        const char CH = 'A';



     Operators :
     Operators are special symbols used for specific purposes. Operator operates on operand (variables).
     Basically we differentiate operators by number of variables on which they perform operation

Unary Operator : These operators operates on single operand (variable).
Example :  - (unary minus),  ++ (increment operator), -- (decrement operator)

Binary Operator : These operators operates on two operands (variables).
Example : + (plus), - (binary minus), * (multiplication), / (modulo), etc.

Ternary Operator : These operator operates on three operands.
Example :  ?: (Conditional operator)


        Arithmetic Operators :
                   Arithmetical operators +, -, *, /, and % are used to performs an arithmetic (numeric) operation.
                   You can use the operators +, -, *, and / with both integral and floating-point data types. Modulus or    remainder % operator is used only with the integral data type.
 These operators take two operands (variables) to perform operation that’s why they are known as  binary operators.

         Relational Operators :
                   The relational operators are used to test the relation between two values.
                    All relational operators are binary operators and therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true. The following table shows the relational operators.
Relational Operators
Meaning
Less than
<=
Less than or equal to
==
Equal to
Greater than
>=
Greater than or equal to
! =
Not equal to


      Logical Operators :
            The logical operators are used to combine one or more relational expression. The logical operators are

Operators
Meaning
||
OR
&&
AND
!
NOT

      Increment and Decrement Operators
                  C++ provides two special operators viz '++' and '--' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable but it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post.
      The syntax of the increment operator is:
                                  Pre-increment: ++variable
                                  Post-increment: variable++
The syntax of the decrement operator is:
                                  Pre-decrement: --variable
                                  Post-decrement: variable--

      Assignment Operator :
      The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression on its right-hand-side and places it into the variable on its left-hand-side. For example:

       x = 30;

     Compound assignment Operator :
Operator
Example
Equivalent to
+ =
A + = 2
A = A + 2
- =
A - = 2
A = A - 2
% =
A % = 2
A = A % 2
/=
A/ = 2
A = A / 2
*=
A * = 2
A = A * 2

      Conditional operator
      The conditional operator ?: is called ternary operator as it requires three operands. The format of the conditional operator is:
Conditional_ expression ? expression1 : expression2;
If the value of conditional expression is true then the expression1 is evaluated, otherwise expression2 is evaluated.
               int a = 5, b = 6;
               big = (a > b) ? a : b;

The condition evaluates to false, therefore biggets the value from b and it becomes 6.

        Dynamic Initialization of Variable :
                  Where we don’t know the value of variable at compile-time, its computed (calculated) at run-time is known as dynamic initialization of variable

      Example :   
                        //  HERE WE INITIALIZE rad AT THE TIME OF DECLARATION
                        Int rad = 5;
                        Const float pi = 3.14;
                        Int area;
                        //  HERE WE INIALIZE  area DYNAMICALY
                        area = pi * rad * rad;
                        cout<<” Area of Circle is : ”<<area;


       Expressions and qualifiers :

       Qualifiers :  The type qualifiers provide additional information about the variable the precede.
       Type qualifiers give one of two properties to an identifier
       Example :  The const type qualifier declares an variable to be constant, means we can’t change its value.

const
Objects of type const cannot be changed by your program during execution
volatile
The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.

restrict
A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.



      Operators Precedence and associativity :
                        Operator precedence determines the grouping of terms in an expression. This affects how as expression is solve.
                        Certain operators have higher precedence than other;
      Examle : * has higher precedence than + operator.

            X = 7 + 10 * 2;
            Here x is assigned 27, not 34
            X = 7 + 10 * 2
            X = 7 + 20
            X = 27


Operator
Associativity
1
()  []
Left to right
2
* , /,  %
Left to right
3
+ , -
Left to right
4
< , <=,  >,  >=
Left to right
5
==,  !=
Left to right
6
&&
Left to right
7
||
Left to right
8
?:
Right to left
9
=,  +=,  -=,  *=,  /=,  %=
Right to left


       The iostream.h file :  
                    iostream.h is important header file in C++, use for input (cin) and output (cout) operations. In C++ input/output occurs in streams, which are sequences of bytes.
(     iostream.h : InputOutputStream headerfile)
                    If bytes flow from a device likes a keyboard, a disk drive, or a network connection, etc., to main memory, this is called input operation.
                    If bytes flow from main memory to a device likes a display screen, a printer, a disk drive, or a network connection, etc., this is called output operation.
  This file defines the cin, cout, cerr and clog objects, which correspond to the standard input stream, the standard output stream, the un-buffered standard error stream and the buffered standard error stream, respectively.   

Example :
                        Cout << ” Hello ”;
                        Cin >> x;
       
       Cin and Cout Operators :
·         
       Cin Operators (>> Extraction Operator) :  these operators use to take input from keyboard.

        Example :        int a;
                                 cin >> a;
      
·         Cout Operator (<< Insertion Operator) :    these operators use to display output on screen (console     window).
        Example :        cout<<” Good Morning Class…!!!”;
                                cout<<a;

     Cascading of operators :
            Successive occurrence of input and output operators (“>>” and “<<”) in C++ can be concatenated.

            We have used the extraction operator << repeatedly in the two statements for printing results.
Example : cout<<”Total Value is =”<<total<<”\n”;

              First sends the string “Total Value is=” to cout and then sends the value of sum. Finally, it sends the new line character so that the next output will be in the new line. The multiple use of << in one statement is called cascading. When cascading an output operator, we should ensure necessary blank spaces between different items. Using the cascading technique, the last two statements can be combine as follows. 

Cout<<”Total Value is=”<<total<<”\n”<<”average = “<<average;
This is one statement but provides two lines of output. 
Total Value is = 15 
Average = 7.5 

                 We can also cascade input operator >> as shown below 
cin>>n1>>n2>>; 
the values are assigned from left to right. That is, if we key in two values, say, 15 and 24 then 15 will be assigned to n1 and 24 will be assigned to 

1 comment:

  1. Vip League 2: Tipster on youtube
    Vip League 2: Tipster on youtube Vip League 2 is youtube convert to mp3 a video game, developed and released in 2016 by Kiron Interactive, one of the leading developers

    ReplyDelete