C Language(Synopsis)

Embed Size (px)

Citation preview

  • 7/28/2019 C Language(Synopsis)

    1/90

    C-LANGUAGE

    SYNOPSIS

    Unit-I

    Overview of C

    C is a programming language. It is most popular computer language today because it is a

    structured high level, machine independent language. Dennis Ritchie invented Clanguage. Ken Thompson created a language which was based upon a language known as

    BCPL and it was called as B. B language was created in 1970, basically for Unix

    operating system Dennis Ritchie used ALGOL, BCPL and B as the basic reference

    language from which he created C.

    C has many qualities which any programmer may desire. It contains the capability of

    assembly language with the features of high level language which can be used for

    creating software packages, system software etc. It supports the programmer with a richset of built-in functions and operators. C is highly portable. C programs written on one

    computer can run on other computer without making any changes in the program.

    Structured programming concept is well supported in C, this helps in dividing the

    programs into function modules or code blocks.

    History of C

    The milestones in C's development as a language are listed below:

    UNIX developed c. 1969 -- DEC PDP-7 Assembly Language

    BCPL -- a user friendly OS providing powerful development tools developed

    from BCPL. Assembler tedious long and error prone.

    A new language ``B'' a second attempt. c. 1970.

    A totally new language ``C'' a successor to ``B''. c. 1971

    By 1973 UNIX OS almost totally written in ``C''.

    Characteristics of C

    We briefly list some of C's characteristics that define the language and also have lead toits popularity as a programming language. Naturally we will be studying many of these

    aspects throughout the course.

    Small size

    Extensive use of function calls

    Loose typing -- unlike PASCAL

    Structured language

    Low level (BitWise) programming readily available

  • 7/28/2019 C Language(Synopsis)

    2/90

    Pointer implementation - extensive use of pointers for memory, array, structures

    and functions.

    C has now become a widely used professional language for various reasons.

    It has high-level constructs. It can handle low-level activities.

    It produces efficient programs.

    It can be compiled on a variety of computers.

    Its main drawback is that it has poor error detection which can make it off putting to the

    beginner. However diligence in this matter can pay off handsomely since having learnedthe rules of C we can break them. Not many languages allow this. This if done properly

    and carefully leads to the power of C programming

    C Program Structure

    A C program basically has the following form:

    Preprocessor Commands

    Type definitions

    Function prototypes -- declare function types and variables passed to function.

    Variables

    Functions

    We must have a main() function.

    Writing and Executing C Program

    A First Program

    Let's be polite and start by saluting the world! Type the following program into your

    favorite editor:

    #include < stdio.h>

    void main(){

    printf("\nHello World\n");}

    Save the code in the file hello.c, then compile it by typing:gcc hello.c

    This creates an executable file a.out, which is then executed simply by typing its name.

    The result is that the characters `` Hello World'' are printed out, preceded by an empty

    line. A C program containsfunctions and variables. The functions specify the tasks to beperformed by the program. The ``main'' function establishes the overall logic of the code.

    http://www.physics.drexel.edu/courses/Comp_Phys/General/UNIX/editors.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/UNIX/editors.htmlhttp://www.physics.drexel.edu/courses/Comp_Phys/General/C_basics/compile.html
  • 7/28/2019 C Language(Synopsis)

    3/90

    It is normally kept short and calls different functions to perform the necessary sub-tasks.

    All C codes must have a ``main'' function.

    Ourhello.c code calls printf, an output function from the I/O (input/output) library

    (defined in the file stdio.h). The original C language did not have any built-in I/O

    statements whatsoever. Nor did it have much arithmetic functionality. The originallanguage was really not intended for ''scientific'' or ''technical'' computation.. Thesefunctions are now performed by standard libraries, which are now part of ANSI C. The K

    & R textbook lists the content of these and other standard libraries in an appendix.

    The printf line prints the message ``Hello World'' on ``stdout'' (the output stream

    corresponding to the X-terminal window in which you run the code); ``\n'' prints a ``new

    line'' character, which brings the cursor onto the next line. By construction, printf never

    inserts this character on its own: the following program would produce the same result:

    #include < stdio.h>

    void main(){

    printf("\n");printf("Hello World");printf("\n");

    }

    Try leaving out the ``\n'' lines and see what happens.

    The first statement ``#include < stdio.h>'' includes a specification of the C I/O

    library. All variables in C must be explicitly defined before use: the ``.h'' files are by

    convention ``header files'' which contain definitions of variables and functions necessaryfor the functioning of a program, whether it be in a user-written section of code, or as part

    of the standard C libaries. The directive ``#include'' tells the C compiler to insert the

    contents of the specified file at that point in the code. The ``< ...>'' notation instructs the

    compiler to look for the file in certain ``standard'' system directories.

    The void preceeding ``main'' indicates that main is of ``void'' type--that is, it has no type

    associated with it, meaning that it cannot return a result on execution.

    The ``;'' denotes the end of a statement. Blocks of statements are put in braces {...}, as in

    the definition of functions. All C statements are defined in free format, i.e., with no

    specified layout or column assignment. Whitespace (tabs or spaces) is never significant,except inside quotes as part of a character string. The following program would produce

    exactly the same result as our earlier example:

    #include < stdio.h>void main(){printf("\nHello World\n");}

  • 7/28/2019 C Language(Synopsis)

    4/90

    Pre-processors in C

    The C Preprocessor is not part of the compiler, but is a separate step in the compilation

    process. In simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer tothe C Preprocessor as the CPP.

    All preprocessor lines begin with #

    The unconditional directives are:

    o #include - Inserts a particular header from another file

    o #define - Defines a preprocessor macro

    o #undef - Undefines a preprocessor macro

    The conditional directives are:

    o #ifdef - If this macro is defined

    o #ifndef - If this macro is not defined

    o #if - Test if a compile time condition is true

    o #else - The alternative for #if

    o #elif - #else an #if in one statement

    o #endif - End preprocessor conditional

    Other directives include:

    o # - Stringization, replaces a macro parameter with a string constant

    o ## - Token merge, creates a single token from two adjacent ones

    Pre-Processors Examples:

    Analyze following examples to understand various directives.

    #define MAX_ARRAY_LENGTH 20

    Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for

    constants to increase readability.

    #include

  • 7/28/2019 C Language(Synopsis)

    5/90

    #include "myheader.h"

    Tells the CPP to get stdio.h from System Libraries and add the text to this file. The nextline tells CPP to get myheader.h from the local directory and add the text to the file.

    #undef FILE_SIZE#define FILE_SIZE 42

    Tells the CPP to undefine FILE_SIZE and define it for 42.

    #ifndef MESSAGE#define MESSAGE "You wish!"#endif

    Tells the CPP to define MESSAGE only if MESSAGE isn't defined already.

    #ifdef DEBUG/* Your debugging statements here */

    #endif

    Tells the CPP to do the following statements if DEBUG is defined. This is useful if you

    pass the -DDEBUG flag to gcc. This will define DEBUG, so you can turn debugging on

    and off on the fly!

    Data Types and I/O operations

    C - Basic DatatypesC language programmer has to tell the system before-hand, the type of numbers or

    characters he is using in his program. These are data types. There are many data types in

    C language. A C programmer has to use appropriate data type as per his requirement.

    C language data types can be broadly classified as

    Primary data type

    Derived data typeUser-defined data type

    Primary data type

    All C Compilers accept the following fundamental data types

    1. Integer int

    2. Character char

  • 7/28/2019 C Language(Synopsis)

    6/90

    3. Floating Point float

    4. Double precision floating point double

    5. Void void

    The size and range of each data type is given in the table below

    DATA TYPE RANGE OF VALUES

    char -128 to 127

    Int -32768 to +32767

    float 3.4 e-38 to 3.4 e+38

    double 1.7 e-308 to 1.7 e+308

    Integer Type :

    Integers are whole numbers with a machine dependent range of values. A good

    programming language as to support the programmer by giving a control on a range of

    numbers and storage space. C has 3 classes of integer storage namely short int, int andlong int. All of these data types have signed and unsigned forms. A short int requires half

    the space than normal integer values. Unsigned numbers are always positive andconsume all the bits for the magnitude of the number. The long and unsigned integers areused to declare a longer range of values.

    Floating Point Types :

    Floating point number represents a real number with 6 digits precision. Floating point

    numbers are denoted by the keyword float. When the accuracy of the floating pointnumber is insufficient, we can use the double to define the number. The double is same as

    float but with longer precision. To extend the precision further we can use long double

    which consumes 80 bits ofmemory space.

    Void Type :

    Using void data type, we can specify the type of a function. It is a good practice to avoid

    functions that does not return any values to the calling function.

  • 7/28/2019 C Language(Synopsis)

    7/90

    Character Type :

    A single character can be defined as a defined as a character type of data. Characters are

    usually stored in 8 bits of internal storage. The qualifier signed or unsigned can beexplicitly applied to char. While unsigned characters have values between 0 and 255,

    signed characters have values from 128 to 127.

    Size and Range of Data Types on 16 bit machine.

    TYPE SIZE (Bits) Range

    Char or Signed Char 8 -128 to 127

    Unsigned Char 8 0 to 255

    Int or Signed int 16 -32768 to 32767

    Unsigned int 16 0 to 65535

    Short int or Signed short int 8 -128 to 127

    Unsigned short int 8 0 to 255

    Long int or signed long int 32 -2147483648 to 2147483647

    Unsigned long int 32 0 to 4294967295

    Float 32 3.4 e-38 to 3.4 e+38

    Double 64 1.7e-308 to 1.7e+308

    Long Double 80 3.4 e-4932 to 3.4 e+4932

    C has the following basic built-in datatypes.

    int

    float

    double

    char

    Please note that there is not a boolean data type. C does not have the traditional view

    about logical comparison, but thats another story.

  • 7/28/2019 C Language(Synopsis)

    8/90

    int - data type

    int is used to define integer numbers.

    {

    int Count;Count = 5;}

    float - data type

    float is used to define floating point numbers.

    {float Miles;Miles = 5.6;

    }

    double - data type

    double is used to define BIG floating point numbers. It reserves twice the storage for thenumber. On PCs this is likely to be 8 bytes.

    {double Atoms;Atoms = 2500000;

    }

    char - data type

    char defines characters.

    {char Letter;Letter = 'x';

    }

    Modifiers

    The data types explained above have the following modifiers.

    short

    long

    signed

    unsigned

  • 7/28/2019 C Language(Synopsis)

    9/90

    The modifiers define the amount of storage allocated to the variable. The amount of

    storage allocated is not cast in stone. ANSI has the following rules:

    short int +2,147,483,647 ( 2Gb)

    long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)signed char 1 -128 -> +127

    unsigned char 1 0 -> +255float 4double 8

    long double 12

    These figures only apply to todays generation of PCs. Mainframes and midrangemachines could use different figures, but would still comply with the rule above.

    You can find out how much storage is allocated to a data type by using the sizeof

    operator discussed in Operator TypesSession.

    Here is an example to check size of memory taken by various datatypes.

    intmain(){printf("sizeof(char) == %d\n", sizeof(char));printf("sizeof(short) == %d\n", sizeof(short));printf("sizeof(int) == %d\n", sizeof(int));printf("sizeof(long) == %d\n", sizeof(long));printf("sizeof(float) == %d\n", sizeof(float));printf("sizeof(double) == %d\n", sizeof(double));printf("sizeof(long double) == %d\n", sizeof(long double));

    printf("sizeof(long long) == %d\n", sizeof(long long));

    return 0;}

    Qualifiers

    http://www.tutorialspoint.com/ansi_c/c_operator_types.htmhttp://www.tutorialspoint.com/ansi_c/c_operator_types.htmhttp://www.tutorialspoint.com/ansi_c/c_operator_types.htm
  • 7/28/2019 C Language(Synopsis)

    10/90

    A type qualifier is used to refine the declaration of a variable, a function, and parameters,

    by specifying whether:

    The value of a variable can be changed.

    The value of a variable must always be read from memory rather than from a

    register

    Standard C language recognizes the following two qualifiers:

    const

    volatile

    The constqualifier is used to tell C that the variable value can not change afterinitialisation.

    const float pi=3.14159;

    Nowpi cannot be changed at a later time within the program.

    Another way to define constants is with the #define preprocessor which has the advantage

    that it does not use any storage

    The volatile qualifier declares a data type that can have its value changed in ways outsidethe control or detection of the compiler (such as a variable updated by the system clock or

    by another program). This prevents the compiler from optimizing code referring to the

    object by storing the object's value in a register and re-reading it from there, rather thanfrom memory, where it may have changed. You will use this qualifier once you will

    become expert in "C". So for now just proceed.

    Declaration of Variables

    Every variable used in the program should be declared to the compiler. The declarationdoes two things.

    1. Tells the compiler the variables name.

    2. Specifies what type of data the variable will hold.

    The general format of any declaration

    datatype v1, v2, v3, .. vn;Where v1, v2, v3 are variable names. Variables are separated by commas. A declaration

    statement must end with a semicolon.

    Example:

  • 7/28/2019 C Language(Synopsis)

    11/90

    Int sum;Int number, salary;Double average, mean;

    Datatype Keyword Equivalent

    Character char

    Unsigned Character unsigned char

    Signed Character signed char

    Signed Integer signed int (or) int

    Signed Short Integer signed short int (or) short int (or) short

    Signed Long Integer signed long int (or) long int (or) long

    UnSigned Integer unsigned int (or) unsigned

    UnSigned Short Integer unsigned short int (or) unsigned short

    UnSigned Long Integer unsigned long int (or) unsigned long

    Floating Point float

    Double Precision Floating Point double

    Extended Double Precision Floating Point long double

    User defined type declaration

    In C language a user can define an identifier that represents an existing data type. The

    user defined datatype identifier can later be used to declare variables. The general syntax

    is

    typedef type identifier;

    here type represents existing data type and identifier refers to the row name given to

    the data type.

    Example:

    typedef int salary;typedef float average;

    Here salary symbolizes int and average symbolizes float. They can be later used to

    declare variables as follows:

  • 7/28/2019 C Language(Synopsis)

    12/90

    Units dept1, dept2;Average section1, section2;

    Therefore dept1 and dept2 are indirectly declared as integer datatype and section1 andsection2 are indirectly float data type.

    The second type of user defined datatype is enumerated data type which is defined as

    follows.Enum identifier {value1, value2 . Value n};

    The identifier is a user defined enumerated datatype which can be used to declarevariables that have one of the values enclosed within the braces. After the definition we

    can declare variables to be of this new type as below.

    enum identifier V1, V2, V3, Vn

    The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2

    .. value n

    Example:enum day {Monday, Tuesday, . Sunday};enum day week_st, week end;week_st = Monday;week_end = Friday;if(wk_st == Tuesday)week_en = Saturday;

    Defining Symbolic Constants

    A symbolic constant value can be defined as a preprocessor statement and used in the

    program as any other constant value. The general form of a symbolic constant is

    # define symbolic_name value of constant

    Valid examples of constant definitions are :# define marks 100# define total 50# define pi 3.14159

    These values may appear anywhere in the program, but must come before it is referenced

    in the program.

    It is a standard practice to place them at the beginning of the program.

  • 7/28/2019 C Language(Synopsis)

    13/90

    Declaring Variable as Constant

    The values of some variable may be required to remain constant through-out the program.

    We can do this by using the qualifier const at the time of initialization.

    Example:

    Const int class_size = 40;

    The const data type qualifier tells the compiler that the value of the int variable class_size

    may not be modified in the program.

    Volatile Variable

    A volatile variable is the one whose values may be changed at any time by some externalsources.

    Example:

    volatile int num;

    The value of data may be altered by some external factor, even if it does not appear onthe left hand side of the assignment statement. When we declare a variable as volatile the

    compiler will examine the value of the variable each time it is encountered to see if an

    external factor has changed the value.

    C has a concept of 'data types' which are used to define a variable before its use. The

    definition of a variable will assign storage for the variable and define the type of data thatwill be held in the location.

    The value of a variable can be changed any time.

    C - Variable Types

    A variable is just a named area of storage that can hold a single value (numeric or

    character). The C language demands that you declare the name of each variable that you

    are going to use and its type, or class, before you actually try to do anything with it.

    The Programming language C has two main variable types

    Local Variables

    Global Variables

  • 7/28/2019 C Language(Synopsis)

    14/90

    Local Variables

    Local variables scope is confined within the block or function where it is defined.

    Local variables must always be defined at the top of a block.

    When a local variable is defined - it is not initalised by the system, you must

    initalise it yourself.

    When execution of the block starts the variable is available, and when the block

    ends the variable 'dies'.

    Check following example's output

    main(){

    int i=4;int j=10;

    i++;

    if (j > 0){

    /* i defined in 'main' can be seen */printf("i is %d\n",i);

    }

    if (j > 0){

    /* 'i' is defined and so local to this block */int i=100;printf("i is %d\n",i);

    }/* 'i' (value 100) dies here */

    printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/}

    This will generate following outputi is 5i is 100i is 5

    Here ++ is called incremental operator and it increase the value of any integer variable by1. Thus i++ is equivalent to i = i + 1;

    You will see -- operator also which is called decremental operator and it idecrease thevalue of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

    Global Variables

    Global variable is defined at the top of the program file and it can be visible and modifiedby any function that may reference it.

  • 7/28/2019 C Language(Synopsis)

    15/90

    Global variables are initalised automatically by the system when you define them!

    Data Type Initialser

    int 0

    char '\0'

    float 0pointer NULL

    If same variable name is being used for global and local variable then local variable takes

    preference in its scope. But it is not a good practice to use global variables and localvariables with the same name.

    int i=4; /* Global definition */

    main(){

    i++; /* Global variable */func();printf( "Value of i = %d -- main function\n", i );

    }

    func(){

    int i=10; /* Local definition */i++; /* Local variable */printf( "Value of i = %d -- func() function\n", i );

    }

    This will produce following resultValue of i = 11 -- func() function

    Value of i = 5 -- main function

    i in main function is global and will be incremented to 5. i in func is internal and will be

    incremented to 11. When control returns to main the internal variable will die and andany reference to i will be to the global.

    Declaration of Storage Class

    Variables in C have not only the data type but also storage class that provides information

    about their location and visibility. The storage class divides the portion of the program

    within which the variables are recognized.

    auto : It is a local variable known only to the function in which it is declared. Auto is the

    default storage class.

    static : Local variable which exists and retains its value even after the control is

    transferred to the calling function.

    extern : Global variable known to all functions in the file

  • 7/28/2019 C Language(Synopsis)

    16/90

    register : Social variables which are stored in the register.

    A storage class defines the scope (visibility) and life time of variables and/or functionswithin a C Program.

    There are following storage classes which can be used in a C Program

    auto

    register

    static

    extern

    auto - Storage Class

    auto is the default storage class for all local variables.

    {int Count;auto int Month;

    }

    The example above defines two variables with the same storage class. auto can only be

    used within functions, i.e. local variables.

    register - Storage Class

    register is used to define local variables that should be stored in a register instead ofRAM. This means that the variable has a maximum size equal to the register size (usually

    one word) and cant have the unary '&' operator applied to it (as it does not have a

    memory location).

    {register int Miles;

    }

    Register should only be used for variables that require quick access - such as counters. It

    should also be noted that defining 'register' goes not mean that the variable will be storedin a register. It means that it MIGHT be stored in a register - depending on hardware and

    implimentation restrictions.

    static - Storage Class

    static is the default storage class for global variables. The two variables below (count and

    road) both have a static storage class.

  • 7/28/2019 C Language(Synopsis)

    17/90

    static int Count;int Road;

    {printf("%d\n", Road);

    }

    static variables can be 'seen' within all functions in this source file. At link time, the static

    variables defined here will not be seen by the object modules that are brought in.

    static can also be defined within a function. If this is done the variable is initalised at run

    time but is not reinitalized when the function is called. This inside a function staticvariable retains its value during vairous calls.

    void func(void);

    static count=10; /* Global variable - static is the default */

    main(){while (count--){

    func();}

    }

    void func( void ){static i = 5;i++;printf("i is %d and count is %d\n", i, count);

    }

    This will produce following result

    i is 6 and count is 9i is 7 and count is 8i is 8 and count is 7i is 9 and count is 6i is 10 and count is 5i is 11 and count is 4i is 12 and count is 3i is 13 and count is 2i is 14 and count is 1

    i is 15 and count is 0

    NOTE : Here keyword voidmeans function does not return anything and it does not take

    any parameter. You can memoriese void as nothing. static variables are initialized to 0automatically.

    Definition vs Declaration : Before proceeding, let us understand the difference between

  • 7/28/2019 C Language(Synopsis)

    18/90

    defintion and declaration of a variable or function. Definition means where a variable or

    function is defined in realityand actual memory is allocated for variable or function.

    Declaration means just giving a reference of a variable and function. Through declarationwe assure to the complier that this variable or function has been defined somewhere else

    in the program and will be provided at the time of linking. In the above examples char*func(void) has been put at the top which is a declaration of this function where as this

    function has been defined below to main() function.

    There is one more very important use for 'static'. Consider this bit of code.

    char *func(void);

    main(){

    char *Text1;Text1 = func();

    }

    char *func(void){

    char Text2[10]="martin";return(Text2);

    }

    Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a

    storage class of 'auto' and will disappear when we exit the function and could be

    overwritten but something else. The answer is to specify

    static char Text[10]="martin";

    The storage assigned to 'text2' will remain reserved for the duration if the program.

    extern - Storage Class

    extern is used to give a reference of a global variable that is visible to ALL the programfiles. When you use 'extern' the variable cannot be initalized as all it does is point the

    variable name at a storage location that has been previously defined.

    When you have multiple files and you define a global variable or function which will be

    used in other files also, then extern will be used in another file to give reference ofdefined variable or function. Just for understanding extern is used to decalre a global

    variable or function in another files.

    File 1: main.c

    int count=5;

    main()

  • 7/28/2019 C Language(Synopsis)

    19/90

    {write_extern();

    }

    File 2: write.c

    void write_extern(void);

    extern int count;

    void write_extern(void){printf("count is %i\n", count);

    }

    Here extern keyword is being used to declare count in another file.

    Now compile these two files as follows

    gcc main.c write.c -o write

    This fill produce write program which can be executed to produce result.

    Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c

    will see the new value

    C - Using Constants

    A C constant is usually just the written version of a number. For example 1, 0, 5.73,

    12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treatedas long integers.

    Octal constants are written with a leading zero - 015.

    Hexadecimal constants are written with a leading 0x - 0x1ae.

    Long constants are written with a trailing L - 890L.

    Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'.

    Some characters can't be represented in this way, so we use a 2 character sequence asfollows.'\n' newline

    '\t' tab'\\' backslash'\'' single quote'\0' null ( Usedautomatically to terminate character string )

    In addition, a required bit pattern can be specified using its octal equivalent.

    '\044' produces bit pattern 00100100.

  • 7/28/2019 C Language(Synopsis)

    20/90

    Character constants are rarely used, since string constants are more convenient. A string

    constant is surrounded by double quotes eg "Brian and Dennis". The string is actually

    stored as an array of characters. The null character '\0' is automatically placed at the endof such a string to act as a string terminator.A character is a different type to a single

    character string. This is important poing to note.

    Instructions in C language are formed using syntax and keywords. It is necessary to

    strictly follow C language Syntax rules. Any instructions that mis-matches with Clanguage Syntax generates an error while compiling the program. All programs must

    confirm to rules pre-defined in C Language. Keywords as special words which are

    exclusively used by C language, each keyword has its own meaning and relevance hence,Keywords should not be used either as Variable or Constant names.

    Character Set

    The character set in C Language can be grouped into the following categories.

    1. Letters

    2. Digits3. Special Characters

    4. White Spaces

    White Spaces are ignored by the compileruntil they are a part of string constant. White

    Space may be used to separate words, but are strictly prohibited while using between

    characters of keywords or identifiers.

    C Character-Set Table

    Letters Digits

    Upper Case A to Z 0 to 9

    Lower Case a to z

    .

    Special Characters

  • 7/28/2019 C Language(Synopsis)

    21/90

    , .Comma & .Ampersand

    . .Period ^.Caret

    ; .Semicolon * .Asterisk

    : .Colon - .Minus Sign

    ? .Question Mark + .Plus Sign

    ' .Aphostrophe < .Opening Angle (Less than sign)

    " .Quotation Marks > .Closing Angle (Greater than sign)

    ! .Exclaimation Mark ( .Left Parenthesis

    | .Vertical Bar ) .Right Parenthesis

    / .Slash [ .Left Bracket

    \ .Backslash ] .Right Bracket

    ~ .Tilde { .Left Brace

    - .Underscore } .Right Bracket

    $ .Dollar Sign # .Number Sign

    %.Percentage Sign . .

  • 7/28/2019 C Language(Synopsis)

    22/90

    C - Input and Output

    Input : In any programming language input means to feed some data into program. This

    can be given in the form of file or from command line. C programming languageprovides a set of built-in functions to read given input and feed it to the program as per

    requirement.

    Output : In any programming language output means to display some data on screen,

    printer or in any file. C programming language provides a set of built-in functions tooutput required data.

    Here we will discuss only one input function and one putput function just to understand

    the meaning of input and output. Rest of the functions are given into C - Built-in

    Functions

    printf() function

    This is one of the most frequently used functions in C for output. ( we will discuss whatis function in subsequent chapter. ).

    Try following program to understand printf() function.

    #include

    main(){int dec = 5;char str[] = "abc";char ch = 's';

    float pi = 3.14;

    printf("%d %s %f %c\n", dec, str, pi, ch);}

    The output of the above would be:

    5 abc 3.140000 c

    Here %d is being used to print an integer, %s is being usedto print a string, %f is being

    used to print a float and %c is being used to print a character.

    A complete syntax of printf() function is given in C - Built-in Functions

    scanf() function

    This is the function which can be used to to read an input from the command line.

  • 7/28/2019 C Language(Synopsis)

    23/90

    Try following program to understand scanf() function.

    #include

    main(){int x;int args;

    printf("Enter an integer: ");if (( args = scanf("%d", &x)) == 0) {

    printf("Error: not an integer\n");} else {

    printf("Read in %d\n", x);}

    }

    Here %d is being used to read an integer value and we are passing &x to store the valeread input. Here &indicates the address of variavle x.

    This program will prompt you to enter a value. Whatever value you will enter at

    command prompt that will be output at the screen using printf() function. If you eneter a

    non-integer value then it will display an error message.

    Enter an integer: 20Read in 20

    One of the essential operations performed in a C language programs is to provide input

    values to the program and output the data produced by the program to a standard outputdevice. We can assign values to variable through assignment statements such as x = 5

    a = 0 ; and so on. Another method is to use the Input then scanf which can be used

    to read data from a key board. For outputting results we have used extensively the

    function printf which sends results out to a terminal. There exists several functions in

    C language that can carry out input output operations. These functions are collectively

    known as standard Input/Output Library. Each program that uses standard input / out put

    function must contain the statement.

    # include < stdio.h >

    at the beginning.

    Single character input output:

    The basic operation done in input output is to read a characters from the standard input

    device such as the keyboard and to output or writing it to the output unit usually thescreen. The getchar function can be used to read a character from the standard input

    device. The scanf can also be used to achieve the function. The getchar has the following

    http://www.tutorialspoint.com/ansi_c/c_function_references.htmhttp://www.tutorialspoint.com/ansi_c/c_function_references.htmhttp://www.tutorialspoint.com/ansi_c/c_function_references.htmhttp://www.tutorialspoint.com/ansi_c/c_function_references.htm
  • 7/28/2019 C Language(Synopsis)

    24/90

    form.Variable name = getchar:

    Variable name is a valid C variable, that has been declared already and that possess the

    type char.

    Example program :

    # include < stdio.h > // assigns stdio-h header file to your program

    void main ( ) // Indicates the starting point of the program.{char C, // variable declarationprintf (Type one character:) ; // message to userC = getchar () ; // get a character from key board andStores it in variable C.Printf ( The character you typed is = %c, C) ; // output} // Statement which displays value of C on

    // Standard screen.

    The putchar function which in analogus to getchar function can be used for writing

    characters one at a time to the output terminal. The general form isputchar (variable name);

    Where variable is a valid C type variable that has already been declared Ex:-Putchar ( );

    Displays the value stored in variable C to the standard screen.Program shows the use of getchar function in an interactive environment.

    #include < stdio.h > // Inserts stdio.h header file into the Pgmvoid main ( ) // Beginning of main function.{char in; // character declaration of variable in.printf ( please enter one character); // message to userin = getchar ( ) ; // assign the keyboard input value to in.putchar (in); // out put in value to standard screen.}

    String input and output:

    The gets function relieves the string from standard input device while put S outputs the

    string to the standard output device. A strong is an array or set of characters.

    The function gets accepts the name of the string as a parameter, and fills the string with

    characters that are input from the keyboard till newline character is encountered. (That istill we press the enter key). All the end function gets appends a null terminator as must be

    done to any string and returns.

    The puts function displays the contents stored in its parameter on the standard screen.The standard form of the gets function is

  • 7/28/2019 C Language(Synopsis)

    25/90

    gets (str)

    Here str is a string variable.

    The standard form for the puts character is

    puts (str)

    Where str is a string variable.

    Eample program (Involving both gets and puts)

    # include < stdio.h >Void main ( ){char s [80];printf (Type a string less than 80 characters:);gets (s);printf (The string types is:);puts(s);}

    Formatted Input For Scanf:

    The formatted input refers to input data that has been arranged in a particular format.Input values are generally taken by using the scanf function. The scanf function has the

    general form.Scanf (control string, arg1, arg2, arg3 .argn);

    The format field is specified by the control string and the arguments

    arg1, arg2, .argn specifies the addrss of location where address is to be

    stored.The control string specifies the field format which includes format specifications and

    optional number specifying field width and the conversion character % and also blanks,

    tabs and newlines.The Blanks tabs and newlines are ignored by compiler. The conversion character % is

    followed by the type of data that is to be assigned to variable of the assignment. The field

    width specifier is optional.

    The general format for reading a integer number is

    % x d

    Here percent sign (%) denotes that a specifier for conversion follows and x is an integer

    number which specifies the width of the field of the number that is being read. The data

  • 7/28/2019 C Language(Synopsis)

    26/90

    type character d indicates that the number should be read in integer mode.

    Example :

    scanf (%3d %4d, &sum1, &sum2);

    If the values input are 175 and 1342 here value 175 is assigned to sum1 and 1342 to sum

    2. Suppose the input data was follows 1342 and 175.

    The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d the

    number 1342 will be cut to 134 and the remaining part is assigned to second variable

    sum2. If floating point numbers are assigned then the decimal or fractional part is skipped

    by the computer.To read the long integer data type we can use conversion specifier % ld & % hd for short

    integer.

    Input specifications for real number:Field specifications are not to be use while representing a real number therefore real

    numbers are specified in a straight forward manner using % f specifier.

    The general format of specifying a real number input is

    Scanf (% f , &variable);

    Example:

    Scanf (%f %f % f, &a, &b, &c);

    With the input data

    321.76, 4.321, 678 The values

    321.76 is assigned to a , 4.321 to b & 678 to C.If the number input is a double data type then the format specifier should be % lf instead

    of %f.

    Input specifications for a character.

    Single character or strings can be input by using the character specifiers.

    The general format is

    % xc or %xs

    Where C and S represents character and string respectively and x represents the field

    width.

    The address operator need not be specified while we input strings.

    Example :

  • 7/28/2019 C Language(Synopsis)

    27/90

    Scanf (%C %15C, &ch, nname):

    Here suppose the input given is a, Robert then a is assigned to ch and name will be

    assigned to Robert.

    Printing One Line:

    printf();The most simple output statement can be produced in C Language by using printfstatement. It allows you to display information required to the user and also prints thevariables we can also format the output and provide text labels. The simple statement

    such as

    Printf (Enter 2 numbers);

    Prompts the message enclosed in the quotation to be displayed.A simple program to illustrate the use of printf statement:-

    #include < stdio.h >

    main ( ){printf (Hello!);printf (Welcome to the world of Engineering!);}

    Output:Hello! Welcome to the world of Engineering.

    Both the messages appear in the output as if a single statement. If you wish to print thesecond message to the beginning of next line, a new line character must be placed inside

    the quotation marks.

    For Example :

    printf (Hello!\n);

    OR

    printf (\n Welcome to the world of Engineering);

    Conversion Strings and Specifiers:

    The printf ( ) function is quite flexible. It allows a variable number of arguments, labelsand sophisticated formatting of output. The general form of the printf ( ) function is

    Syntax

    Printf (conversion string, variable list);

  • 7/28/2019 C Language(Synopsis)

    28/90

    The conversion string includes all the text labels, escape character and conversion

    specifiers required for the desired output. The variable includes all the variable to be

    printed in order they are to be printed. There must be a conversion specifies after eachvariable.

    Specifier Meaning

    %c Print a character

    %d Print a Integer%i Print a Integer

    %e Print float value in exponential form.

    %f Print float value%g Print using %e or %f whichever is smaller

    %o Print actual value

    %s Print a string

    %x Print a hexadecimal integer (Unsigned) using lower case a F

    %X Print a hexadecimal integer (Unsigned) using upper case A F%a Print a unsigned integer.

    %p Print apointervalue%hx hex short

    %lo octal long

    %ld long

    Unit-2

  • 7/28/2019 C Language(Synopsis)

    29/90

    What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9.

    Here 4 and 5 are called operands and + is called operator. C language supports following

    type of operators.

    Arithmetic Operators

    Logical (or Relational) Operators

    Bitwise Operators

    Assignment Operators

    Misc Operators

    Lets have a look on all operators one by one.

    Arithmetic Operators:

    There are following arithmetic operators supported by C language:

    Assume variable A holds 10 and variable holds 20 then:

    Show Examples

    Operator Description Example

    + Adds two operands A + B will give 30

    - Subtracts second operand from thefirst

    A - B will give -10

    * Multiply both operands A * B will give 200

    / Divide numerator by denumerator B / A will give 2

    %Modulus Operator and remainder ofafter an integer division

    B % A will give 0

    ++Increment operator, increases integervalue by one

    A++ will give 11

    --Decrement operator, decreases

    integer value by oneA-- will give 9

    Logical (or Relational) Operators:

    There are following logical operators supported by C language

    Assume variable A holds 10 and variable holds 20 then:

  • 7/28/2019 C Language(Synopsis)

    30/90

    Arithmetic Expressions

    An expression is a combination ofvariables constants and operators written according to

    the syntax of C language. In C every expression evaluates to a value i.e., everyexpression results in some value of a certain type that can be assigned to a variable. Some

    examples of C expressions are shown in the table given below.

    Algebraic

    Expr

    essio

    n

    C Expression

    a x b c a * b c

    (m + n) (x + y) (m + n) * (x + y)

    (ab / c) a * b / c

    3x2 +2x + 1 3*x*x+2*x+1

    (x / y) + c x / y + c

    Evaluation of Expressions

    Expressions are evaluated using an assignment statement of the form

    Variable = expression;

    Variable is any valid C variable name. When the statement is encountered, the expression

    is evaluated first and then replaces the previous value of the variable on the left hand

    side. All variables used in the expression must be assigned values before evaluation isattempted.

    Example of evaluation statements are

    x = a * b cy = b / c * a

    z = a b / c + d;

    The following program illustrates the effect of presence of parenthesis in expressions.

    .main (){float a, b, c x, y, z;

  • 7/28/2019 C Language(Synopsis)

    31/90

    a = 9;b = 12;c = 3;x = a b / 3 + c * 2 1;y = a b / (3 + c) * (2 1);z = a ( b / (3 + c) * 2) 1;

    printf (x = %fn,x);printf (y = %fn,y);printf (z = %fn,z);}

    .

    output

    x = 10.00y = 7.00z = 4.00

    Precedence in Arithmetic Operators

    An arithmetic expression without parenthesis will be evaluated from left to right usingthe rules of precedence of operators. There are two distinct priority levels of arithmetic

    operators in C.

    High priority * / %Low priority + -

    Rules for evaluation of expression First parenthesized sub expression left to right are evaluated.

    .

    If parenthesis are nested, the evaluation begins with the innermost sub expression.

    The precedence rule is applied in determining the order of application of operatorsin evaluating sub expressions.

    The associability rule is applied when two or more operators of the same

    precedence level appear in the sub expression.

    Arithmetic expressions are evaluated from left to right using the rules ofprecedence.

    . When Parenthesis are used, the expressions within parenthesis assume highest

    priority.

    http://www.tutorialspoint.com/ansi_c/arithmatic_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/arithmatic_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/logical_operators_examples.htm
  • 7/28/2019 C Language(Synopsis)

    32/90

    Type conversions in expressions

    Implicit type conversion

    C permits mixing of constants and variables of different types in an expression. C

    automatically converts any intermediate values to the proper type so that the expressioncan be evaluated without loosing any significance. This automatic type conversion is

    know as implicit type conversion

    During evaluation it adheres to very strict rules and type conversion. If the operands areof different types the lower type is automatically converted to the higher type before the

    operation proceeds. The result is of higher type.

    The following rules apply during evaluating expressions

    All short and char are automatically converted to int then

    1. If one operand is long double, the other will be converted to long double and result.....will be long double.2. If one operand is double, the other will be converted to double and result will be

    double.

    3. If one operand is float, the other will be converted to float and result will be float.4. If one of the operand is unsigned long int, the other will be converted into unsigned

    .....long int and result will be unsigned long int.

    5. If one operand is long int and other is unsigned int then.....a. If unsigned int can be converted to long int, then unsigned int operand will be

    ..........converted as such and the result will be long int.

    .....b. Else Both operands will be converted to unsigned long int and the result will be

    ..........unsigned long int.6. If one of the operand is long int, the other will be converted to long int and the result

    will be long int. .

    7. If one operand is unsigned int the other will be converted to unsigned int and the.....result will be unsigned int.

    Explicit Conversion

    Many times there may arise a situation where we want to force a type conversion in a

    way that is different from automatic conversion.

    Consider for example the calculation of number of female and male students in a class

    ........................female_studentsRatio =........-------------------

    ........................male_students

    Since if female_students and male_students are declared as integers, the decimal part will

  • 7/28/2019 C Language(Synopsis)

    33/90

    be rounded off and its ratio will represent a wrong figure. This problem can be solved by

    converting locally one of the variables to the floating point as shown below.

    Ratio = (float) female_students / male_students

    The operator float converts the female_students to floating point for the purpose ofevaluation of the expression. Then using the rule of automatic conversion, the division is

    performed by floating point mode, thus retaining the fractional part of the result. Theprocess of such a local conversion is known as explicit conversion or casting a value. The

    general form is

    (type_name) expression

    Operator precedence and associativity

    Each operator in C has a precedence associated with it. The precedence is used to

    determine how an expression involving more than one operator is evaluated. There aredistinct levels of precedence and an operator may belong to one of these levels. The

    operators of higher precedence are evaluated first.

    The operators of same precedence are evaluated from right to left or from left to right

    depending on the level. This is known as associativity property of an operator.

    C - Flow Control Statements

    C provides two sytles of flow control:

    Branching Looping

    C Programming - Decision Making - Branching

    Branching

    The C language programs presented until now follows a sequential form of execution of

    statements. Many times it is required to alter the flow of the sequence of instructions. C

    language provides statements that can alter the flow of a sequence of instructions. Thesestatements are called control statements. These statements help to jump from one part of

    the program to another. The control transfer may be conditional or unconditional.

    if Statement:

    The simplest form of the control statement is the If statement. It is very frequently used indecision making and allowing the flow of program execution.

    The If structure has the following syntax

    http://www.tutorialspoint.com/ansi_c/assignment_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/bitwise_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/assignment_operators_examples.htm
  • 7/28/2019 C Language(Synopsis)

    34/90

    if (condition)statement;

    The statement is any valid C language statement and the condition is any valid Clanguage expression, frequently logical operators are used in the condition statement. The

    condition part should not end with a semicolon, since the condition and statement shouldbe put together as a single statement. The command says if the condition is true thenperform the following statement or If the condition is fake the computer skips the

    statement and moves on to the next instruction in the program.

    Example program

    Sample Code1. # include //Include the stdio.h file2. void main () // start of the program3. {

    4. int numbers // declare the variables

    5. printf ("Type a number:") // message to the user

    6. scanf ("%d", &number) // read the number fromstandard input

    7. if (number < 0) // check whether the number is anegative number

    8. number = -number // if it is negative thenconvert it into positive

    9. printf ("The absolute value is %d \n", number)// print the value

    10. }

    The above program checks the value of the input number to see if it is less than zero. If itis then the following program statement which negates the value of the number is

    executed. If the value of the number is not less than zero, we do not want to negate it then

    this statement is automatically skipped. The absolute number is then displayed by theprogram, and program execution ends.

    The If else construct:

    The syntax of the If else construct is as follows:-

    The if else is actually just on extension of the general format of if statement. If the result

    of the condition is true, then program statement 1 is executed, otherwise programstatement 2 will be executed. If any case either program statement 1 is executed or

    http://www.tutorialspoint.com/ansi_c/misc_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/misc_operators_examples.htmhttp://www.tutorialspoint.com/ansi_c/misc_operators_examples.htm
  • 7/28/2019 C Language(Synopsis)

    35/90

    program statement 2 is executed but not both when writing programs this else statement

    is so frequently required that almost all programming languages provide a special

    construct to handle this situation.

    Sample Code

    1. #include //include the stdio.h header filein your program2. void main () // start of the main3. {4. int num // declare variable num as integer

    5. printf ("Enter the number") // message to theuser

    6. scanf ("%d", &num) // read the input number fromkeyboard

    7. if (num < 0) // check whether number is lessthan zero

    8. printf ("The number is negative") // if it isless than zero then it is negative

    9. else // else statement10. printf ("The number is positive") // if

    it is more than zero then the given number is positive

    11. }

    In the above program the If statement checks whether the given number is less than 0. Ifit is less than zero then it is negative therefore the condition becomes true then the

    statement The number is negative is executed. If the number is not less than zero the If

    else construct skips the first statement and prints the second statement declaring that thenumber is positive.

    Compound Relational tests:

    C language provides the mechanisms necessary to perform compound relational tests. A

    compound relational test is simple one or more simple relational tests joined together by

    either the logical AND or the logical OR operators. These operators are represented bythe character pairs && // respectively. The compound operators can be used to form

    complex expressions in C.

    Syntax

    a> if (condition1 && condition2 && condition3)b> if (condition1 // condition2 // condition3)

  • 7/28/2019 C Language(Synopsis)

    36/90

    The syntax in the statement a represents a complex if statement which combines

    different conditions using the and operator in this case if all the conditions are true only

    then the whole statement is considered to be true. Even if one condition is false the wholeif statement is considered to be false.

    The statement b uses the logical operator or (//) to group different expression to bechecked. In this case if any one of the expression if found to be true the whole expression

    considered to be true, we can also uses the mixed expressions using logical operators and

    and or together.

    Nested if Statement

    The if statement may itself contain another if statement is known as nested if statement.

    Syntax:

    if (condition1)if (condition2)

    statement-1;else

    statement-2;else

    statement-3;

    The if statement may be nested as deeply as you need to nest it. One block of code will

    only be executed if two conditions are true. Condition 1 is tested first and then condition2 is tested. The second if condition is nested in the first. The second if condition is tested

    only when the first condition is true else the program flow will skip to the corresponding

    else statement.

    Sample Code1. #include //includes the stdio.h file to your

    program2. main () //start of main function3. {4. int a,b,c,big //declaration of variables

    5. printf ("Enter three numbers") //message to theuser

    6. scanf ("%d %d %d", &a, &b, &c) //Read variablesa,b,c,

    7. if (a > b) // check whether a is greater than bif true then

    8. if (a > c) // check whether a is greater than c

  • 7/28/2019 C Language(Synopsis)

    37/90

    9. big = a // assign a to big

    10. else big = c // assign c to big

    11. else if (b > c) // if the condition (a > b)

    fails check whether b is greater than c12. big = b // assign b to big

    13. else big = c // assign c to big

    14. printf ("Largest of %d, %d & %d = %d",a,b,c,big) //print the given numbers along with thelargest number

    15. }

    In the above program the statement if (a>c) is nested within the if (a>b). If the first Ifcondition if (a>b)

    If (a>b) is true only then the second if statement if (a>b) is executed. If the first if

    condition is executed to be false then the program control shifts to the statement aftercorresponding else statement.

    Sample Code1. #include //Includes stdio.h file to your

    program2. void main () // start of the program3. {4. int year, rem_4, rem_100, rem_400 // variable

    declaration

    5.6. printf ("Enter the year to be tested") // message

    for user

    7. scanf ("%d", &year) // Read the year from standardinput.

    8.9. rem_4 = year % 4 //find the remainder of year by 4

    10. rem_100 = year % 100 //find the remainder ofyear by 100

    11. rem_400 = year % 400 //find the remainder ofyear by 400

    12.

  • 7/28/2019 C Language(Synopsis)

    38/90

    13. if ((rem_4 == 0 && rem_100 != 0) rem_400 == 0)

    14. //apply if condition 5 check whetherremainder is zero

    15. printf ("It is a leap year. \n") // printtrue condition

    16. else17. printf ("No. It is not a leap year.

    \n") //print the false condition

    18. }

    The above program checks whether the given year is a leap year or not. The year given is

    divided by 4,100 and 400 respectively and its remainder is collected in the variables

    rem_4, rem_100 and rem_400. A if condition statements checks whether the remaindersare zero. If remainder is zero then the year is a leap year. Here either the year y 400 is

    to be zero or both the year 4 and year by 100 has to be zero, then the year is a leap

    year.

    C Programming - Decision Making - Looping

    During looping a set of statements are executed until some conditions for termination of

    the loop is encountered. A program loop therefore consists of two segments one known

    as body of the loop and other is the control statement. The control statement tests certainconditions and then directs the repeated execution of the statements contained in the body

    of the loop.In looping process in general would include the following four steps

    1. Setting and initialization of a counter2. Exertion of the statements in the loop

    3. Test for a specified conditions for the execution of the loop

    4. Incrementing the counterThe test may be either to determine whether the loop has repeated the specified number

    of times or to determine whether the particular condition has been met.

    The While Statement:

    The simplest of all looping structure in C is the while statement. The general format ofthe while statement is:

    while (test condition){body of the loop}

  • 7/28/2019 C Language(Synopsis)

    39/90

    Here the given test condition is evaluated and if the condition is true then the body of the

    loop is executed. After the execution of the body, the test condition is once again

    evaluated and if it is true, the body is executed once again. This process of repeatedexecution of the body continues until the test condition finally becomes false and the

    control is transferred out of the loop. On exit, the program continues with the statements

    immediately after the body of the loop. The body of the loop may have one or morestatements. The braces are needed only if the body contained two are more statements

    Example program for generating N Natural numbers using while loop:

    # include < stdio.h > //include the stdio.h filevoid main() // Start of your program{int n, i=0; //Declare and initialize the variablesprintf(Enter the upper limit number); //Message to theuserscanf(%d, &n); //read and store the numberwhile(I < = n) // While statement with condition{ // Body of the loopprintf(\t%d,I); // print the value of iI++; increment I to the next natural number.}}

    In the above program the looping concept is used to generate n natural numbers. Here n

    and I are declared as integer variables and I is initialized to value zero. A message is

    given to the user to enter the natural number till where he wants to generate the numbers.The entered number is read and stored by the scanf statement. The while loop then checks

    whether the value of I is less than n i.e., the user entered number if it is true then the

    control enters the loop body and prints the value of I using the printf statement andincrements the value of I to the next natural number this process repeats till the value of I

    becomes equal to or greater than the number given by the user.

    The Do while statement:

    The do while loop is also a kind of loop, which is similar to the while loop in contrast towhile loop, the do while loop tests at the bottom of the loop after executing the body of

    the loop. Since the body of the loop is executed first and then the loop condition is

    checked we can be assured that the body of the loop is executed at least once.

    The syntax of the do while loop is:

    Do{statement;

  • 7/28/2019 C Language(Synopsis)

    40/90

    }while(expression);

    Here the statement is executed, then expression is evaluated. If the condition expressionis true then the body is executed again and this process continues till the conditional

    expression becomes false. When the expression becomes false. When the expressionbecomes false the loop terminates.

    To realize the usefulness of the do while construct consider the following problem. Theuser must be prompted to press Y or N. In reality the user can press any key other than y

    or n. IN such case the message must be shown again and the user should be allowed to

    enter one of the two keys, clearly this is a loop construct. Also it has to be executed at

    least once. The following program illustrates the solution.

    /* Program to illustrate the do while loop*/#include < stdio.h > //include stdio.h file to your program

    void main() // start of your program{char inchar; // declaration of the characterdo // start of the do loop{printf(Input Y or N); //message for the userscanf(%c, &inchar); // read and store the character}while(inchar!=y && inchar != n); //while loop endsif(inchar==y) // checks whther entered character is yprintf(you pressed u\n); // message for the userelseprintf(You pressed n\n);} //end of for loop

    The Break Statement:

    Sometimes while executing a loop it becomes desirable to skip a part of the loop or quit

    the loop as soon as certain condition occurs, for example consider searching a particularnumber in a set of 100 numbers as soon as the search number is found it is desirable to

    terminate the loop. C language permits a jump from one statement to another within a

    loop as well as to jump out of the loop. The break statement allows us to accomplish thistask. A break statement provides an early exit from for, while, do and switch constructs.

    A break causes the innermost enclosing loop or switch to be exited immediately.

    Example program to illustrate the use of break statement.

    /* A program to find the average of the marks*/#include < stdio.h > //include the stdio.h file to yourprogramvoid main() // Start of the program

  • 7/28/2019 C Language(Synopsis)

    41/90

    {int I, num=0; //declare the variables and initializefloat sum=0,average; //declare the variables and initializeprintf(Input the marks, -1 to end\n); // Message to theuser

    while(1) // While loop starts{scanf(%d,&I); // read and store the input numberif(I==-1) // check whether input number is -1break; //if number 1 is input skip the loopsum+=I; //else add the value of I to sumnum++ // increment num value by 1}} end of the program

    Continue statement:

    During loop operations it may be necessary to skip a part of the body of the loop undercertain conditions. Like the break statement C supports similar statement called continuestatement. The continue statement causes the loop to be continued with the next iteration

    after skipping any statement in between. The continue with the next iteration the format

    of the continue statement is simply:

    Continue;

    Consider the following program that finds the sum of five positive integers. If a negative

    number is entered, the sum is not performed since the remaining part of the loop isskipped using continue statement.

    #include < stdio.h > //Include stdio.h filevoid main() //start of the program{int I=1, num, sum=0; // declare and initialize thevariablesfor (I = 0; I < 5; I++) // for loop{printf(Enter the integer); //Message to the userscanf(%I, &num); //read and store the numberif(num < 0) //check whether the number is less than zero{

    printf(You have entered a negative number); // message tothe usercontinue; // starts with the beginning of the loop} // end of for loopsum+=num; // add and store sum to num}printf(The sum of positive numbers entered = %d,sum); //

  • 7/28/2019 C Language(Synopsis)

    42/90

    print thte sum.} // end of the program.

    For Loop:

    The for loop provides a more concise loop control structure. The general form of the forloop is:

    for (initialization; test condition; increment){body of the loop}

    When the control enters for loop the variables used in for loop is initialized with the

    starting value such as I=0,count=0. The value which was initialized is then checked with

    the given test condition. The test condition is a relational expression, such as I < 5 that

    checks whether the given condition is satisfied or not if the given condition is satisfiedthe control enters the body of the loop or else it will exit the loop. The body of the loop is

    entered only if the test condition is satisfied and after the completion of the execution ofthe loop the control is transferred back to the increment part of the loop. The control

    variable is incremented using an assignment statement such as I=I+1 or simply I++ and

    the new value of the control variable is again tested to check whether it satisfies the loopcondition. If the value of the control variable satisfies then the body of the loop is again

    executed. The process goes on till the control variable fails to satisfy the condition.

    Additional features of the for loop:

    We can include multiple expressions in any of the fields of for loop provided that weseparate such expressions by commas. For example in the for statement that begins

    For( I = 0; j = 0; I < 10, j=j-10)

    Sets up two index variables I and j the former initialized to zero and the latter to 100

    before the loop begins. Each time after the body of the loop is executed, the value of Iwill be incremented by 1 while the value of j is decremented by 10.

    Just as the need may arise to include more than one expression in a particular field of the

    for statement, so too may the need arise to omit on or more fields from the for statement.

    This can be done simply by omitting the desired filed, but by marking its place with asemicolon. The init_expression field can simply be left blank in such a case as long as

    the semicolon is still included:

    For(;j!=100;++j)

    The above statement might be used if j were already set to some initial value before the

    loop was entered. A for loop that has its looping condition field omitted effectively sets

  • 7/28/2019 C Language(Synopsis)

    43/90

    up an infinite loop, that is a loop that theoretically will be executed for ever.

    For loop example program:

    /* The following is an example that finds the sum of the

    first fifteen positive natural numbers*/#include < stdio.h > //Include stdio.h filevoid main() //start main program{int I; //declare variableint sum=0,sum_of_squares=0; //declare and initializevariable.for(I=0;I < = 30; I+=2) //for loop{sum+=I; //add the value of I and store it to sumsum_of_squares+=I*I; //find the square value and add it tosum_of_squares} //end of for loopprintf(Sum of first 15 positive even numbers=%d\n,sum); //Print sumprintf(Sum of their squares=%d\n,sum_of_squares); //printsum_of_square}

    Unit-3

    C Programming - Arrays

    The C language provides a capability that enables the user to define a set of ordered dataitems known as an array.

    Suppose we had a set of grades that we wished to read into the computer and suppose we

    wished to perform some operations on these grades, we will quickly realize that we

    cannot perform such an operation until each and every grade has been entered since itwould be quite a tedious task to declare each and every student grade as a variable

    especially since there may be a very large number.

    In C we can define variable called grades, which represents not a single value of grade

    but a entire set of grades. Each element of the set can then be referenced by means of anumber called as index number or subscript.

    Declaration of arrays:

    Like any other variable arrays must be declared before they are used. The general form of

    declaration is:

  • 7/28/2019 C Language(Synopsis)

    44/90

    type variable-name[50];

    The type specifies the type of the elements that will be contained in the array, such as intfloat or char and the size indicates the maximum number of elements that can be stored

    inside the array for ex:

    float height[50];

    Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are

    valid. In C the array elements index or subscript begins with number zero. So height [0]

    refers to the first element of the array. (For this reason, it is easier to think of it asreferring to element number zero, rather than as referring to the first element).

    As individual array element can be used anywhere that a normal variable with a statement

    such as

    G = grade [50];

    The statement assigns the value stored in the 50th index of the array to the variable g.

    More generally if I is declared to be an integer variable, then the statement g=grades [I];

    Will take the value contained in the element number I of the grades array to assign it to g.so if I were equal to 7 when the above statement is executed, then the value of grades [7]

    would get assigned to g.

    A value stored into an element in the array simply by specifying the array element on theleft hand side of the equals sign. In the statement

    grades [100]=95;

    The value 95 is stored into the element number 100 of the grades array.The ability to represent a collection of related data items by a single array enables us to

    develop concise and efficient programs. For example we can very easily sequence

    through the elements in the array by varying the value of the variable that is used as a

    subscript into the array. So the for loop

    for(i=0;i < 100;++i);sum = sum + grades [i];

    Will sequence through the first 100 elements of the array grades (elements 0 to 99) and

    will add the values of each grade into sum. When the for loop is finished, the variablesum will then contain the total of first 100 values of the grades array (Assuming sum

    were set to zero before the loop was entered)

    In addition to integer constants, integer valued expressions can also be inside the brackets

    to reference a particular element of the array. So if low and high were defined as integervariables, then the statement

  • 7/28/2019 C Language(Synopsis)

    45/90

    next_value=sorted_data[(low+high)/2]; would assign to the variable

    next_value indexed by evaluating the expression (low+high)/2. If low is equal to

    1 and high were equal to 9, then the value ofsorted_data[5] would be assigned to

    the next_value and if low were equal to 1 and high were equal to 10 then the value

    ofsorted_data[5] would also be referenced.

    Just as variables arrays must also be declared before they are used. The declaration of anarray involves the type of the element that will be contained in the array such as int, float,

    char as well as maximum number of elements that will be stored inside the array. The C

    system needs this latter information in order to determine how much memory space toreserve for the particular array.

    The declaration int values[10]; would reserve enough space for an array called values that

    could hold up to 10 integers. Refer to the below given picture to conceptualize the

    reserved storage space.

    values[0]

    values[1]

    values[2]

    values[3]

    values[4]

    values[5]

    values[6]

    values[7]

    values[8]

    values[9]

    The array values stored in the memory.

    Initialization of arrays:

    We can initialize the elements in the array in the same way as the ordinary variableswhen they are declared. The general form of initialization off arrays is:

    type array_name[size]={list of values};

  • 7/28/2019 C Language(Synopsis)

    46/90

    The values in the list care separated by commas, for example the statement

    int number[3]={0,0,0};

    Will declare the array size as a array of size 3 and will assign zero to each element if the

    number of values in the list is less than the number of elements, then only that manyelements are initialized. The remaining elements will be set to zero automatically.

    In the declaration of an array the size may be omitted, in such cases the compilerallocates enough space for all initialized elements. For example the statement

    int counter[]={1,1,1,1};

    Will declare the array to contain four elements with initial values 1. this approach worksfine as long as we initialize every element in the array.

    The initialization of arrays in c suffers two draw backs1. There is no convenient way to initialize only selected elements.

    2. There is no shortcut method to initialize large number of elements.

    /* Program to count the no of positive and negative numbers*/#include< stdio.h >void main( ){int a[50],n,count_neg=0,count_pos=0,I;printf(Enter the size of the array\n);scanf(%d,&n);printf(Enter the elements of the array\n);for I=0;I < n;I++)

    scanf(%d,&a[I]);for(I=0;I < n;I++){if(a[I] < 0)count_neg++;elsecount_pos++;}printf(There are %d negative numbers in the array\n,count_neg);printf(There are %d positive numbers in the array\n,count_pos);}

    Multi dimensional Arrays:

    Often there is a need to store and manipulate two dimensional data structure such as

    matrices & tables. Here the array has two subscripts. One subscript denotes the row & the

    other the column.

    The declaration of two dimension arrays is as follows:

  • 7/28/2019 C Language(Synopsis)

    47/90

    data_type array_name[row_size][column_size];int m[10][20]

    Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last

    row last column is m[9][19]

    Elements of multi dimension arrays:

    A 2 dimensional array marks [4][3] is shown below figure. The first element is given by

    marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.

    marks [0][0]

    35.5

    Marks [0][1]40.5

    Marks [0][2]45.5

    marks [1][0]

    50.5

    Marks [1][1]

    55.5

    Marks [1][2]

    60.5

    marks [2][0] Marks [2][1] Marks [2][2]

    marks [3][0] Marks [3][1] Marks [3][2]

    Initialization of multidimensional arrays:

    Like the one dimension arrays, 2 dimension arrays may be initialized by following their

    declaration with a list of initial values enclosed in braces

    Example:

    int table[2][3]={0,0,01,1,1};

    Initializes the elements of first row to zero and second row to 1. The initialization is done

    row by row. The above statement can be equivalently written as

    int table[2][3]={{0,0,0},{1,1,1}}

    By surrounding the elements of each row by braces.C allows arrays of three or more dimensions. The compiler determines the maximumnumber of dimension. The general form of a multidimensional array declaration is:

    date_type array_name[s1][s2][s3]..[sn];

    Where s is the size of the ith dimension. Some examples are:

  • 7/28/2019 C Language(Synopsis)

    48/90

    int survey[3][5][12];float table[5][4][5][3];

    Survey is a 3 dimensional array declared to contain 180 integer elements. Similarly tableis a four dimensional array containing 300 elements of floating point type.

    /* example program to add two matrices & store the results in the3rd matrix */#include< stdio.h >#include< conio.h >void main(){int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;clrscr();printf(enter the order of the matrix\n);scanf(%d%d,&p,&q);if(m==p && n==q){

    printf(matrix can be added\n);printf(enter the elements of the matrix a);for(i=0;i < m;i++)for(j=0;j < n;j++)scanf(%d,&a[i][j]);printf(enter the elements of the matrix b);for(i=0;i < p;i++)for(j=0;j < q;j++)scanf(%d,&b[i][j]);printf(the sum of the matrix a and b is);for(i=0;i < m;i++)for(j=0;j < n;j++)c[i][j]=a[i][j]+b[i][j];for(i=0;i < m;i++)

    {for(j=0;j < n;j++)printf(%d\t,&a[i][j]);printf(\n);}}

    C - Play with Strings

    In C language Strings are defined as an array of characters or a pointer to a

    portion of memory containing ASCII characters. A string in C is a sequence ofzero or more characters followed by a NULL '\0' character:

    It is important to preserve the NULL terminating character as it is how C defines

    and manages variable length strings. All the C standard library functions require

    this for successful operation.

    All the string handling functions are prototyped in: string.h or stdio.h standard

    header file. So while using any string related function, don't forget to include

  • 7/28/2019 C Language(Synopsis)

    49/90

    either stdio.h or string.h. May be your compiler differes so please check before

    going ahead.

    If you were to have an array of characters WITHOUT the null character as the last

    element, you'd have an ordinary character array, rather than a string constant.

    String constants have double quote marks around them, and can be assigned to

    char pointers as shown below. Alternatively, you can assign a string constant to a

    char array - either with no size specified, or you can specify a size, but don't

    forget to leave a space for the null character!

    char *string_1 = "Hello";char string_2[] = "Hello";char string_3[6] = "Hello";

    Reading and Writing Strings:

    One possible way to read in a string is by usingscanf. However, the problem with this, is

    that if you were to enter a string which contains one or more spaces, scanf would finish

    reading when it reaches a space, or if return is pressed. As a result, the string would getcut off. So we could use thegets function

    Agets takes just one argument - a char pointer, or the name of a char array, but don't

    forget to declare the array / pointer variable first! What's more, is that it automatically

    prints out a newline character, making the output a little neater.

    Aputs function is similar togets function in the way that it takes one argument - a char

    pointer. This also automatically adds a newline character after printing out the string.Sometimes this can be a disadvantage, soprintfcould be used instead.

    #include

    int main() {char array1[50];char *array2;

    printf("Now enter another string less than 50");printf(" characters with spaces: \n");gets(array1);printf("\nYou entered: ");

    puts(array1);

    printf("\nTry entering a string less than 50");printf(" characters, with spaces: \n");scanf("%s", array2);

    printf("\nYou entered: %s\n", array2);

    return 0;

  • 7/28/2019 C Language(Synopsis)

    50/90

    }

    This will produce following result:

    Now enter another string less than 50 characters with spaces:

    hello world

    You entered: hello world

    Try entering a string less than 50 characters, with spaces:hello world

    You entered: hello

    A string is a sequence of characters. Any sequence or set of characters defined within

    double quotation symbols is a constant string. In c it is required to do some meaningful

    operations on strings they are:

    Reading string displaying strings

    Combining or concatenating strings

    Copying one string to another.

    Comparing string & checking whether they are equal

    Extraction of a portion of a string

    Strings are stored in memory as ASCII codes of characters that make up the string

    appended with \0(ASCII value of null). Normally each character is stored in one byte,

    successive characters are stored in successive bytes.

    Character m y a g e i s

    ASCIICode

    77 121 32 97 103 10 32 105 115

  • 7/28/2019 C Language(Synopsis)

    51/90

    Character 2 ( t w o ) \0

    ASCIICode

    32 50 32 40 116 119 41 0 0

    The last character is the null character having ASCII value zero.

    Initializing Strings

    Following the discussion on characters arrays, the initialization of a string must the

    following form which is simpler to one dimension array.

    char month1[ ]={j,a,n,u,a,r,y};

    Then the string month is initializing to January. This is perfectly valid but C offers a

    special way to initialize strings. The above string can be initialized char

    month1[]=January; The characters of the string are enclosed within a part of

    double quotes. The compilertakes care of string enclosed within a pair of a double

    quotes. The compiler takes care of storing the ASCII codes of characters of the string inthe memory and also stores the null terminator in the end.

    /*String.c string variable*/#include < stdio.h >main(){char month[15];

  • 7/28/2019 C Language(Synopsis)

    52/90

    printf (Enter the string);gets (month);printf (The string entered is %s, month);}

    In this example string is stored in the character variable month the string is displayed inthe statement.

    printf(The string entered is %s, month);

    It is one dimension array. Each character occupies a byte. A null character (\0) that has

    the ASCII value 0 terminates the string. The figure shows the storage of string January inthe memory recall that \0 specifies a single character whose ASCII value is zero.

    J

    A

    N

    U

    A

    R

    Y

    \0

    Character string terminated by a null character \0.

    A string variable is any valid C variable name & is always declared as an array. Thegeneral form of declaration of a string variable is

    Char string_name[size];

    The size determines the number of characters in the string name.

    Example:

    char month[10];char address[100];

    The size of the array should be one byte more than the actual space occupied by the string

    since the complier appends a null character at the end of the string.

  • 7/28/2019 C Language(Synopsis)

    53/90

    Reading Strings from the terminal:

    The function scanf with %s format specification is needed to read the character string

    from the terminal.

    Example:

    char address[15];scanf(%s,address);

    Scanf statement has a draw back it just terminates the statement as soon as it finds a

    blank space, suppose if we type the string new york then only the string new will be readand since there is a blank space after word new it will terminate the string.

    Note that we can use the scanf without the ampersand symbol before the variable name.

    In many applications it is required to process text by reading an entire line of text from

    the terminal.

    The function getchar can be used repeatedly to read a sequence of successive single

    characters and store it in the array.

    We cannot manipulate strings since C does not provide any operators for string. For

    instance we cannot assign one string to another directly.

    For example:

    String=xyz;String1=string2;

    Are not valid. To copy the chars in one string to another string we may do so on acharacter to character basis.

    Writing strings to screen:

    The printf statement along with format specifier %s to print strings on to the screen. The

    format %s can be used to display an array of characters that is terminated by the nullcharacter for example printf(%s,name); can be used to display the entire contents of the

    array name.

    Arithmetic operations on characters:

    We can also manipulate the characters as we manipulate numbers in c language. Whenever the system encounters the character data it is automatically converted into a integer

    value by the system. We can represent a character as a interface by using the following

    method.

  • 7/28/2019 C Language(Synopsis)

    54/90

    X=a;Printf(%d\n,x);

    Will display 97 on the screen. Arithmetic operations can also be performed on charactersfor example x=z-1; is a valid statement. The ASCII value of z is 122 the statement the

    therefore will assign 121 to variable x.

    It is also possible to use character constants in relational expressions for example

    ch>a && ch < = z will check whether the character stored in variable ch is a lowercase letter. A character digit can also be converted into its equivalent integer value

    suppose un the expression a=character-1; where a is defined as an integer variable &

    character contains value 8 then a= ASCII value of 8 ASCII value 1=56-49=7.

    We can also get the support of the c library function to converts a string of digits intotheir equivalent integer values the general format of the function in x=atoi(string) here x

    is an integer variable & string is a character array containing string of digits.

    String operations (string.h)

    C language recognizes that string is a different class of array by letting us input andoutput the array as a unit and are terminated by null character. C library supports a large

    number of string handling functions that can be used to array out many o f the string

    manipulations such as:

    Length (number of characters in the string).

    Concatentation (adding two are more strings)

    Comparing two strings.

    Substring (Extract substring from a given string) Copy(copies one string over another)

    To do all the operations described here it is essential to include string.h library header filein the program.

    strlen() function:

    This function counts and returns the number of characters in a string. The length does not

    includ