Docstoc

Data Types, Operator And Expression

Document Sample
Data Types, Operator And Expression Powered By Docstoc
					                                                                                  E3062/4/1

                              Data Types, Operator And Expression




      UNIT 4


            Data Types, Operator And Expression



                                 OBJECTIVES




General Objective     : To Introduce and Use the data types, operator and
                        expression in C++ Programming.



Specific Objectives : At the end of the unit you will be able to :

                             describe the essential data type : int,char,float and double
                             declare constant and variable
                             able to use constant and variable
                             explain the arithmetic operator types
                             explain the arithmetic, relational and logical operator types
                             able to used operators to construct expression
                                                                            E3062/4/2

                      Data Types, Operator And Expression




                               INPUT 4



                               We will look at the basic elements
                               need to construct a C++ program
                               including the C++ data types, constant,
                               variable, operator and expression.




4.0    INTRODUCTION TO DATA TYPES, OPERATOR AND
       EXPRESSION IN C++ PROGRAMMING.

The C++ character set includes the keyboard characters, namely the
uppercase letter A - Z, the lower letters a – z , the digits 0 – 9 , and other special
characters (such as!, #, [, ] , ,&,<,?, and * ). The blank space is also a character in
the set.
         Identifiers are simply references to memory location which can hold values.
They are formed by combining letters (both upper and lowercase), digits and the
underscore( _ ). The first character of an identifier, however, must be a letter. The
blank character is not permitted in an identifier. Although identifiers can be formed
by freely combining the letters, digits and underscores, common sense tells us that
we should give them suggestive names, that is, names that reflect the data items that
they are going to store. Identifiers can be of any length although in practice they
seldom exceed 25 characters.
                                                                          E3062/4/3

                        Data Types, Operator And Expression




Example of valid and invalid identifiers:

Table 4.1
 Valid Identifier    Invalid Identifier           Comment
 x                  “x”                   Illegal character
 Sumx2              2sumx                 Illegal first character
 Hourly_rate        Hourly-rate           Illegal character -
 name               name@                 Illegal character @
 GROSS_PAY          GROSS PAY             Illegal blank

        C++ identifiers are case-sensitive, meaning, lower and uppercase letter in
identifiers are treated as different characters. This means we cannot freely mix the
lower and uppercase letter to refer to the same identifier. For example, identifiers
HOURLY_RATE, Hourly_Rate, Hourly_rate and hourly_rate are all different, they
refer to different memory locations.
        Variables are identifiers whose value may change during the course of
execution of a program.
        Keywords in C++, also called reserved words, have standard, predefined
meanings and must be used only for their intended purpose. Programmers therefore
should not use these keywords as identifiers.



4.1    Basic Data Types

There are four main data types in programming C++

       i.      int
       ii.     char
       iii.    double
       iv.     float

For additional of basic data types programming C++ can support another built-in
data types such as short, long, signed and unsigned. The various data types, the
number of bits required to store them, and their range are shown in Table 4.1
                                                                       E3062/4/4

                    Data Types, Operator And Expression


Table 4.2
 Data Type                C++ Keyword      Bits     Range
 Integer                  int              16      -32768 to 32767
 Long integer             long             32      -42994967296 to 4294967295
 Short integer            short            8       -128 to 127
 Unsigned integer         unsigned         16      0 to 65535
 character                char             8       0 to 255
 Floating point           float            32      Approximately 6 digits of
                                                   precision
 Double floating          double           64      Approximately 12 digits of
 point                                             precision



      4.1.1   Integer data types - int

      Key words int is use to declare variable integer number

              Syntax         int name_identifier
              example :      int bilangan ;
                             int nom1,nom2;

             This declaration means that the compiler was asked to hold integer
      data name bilangan, nom1 and nom 2. Integer data types is classified as sign
      (+) and unsigned (-).For all the computer system, data integer is refer to 0
      and 1 bits. There are three types of integer short int, int, long int. The
      comparison of this integer range in value.

              Short int :   -32768 to 32767
              Int :         -32768 to 32767
              Long int ;    -2147483648 to 2147483648
              Unsigned short int: 65535
              Unsigned int:        65535
              Unsigned long int : 4294967295
                                                                  E3062/4/5

              Data Types, Operator And Expression


4.1.2   Character data types - char

Storage word char is use to declare variable character

        Syantax       char name_identifier
        example:      char huruf;
                      char lagi;



      This declaration means that variable lagi and huruf will given a
memory storage for character data type. Character variable store printed data
or un printed data in character set of computer includes;
       small and capital letters
       decimal digits (0-9)
       special character

       This character represent in 1 byte (8 bit) computer memory. Internal
representative for character value decided by encoder character (ASCII or
EBCDIC) that is used in the computer.



4.1.3   Floating Point data types - float and double

This type can store floating point in computer memory.

        Syntax :      double name_identifier
        Example:      double pendapatan_bersih,cukai_pendapatan;
                      double nilai;

        Memory storage that use for variable pendapatan_bersih be able to
store floating point data. But int and char data types only can be stored
according to computer types. The three floating points data in C++ such as;

        1. float
        2. double
        3. long double
                                                                           E3062/4/6

                      Data Types, Operator And Expression




       The comparison of the three types are range value and digits.

               Float : 1.175494e-38 to 3.402823e+38     (6 place decimal )
               Double : 2.225074e308 to 1.797693e+308 (15 place decimal)
               Long double : 3.362103e-4932 to 1.189731e+4932 (19 place dec.)

4.2    Declaring Constant

Constant are values that do not change during program execution. They can be of
type integer, character or floating point. To declare a constant, use the keyword const
as in the example

               Const int days_of_week=7;



      Constants       data type       identifier



       4.2.1   Integer constant

       Integer constant can be further categorized into four types-short integer,
       integer,unsigned integer and long integer.
       Examples of integer constants
                Short integer constant:
                      -99            -35             0              45      320
                Integer constants:
                       9999          -1              0              555     32767
                Unsigned integer constants:
                      1              256             1000           60000
                Long integer constants:
                      222            0               33333          9999999

              A constant can also be identified as being long by tagging a l or a L to
       the end of the number, For example , the constants 212L and 323l. will be
       viewed by C++ as long constants.
                                                                           E3062/4/7

                        Data Types, Operator And Expression




       4.2.2     Character and string Constants

       A character constant is any character enclosed between two single quotation
       marks (‘ and ‘ ). When the several characters are enclosed between two
       double quotation marks (‘ and ‘ ), it is called a string. Examples of character
       and string constants;

       i.        Character constants:
                    ‘$’        ‘*’              ‘ ‘           ‘z’           ‘G’

       ii.       String constants:
                     “Name:”              “Telephone No:”            “Postcode:”

       iii.    Floating Point Constants
               A floating point constant is a decimal number that contains the
       decimal point (.) or the exponent ( e or E ) or both. Here are some examples
       of floating point constants.
                       5.0            0.005                   2000.0        987.123
                       5e-3           0.01e-2                 0.2345E8      1.23E4

4.3 Declaring Variables

All variables in a program must be declared prior to their use. The declaration takes
the form

       Type variable_list;

    Data types      variable identifier

Examples of variable declarations.

       Int x, y, z;
       Short small_number;
       Long big_number;
       Unsigned positive_number;
       Char ch;
       Float amount, rate;
                                                                           E3062/4/8

                       Data Types, Operator And Expression




Variables may be initialized by assigning constants to them either at the time of their
declaration or at a later time.

Example of variable initialization and declaration

int m, n=10;
float rate, total = 0.0;
char response= ’n’;
char color{6}=’green’;
                                                                   E3062/4/9

                    Data Types, Operator And Expression




                    Activity 4A




TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE
NEXT INPUT…!



4.1   State 4 main data types and C++ keyword ?
      a. Data types__________________              Keywords___________
      b. Data types__________________              Keywords___________
      c. Data types__________________              Keywords___________
      d. Data types__________________              Keywords___________



4.2   Write an expression to declare constant and variable?
      a. constant :________________________
      b. variable: ________________________
                                                                       E3062/4/10

                      Data Types, Operator And Expression




                              Feedback To Activity 4A




4.1.
       a. Data types: integer                        Keywords :   int
       b. Data types : character                     Keywords:    char
       c. Data types : double                        Keywords :   double
       d. Data types : floating point                Keywords ;   float

4.2.
       a.     constant : const Int hourly_rate
       b.     variable: Int a, b, c
                                                                         E3062/4/11

                      Data Types, Operator And Expression




                                 INPUT 4




4.4 The Operators

C++ is very rich in built-in operators. Operators trigger some computations when
applied to operands in an expression. There are several general classes of operators.
But for now, we will present just the arithmetic, relational, logical and assignment
operators.

       4.4.1   Arithmetic Operators

       There are seven arithmetic operators in C++ as shown in Table 4.3

               Table 4.3
                 Operator                  Action
                     -                  Subtraction
                     +                    Addition
                     *                 Multiplication
                     /                    division
                     %                Modulus division
                     -                  Decrement
                    ++                   increment
                                                                  E3062/4/12

              Data Types, Operator And Expression




Examples of operation involving integer variables. With a=7 and b=2, the
expression on the values on the right.

             Table 4.4
                    Expression                       Value
                       a–b                             5
                       a+b                             9
                       a*b                            14
                       a/b                             3
                       a%b                             1
                       a--                             6
                       a--                             3



        Note: You can assign a positive or negative number to a variable by
using a unary +

or - . Example:
        a = -20       // assigns ‘a’ a negative 20
        b = +20       // assigns ‘b’ a positive 20 ( + sign normally not
                      needed)

Unary operators operate on single value. Thus the size of operator is a unary
operator. So are the decrement and increment operator.

4.4.2 Relational Operators

There are six relational operators and three logical operators in C++ are
shown in Table 4.5 and Table 4.6
                                                                      E3062/4/13

                Data Types, Operator And Expression




                Table 4.5
                 Operator       Meaning
                 <              Less than
                 <=             Less than or equal
                 >              Greater than
                 >=             Greater than or equal
                 ==             Equal
                 !=             Not equal

        The result of evaluation of a relational operation is either
true(represented by 1) or false (represented by 0). For example, if a = 7 and b
= 5, then a < b yields 0 and a != b yields 1.

4.4.3    Logical Operators

There are three logical operators in C++ are shown in Table 4.6

        Table 4.6
               Operator                    Meaning
                  &&                        AND
                   ||                        OR
                   !                        NOT



The result of the logical operations on a and b are summarized as Table 4.7:

Table 4.7
                    a||b              a&&b                     !a
   a      b     either a or b       Both a and b          Produces the
                must be true        Must be true        opposite relation
  0       0           0                  0                     1
  0       1           1                  0                     1
  1       0           1                  0                     0
  1       1           1                  1                     0
                                                                         E3062/4/14

                      Data Types, Operator And Expression




   *Hierarchy of Operators
       The hierarchy of operator precedence form highest to lowest is summarized
   below:

          Table 4.8
           Operator Category                          Operator
           Unary                                      - -- ++
           Arithmetic multiply, devide, remainder     + / %
           Arithmetic add and subtract                + -
           Relational operators                       < <= > >=
           Equality operators                         == !=
           Logical AND                                &&
           Logical OR                                 ||



4.5 The Expression

Expression in C++ are formed by properly combining operators, variables and
constants. We have already seen some examples of simple arithmetic and logical
expression. As algebra, C++ expression can be complex. Parentheses can be used to
force the order of evaluation. An expression may also contain spaces for readability.
Examples of expressions.

       Gross_pay – deductions
       (basic_pay + hours * rate) – (socso + premium + loan)
       (b * b – 4 * a * c) > 0
       (gender = = ‘m’) && (age > 20)
       (gender = = ‘m’ || gender = = ‘f’ ) && age >= 21
                                                                       E3062/4/15

                      Data Types, Operator And Expression




                      Activity 4B




TEST YOUR UNDERSTANDING BEFORE YOU CONTINUE WITH THE
NEXT UNITS…!



4.3   Classify the operators given below:

      - , +, &&, ++ , <= , ! , * , !=, % , = =

4.4   Write an expression to mention the arithmetic relational and logical
      operators?
                                                             E3062/4/16

                       Data Types, Operator And Expression




                               Feedback To Activity 4B




4.3.
       a. arithmetic operators : - , + , ++ , *
       b. logical operators    : && , !
       c. Relational operators : <= , != , = =



4.4.
       ( a + b * 2 ) – (x + y + z) – arithmetic
       (sex = = ‘m’ || sex = = ‘f’ ) && age >= 21
                                                                      E3062/4/17

                    Data Types, Operator And Expression




     KEY FACTS


1. To construct a C++ program, we have to look at basic elements of data types,
   identifiers and constant and variable declaration.

2. The arithmetic, relational and logical operators is to trigger some computations
   when applied to operands in an expression .
                                                                          E3062/4/18

                      Data Types, Operator And Expression




                       SELF-ASSESSMENT




You are approaching success. Try all the questions in this self-assessment section
and check your answers with those given in the Feedback on Self-Assessment 14
given on the next page. If you face any problems, discuss it with your lecturer.
Good luck.


Question 4-1


Write a statement (or comment) for the sentence below;
       a. State the program to determine three integer number.
       b. Declare the variables x , y, z and hasil as integers type.
       c. Show the message where the user can input the three integers.
       d. Read three integers value from keyboard and save every value into
            variables x , y and z.
       e. Calculate the multiplication integer that store in variable x,y ,z and
            variable hasil
       f. Print “Hasil darab ialah” followed by variable hasil.




Question 4-2

Using the statement that you write in statement for question no.1, write the complete
program to calculate and printed multiplication of the three integers.
                                                                            E3062/4/19

                         Data Types, Operator And Expression




                         Feedback To Self-Assessment



Have you tried the questions????? If “YES”, check your answers now.

Question 4-1
          a. // Program to determine three integer multiplication
          or
          /* Program to determine three integers multiplication*/
          b. int x, y, z, hasil;
          c. cout << “Enter three integers number:”;
          d. cin >> x >> y >> z;
                   or
              cin >> x;
              cin >> y;
              cin >> z;
          e. hasil = x * y * z;
          f. cout << “Multipication is :” << hasil;

   Question 4-2
         /* Program to determine three integer multiplication*/
         # include <iostream.h>
         int x, y, z, hasil;
         void main( )
                                                                CONGRATULATIONS
         {                                                      !!!!…..May success be
                  cout << “Enter 3 integer number:”;            with you always….
                  cin >> x >> y >> z;
                  hasil = x * y * z;
                  cout << “Multipication is :” << hasil;
         }

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:17
posted:2/29/2012
language:English
pages:19
Description: Data Types, Operator And Expression C