Make your own free website on Tripod.com

Lesson 2:- Constraints, Variables and Data Types.

Prev || Home || Next

Bar_line.gif (11170 bytes)

Character Set Of C:

1) Letters :- Uppercase A to Z.

                    Lowercase a to z.

2) Digits :- All decimal digits 0 to 9.

3) Special characters :-

    , comma                 . period

    ; semicolon               : colon

    ? question mark       ' apostrophe

    " double quote          ! exclamation mark

    | pipe                        \ backslash

    ~ tide                        _ underscore

    $ dollor                     % percent

    # number sign            & ampersand

    ^ carat                       * asterik

    - minus                      + plus

    < less than                 > greater than

    () parenthesis            [] square brackets

    {} braces

    C supports some special backslash character constants that are used in output functions. Each one of them represents one       character. These character combinations are known as escape sequences they are

    \a audible bell             \b back space

    \f form feed                 \n new line

    \t horizontal tab            \0 null character

4) White spaces :

    Blank space, horizontal tab, carriage return, new line & form feed.

 

C Tokens:

   In a C program, the small individual units are known as C tokens. C has 6 types of tokens.

    Every C word is classified as either keyword or identifier.

    Example:-

    #include <stdio.h>

    #define Max 500

    main()

    {

        int k=70;

        float j=23.56, sum1;

        char code='d';

        sum1=k+j;

        clrscr();

        printf("Sum of two numbers :%f",sum1);

        getche();

    }

    In the given example:

    Keywords are  int, float, char.

    Identifiers are a, k, sum1.

    String constants are "Sum of two numbers".

    Singles character constants is code.

    Special symbols are #, {, }.

    Operators are + , -.

 

Keywords:

    All keywords have fixed meaning which cannot be changed. All keywords must be written in lower case.

        auto             default             goto             short

        break           do                   if                 struct

        case             double             int               switch

        char             else                  long            union

        const           float                 register        void

        continue       for                   return          while

 

Identifiers:

   These refer to name of variables, functions & arrays. These are user defined names & consist of a sequence of letters & digits with a letter as first character. Both uppercase & lowercase are allowed but lowercase etters are reffered. ex:- basic, salary, name, emp_no, etc,

 

Constants:

    Constants in C refer to fixed values that do not change during execution of a program.

      Types of constants are as follows:-

        Integer Constants:- A number which does not contain fractional part in it. It refers to sequence of digit ex. 123, -75.

       Real Constants:- A number which contains fractional part or decimal point in it. The numbers                                     containing fractional parts are called real numbers. ex.0.0083, -0.75, 43.35 .

        Single Character Constants:-  It's a single character enclosed in the single quotes. ex. '5', 'x' .

                                                     The character constant '5' is not same as number 5.

                                                      Character constants have integer values known as ASCII values.

                                                       ex. printf("%d",'a'); would print the numbers 97, the ASCII value                                                          of letter a.

                                                       ex.printf("%c",'97'); would print a letter a.

                                                       Since each character constant represents an integer value it is also                                                          possible to perform arithematic operations on character                                                          constants.

        String Constants:- A string constant is a sequence of charcters enclosed in double quotes.

                                     eg."Hello", "`1999", "Well Done", "x". 'X' is not equivalent to "X".

       Defining Symbolic Constants:- We often use certain unique constants in program. These                                                          constants may appear repeatedlyin a number of places in the                                                          program i.e. the value of mathematical constant "pi" which is                                                          3.142. While dealing with such programs we face two problems                                                          first is of modification in the program and another is                                                          understanding the program. Assignement of such constants to a                                                          symbolic name frees us from these problems. It can be defined                                                          as below

    #define STRENGTH 100

    #define PI 3.14159

    #define MAX 200

    1) These are constants and not variables.

    2) No blank space is allowed between # and define.

    3) # must be first character in the line.

    4) #define must be declared before main().

    5) It should not end with semicolon(;).

    6) The name must be in the uppercase.

        Now we can use these constants anywhere in the program with their symbolic names.

                                                           

Variables:

    A variable is a data name used to store a data value. Unlike constants, a variable may take different values at different times during execution.

    Rules to write a variable name:-

    1) It must start with a letter.

    2) The name should not be a keyboard.

    3) White space is not allowed.

    4) C allows a length of 31 characters.

    5) Only underscore( _ ) is allowed in the variable name.

 

Data Types:

    C supports four classes of data types.

    1) Primary Data Types.    2) User Defined Data Types.    3) Derived Data Types.    4) Empty Data                                                                                                                                                Set.

    1) Primary Data Type:- These are integer(int), character(char), floating point(float), double floating                                                                                                                                  point(double).

Data Types. Keyword. Size. Range. Format Specifier.
Integer signed int 2 -32768 to +32767 %d
  unsigned int 2 0 to 65535 %d
Long Integer long signed int 4 -2147483648 to 2147483647 %ld
  long unsigned int 4 0 to 4294967295 %lu
Short Integer short signed int 1 -128 to 127 %d
  short unsigned int 1 0 to 255 %u
Floating Point float 4 3.5e-38 to 3.4+38 %f
Double Floating Point double 8 1.7e-308 to 1.7+308 %lf
Long Double long doubles 10 3.4e-4932 to 1.1e+4932 %Lf
Character signed char 1 -128 to 127 %s
  unsigned char 1 0 to 255 %s

    We have seen primary data types char, int, float. While storing chars and int the highest bit is always used for storing sign of the number. If we know that the value stored in an integer and character variable is not negative(i.e the age of a person) there is no point of wasting highest bit for the sign. Thsi wastage can be avoided by using int or char as unsigned. By doing this the range of the variables is almost doubled.

     Conversion of Integer & Float values:-   It is important to understand the rules that govern the conversion of floating point                                                                     and integer values in C. These are mentioned below.

    1) Result of integer & integer operation yields integer result.

    2) Result of float & float operation yields float result.

    3) Result of integer & float operation yields float result.

    4) Result of float & integer operation yields float result.

    Ex.Assume 'i' to be an int and 'a' to be a float variable.

    i = 5/2 yields result 2  while a = 5/2 yields result 2.5 .

    2) User Defined Data Types:-

   typedef:- C supports a feature known as 'type definition' that allows user to define an identifier that would represent an existing data type. The user defined data type can later be used to declare variables. ex: typedef int units, typedef float marks, etc. where units symbolizes int and marks symbolizes float. They can be later used to declare as below

    Units batch1, batch2;

    Marks name1[50], name2[50];

    where batch1 and batch2 are dclared as integer variables and name1[50] and name2[50] are declared as 50 element floating point array variables. The main advantage of typedef is that we can create meaningful data type name for increasing the readibility of the program.

    enum:- Another user defined data type is enumerated data type which is defined as below.

              enum day{Monday, Tuesday, ......., Sunday};

              where day is a user defined enumerated data type which ca be used to declare variables that                 can have one of the value enclosed within the braces. After this definition we can declare                 variables to be of this type as below.

               enum day week_st, week_end;

                The enumerated variables week_st and week_end can only have one of the values entered in                   the braces above.

                week_st=Monday;

                week_end=Friday;

                if(week_st==Tuesday)

                week_end=Saturday;

                The compiler automatically assigns integer digits to all enumerations constants i.e. The enumeration constant Monday is assigned 0, Tuesday is assigned 1 and so on.

    Storage Class:- Variables are nothing but a fixed number of location reserved with a specific name.                               The storage class decides the portion of the program within which the variables are                               recognized.A C variable can have four storage classes.

   

Storage Class Loaction Default Initial Value Scope Life
automatic Memory Unpredictable garbage value Local to block Till control is within the block
static Memory Zero Local to block Presistes between different function calls
register CPU registers Garbage Value Local to block Till the control is within that block.

    Ex. auto int a;

          register int a;

          static int a;

          extern double a;

    Some Notes:-    

                        1) By default, automatic storage class is assumed for variables declared within a                               function & an external storage class for those declared outside.

                        2) Static storage class should be used only when a program requires the value of the                               variable to presist between different function calls.

                        3) The computer allows access to two types of locations i.e memory & CPU                               registers. The microprocessors have their internal storage locations which are used                               to temporarily hold the data. These storage locations are known as registers.                               Whatever data is to be processed is moved from memory to register by a                               microprocessor. Then data is processed and the result is returned to memory. In                               some languages like C it is possible to access these registers to store values in them                               or retrieve values from them. As there are only 14CPU registers of which maximum                               are utilized by microprocessor itself, we must use them very rarely. Since the                               computer accesses them faster than it accesses memory, they are best utilized as                               loop counters which have to be used a number of times. However if no registers                                are availabel, at such times auto storage class is assumed and execution is carried                                on. Floats cannot be stored in CPU registers.

                        4) The extern storage class should be used for only those variables which are being                               used by almost all the functions in the program. Declaring all the variables as extern                               is not advisable as they would remain active throughout the life of the program,                               wasting a lot of the memory unnecessarily. In case of conflict between a                               global(extern) and a local variable of the same name. It is always the local variable                               that is given the higher priority.

                        Ex. Static storage class:

                               main()                                                                         Output:

                               {  clrscr();                                                                        5               

                                    static int c=5;                                                              4

                                    clrscr();                                                                       3     

                                    printf("c=%d\n",c);                                                     2   

                                    c--;                                                                             1   

                                     if(c)

                                     main();

                                    getche();

                                  }

                                    It is understood from the above program that the values of a static variable initialized only once and thereafter the latest value of the variables persists between different function calls.

                                   Ex. Comparative study of auto & static storage class:

                                    main()                                                            main()

                                    {   clrscr();                                                      {clrscr();

                                        increament();                                                 increament();

                                        increament();                                                 increament();

                                        increament();                                                 increament();

                                     }                                                                    }

                                        increament()                                                     increament();

                                        {                                                                      {

                                          auto int i=1;                                                         static int i=1;

                                          printf("%d\n",i);                                                   printf("%d\n",i);  

                                          i=i+1;                                                                   i=i+1;

                                          getche();                                                              getche();

                                        }                                                                        }

                                        Output:-                                                              Output:-  

                                            1                                                                         1

                                            1                                                                         2   

                                            1                                                                         3

 

Operators and Expressions:-

   C supports a rich set of operators. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.

    C operators are mainly classified into following categories.

    1) Arithematic Operators.     2)  Relational Operators.    3) Logical operators.

    4) Assignment Operators.     5) Increament and Decreament Operators.    6) Conditional Operators.

    1) Arithematic Operators:-    Used to do arithematicl operations. There is no special operator                                                  available for exponentiation in 'C'.

                                               1) Addition[+].    2) Substraction[-].    3) Multiplication[*].

                                               4) Division[/].      5) Modulo Division[%]. 

    2) Relational Operators:- Used to denote relations.

                                           1) Less Than[<].        2) Less Than or Equal To[<=].

                                           3) Greater Than[>].    4) Greater Than or Equal To[>=].

                                           5) Equal To[=].            6) Not Equal To[!=].

    3) Logical Operators:- Used to give conditions.

                                            1) And[&&].    2) Or[||].    3) Not[!].

    4) Assignment Operators:- We have seen usual assignment operator '='. In addition, C has a set of                                                shorthand assignment operators.

                                            Ex.                                            

Simple Assignment Operators. Equivalent Shorthand Operators.
a = a + 1 a + = 1
a = a - 1 a - = 1
a = a * (n+1) a * = n+1
a = a / (n+1) a / = n+1
a = a%b a % =b

    5) Increament and Decreament Operators:-  There are ++ and -- operators. The operator ++ adds 1                                                                         to the operand while -- substracts 1. ++m is equivalent                                                                         to m=m+1 and vice versa.               

    6) Conditional Operators:- Conditional operators ? and : are sometimes called as ternary operators                                                since they take three arguments. Syntax is                                                expression1 ? expression2 : expression 3;

                                              If expression1 is true, then the value returned will be expression2,                                                 otherwise the value returned will be expression3.

                                              Ex. Consider following example

                                                     a=10, b=15;             x=(a>b) ? a : b;

                                                      This statement will store 10 in x if condition is true otherwise it                                                         will store 15 in x.

   Precedence of Operators and Associativity:- An arithematic expression without parantheses will be                                                                          evaluated from left to right using the rules of                                                                          precedence of operators.

                                                                       High Priority  *  /  %

                                                                       Low Priority  +  - 

                                                                       Ex.

Equation Operation.
x = 3 + 4 - 7 * 8 / 5 % 10 *
x = 3 + 4 - 56 / 5 % 10 /
x = 3 + 4 - 11 %10 %
x = 3 + 4 - 1 +
x = 7 - 1 +
x = 6 -

    In this examp;le operations are performed in above given order. Note that 56/5 yield 11 since 56 and 5 both are integers.

    Each operator in C has a precedence associated with it. This precedence is used to determine how an expression with more than one operator is evaluated. The operators at high level of precedencd are evaluated first. The operators of same precedence are evaluated either from left to right or from right to left depending on the level. This is known as the associativity property of an operator.

    Following table shows precedence of different operators and their associativity

Operator Description Associativity Rank(Precedence)
( ) function call Left to Right 1
[ ] array element Left to Right 1
+ unary plus Right to Left 2
- unary minus Right to Left 2
+ + increament Right to Left 2
- - decreament Right to Left 2
! negation Right to Left 2
* multiplication Left to Right 3
/ division Left to Right 3
% modulus Left to Right 3
+ addition Left to Right 4
- substraction Left to Right 4

Bar_line.gif (11170 bytes)

 

Prev || Home || Next