Programing in C - A Study Material

Embed Size (px)

Citation preview

  • 7/26/2019 Programing in C - A Study Material

    1/90

    PROGRAMING IN C - A STUDY MATERIAL

    Compiled By:

    Mr. Kabiraj Nahak

    Supported By:

    Miss Jharana Das

    Miss Manaswini Mahapatra

    Mr. Sanjeev Kumar Nayak

    Mr. Chinmaya Mohini

  • 7/26/2019 Programing in C - A Study Material

    2/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 1

    TABLE OF CONTENTS

    MODULE I:

    Chapter 01: Data Types,Variables &Constants .. 02

    Chapter 02: Operators 10

    Chapter 03: Standard Input/output Operations. 14

    Chapter 04: Control Structures 25

    MODULE II:

    Chapter 05: Functions. 35

    Chapter 06: Storage Classes 41

    Chapter 07: Arrays 44

    Chapter 08: Pointers 55

    Chapter 09: Dynamic Memory Allocation. 62

    Chapter 10: Command Line Argument 64

    MODULE III:

    Chapter 11: Structures,Unions &Enumerations 65

    Chapter 12: File Handling. 71

    Chapter 13: Preprocessors.. 84

  • 7/26/2019 Programing in C - A Study Material

    3/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 2

    MODULE I

    CHAPTER 1 (DATA TYPES, VARIABLES AND CONSTANTS)

    DATA TYPES:

    Every variable has to have a type, which determines computers memory taken up by it and how the

    program interprets the bit patterns found in the objects storage allocation.

    Basic Data Types:

    Data Types Size RangeChar 1 byte -128 to 127

    int2 bytes (16 bit compiler) -32678 to 32767

    4 bytes (32 bit compiler) -2147483648 to 2147483647

    Float 4 bytes 3.4e - 38 to 3.4e + 38

    Double 8 bytes 1.7e - 308 to 1.7e + 308

    1. char:char is aIntegral type stored in computer as coded set of binary digits having positive decimal equivalentand able to hold 8 bits of data. For signed char 1 sign bit and 7 data bits for unsigned char all 8 data bits.

    Modifiers : signed, unsigned Size : 1 bytes

    Range: signed char : -128 to 127

    unsigned char : 0 to 255

    Format specifier: %c

    If data value exceeds max limit or min limit, it loops back to the min limit and max limit respectivily.

    For negative numbers sign bit will be 1 and data bits will be stored in 2s complement. For positive

    numbers sign bit will be 0 and data bits will be stored directly.

    2. int:Variables of int data type hold an integer value. For signed int, 1 sign bit and rest data bits. For unsigned

    int, all are data bits. Modifiers: signed, unsigned, short, long

    Size: short : 2 bytes

    int : 2 bytes (16 bit machine) and 4 bytes (32 bit machine)

    Long : 4 bytes

    Range: signed short int : -32768 to 32767

    unsigned short int : 0 to 65355

    signed int : -2n-1to 2n-1-1 (n is the number of bits)

    unsigned int : 0 to 2X2n-1-1 (n is the number of bits)

    signed long int : -2147483648 to 2147483647

    unsigned long int : 0 to 4294967295 Types: decimal integer, octal integer, hexadecimal integer.

    Format specifier: int: %d, %i

    unsigned int: %u (unsigned)

    long int: %ld, %li

    short int: %h, %hi, %hd

    octal: %o

    hexadecimal: %x

    If data value exceeds max limit it loops back from the min limit and similarly for min limit.

    For negative numbers sign bit will be 1 and data bits will be stored in 2s complement. For positive

    numbers sign bit will be 0 and data bits will be stored directly. Endianness is the system attribute that indicates whether the integers represented from right or

    left.

  • 7/26/2019 Programing in C - A Study Material

    4/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 3

    Big-endian is an order in which the big end (Most significant value in the sequence) is stored first(at lowest storage address) and in little-endian little end (least significant value in the sequence)

    is stored first (at lowest storage address).

    3. float :Variables of float data type hold a real number value.

    Modifiers : short (float), long (double), Long double

    Size: float : 4 bytes

    double : 8 bytes

    long double : 10 bytes

    Range: float : 3.4e - 38 to 3.4e + 38

    double : 1.7e - 308 to 1.7e + 308

    long double : 3.4e - 4932 to 1.1e + 4932 Types: fractional, exponential.

    Format specifier: %f (float), %lf(double), %Lf (long double), %g, %e(exponential form)

    floatstores floating point numbers with 6 digits of precision. doublestores floating point numbers

    with 14 digits of precision.

    float, double and long double data types are stored in memory in the following format:

    float 1 sign bit 8 bit exponent 23 bit mantissa

    double 1 sign bit 11 bit exponent 52 bit mantissa

    long double 1 sign bit 15 bit exponent 64 bit mantissa

    In IEEE standard, floating point no. is stored in a binary form known as normalized form.

    In the normalized form, the most significant bit of mantissa is always 1 (so this bit is not stored).

    The exponent is for representing the power of 2 instead of 10 as computers base is 2.

    Exponent is stored in unsigned binary form after adding a positive integer bias whose value is 127

    for single precision floating-point number (float) and 1023 for double precision floating point

    number.

    4. void:Its and empty data type associated with function and pointer. Its used:

    To explicitly declare a function returning no value. E.g. void show ( );

    To declare a function having no argument. E.g. void show (void );

    To create a generic pointer. e.g.

    void main ( ){

    void *p;

    printf (enter a number);

    scanf(%d, (int) &p);

    printf(%d, (int) p); }

    5. enum:An enumerated variable defines a sequence set of constant of type integral.

    e.g.

    enum subject { C, OOPS, JAVA, OS };

    Tips and Tricks:1. The process of byte ordering is known as endianness.2. Data will be stored in memory in ABCD or DCBA format that depends on Endianness of the system.3. In little-endian systems data is stored in DBCA order.4. In big-endian data is stored in ABCD order.5. C language supports 256 characters. Out of them 127 are ASCII (26 + 26 alphabets, 10 digits, 32

    special characters, 33 control characters, and 129 are Extended ASCII characters.)

    6. Size of integer type depends on compiler or word length of the processor.

    7. Unsigned modifier always makes double the range of a type.8. When a signed negative integer is compared with an unsigned integer, the signed integer is

    immediately converted to an unsigned integer temporarily. E.g.

    void main ( )

  • 7/26/2019 Programing in C - A Study Material

    5/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 4

    {

    int a = -11;

    unsigned int b=2579;

    if (a>b)

    printf (Hello);

    else

    printf (Hi); }

    Output: Hello

    Explanation: Whenthe -11(signed) is compared with 2579(unsigned), then the signed -11converted to the unsigned, i.e. 65536-11=65525(since the max range of unsigned int is 65536)

    which is greater than 2579.

    9. When the conversion is from integer to float using the format specifiers such as %d and %f, the

    same variable and the next variable(s) will suffer i.e. loss of data. e.g.

    void main ( )

    {

    int a=5, b=7;

    float c=9.9;

    printf ( %d %d %d , c, a, b);

    }Output: garbage or wrong value.

    Explanation: memory representation of integer is different from that of float.

    10.Cycle is present in integer and character data type but is not present in float or double types. If a

    value of a variable exceeds its range of its types, it immediately wraps round to positive or negative.

    Finding the output:

    If the given value of an integer is more then 65535 then ans = given value % 65536

    If the given value of an integer is in between 32767 and 65536 then ans = given value - 65536

    e.g.

    void main ( )

    {int s = 90000, c = 50000;

    printf (%d\t%d,s,c);

    }

    Output:24464 -15536

    11.The recurring 32 bits real number is less than 64 bits recurring real number. E.g.

    void main()

    {

    float x=4.2;

    if (x == 4.2)

    printf (hello);else

    printf (hi);

    }

    Output: hi

    Explanation: 4.2 consumes 8 bytes i.e. 64 bits. When its stored in x which is a float variable, it

    consumes 4 bytes i.e. 32 bits. Binary number 4.2 (8 bytes ) > binary number x (4 bytes).

    12.% (modulus) operator is not applicable to any floating number. Itll show a error (illegal use of

    floating point).

    13.Character variables always consume 1 byte but character constants always consume 2 bytes.

    (Character constants are always stored in memory in their ASCII value which is a integer.)e.g.:

    void main ( )

    {

    char p = A;

  • 7/26/2019 Programing in C - A Study Material

    6/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 5

    printf (%d\t%d, sizeof (p), sizeof (A));

    }

    Output: 1 2

    14.When float variables exceed their boundary, error is (+/-) INF (in turbo c 3.0 its overflow error).

    15.Float data is always stored in memory in mantissa and exponent format.16.Float follows 23 bits mantissa, 8 bits exponent, and 1 bit sign, but double follows 52 bits mantissa,

    11 bits exponent and 1 bit sign.

    17.Enum data type creates a sequence set of integral constants. There is no cycle present in enum data

    type.18.BCPL is a type-less language.19.When a language is able to produce a new data type it is called extensibility.20.Typedef creates a new name but does not create a new type.

    21.If the character constant may be one or two characters long, but only the 1stcharacter is considered

    (turbo c). More than two will show an error.

    e.g.

    void main ( )

    {

    char p=AB;

    printf (%c,p);}

    Output:A (in turbo c but in ANSI C output is B)

    22.No two enumerated constants can be assigned the same value.

    e.g.

    void main ( )

    {

    enum day { sun, mon };

    enum star { sun, moon };

    }

    Output:error: multiple declaration for sun.

    23.No variable except a pointer can be expressed with the type void. (Error: sizeof variable is

    unknown or zero.)

    24.void type is used in three different places, such as:i) No argument to a function ii) No Return type iii) Generic Pointer

    25.Result of an operation is not bounded by any overflow.

    void main ( )

    {

    short int a=20000, b=20000;

    if(a+b>0)

    printf("hello");else

    printf("Hi");

    }

    Output:hello

    void main ( )

    {

    short int a=20000, b=20000;

    short int c=a+b;

    if(c>0)printf("hello");

    else

    printf("Hi");

    }

    Output:Hi

    (Result of an operation is not

    bounded by any overflow.)

    (Value of an integer variable wraps

    to the negative value due to overflow.)

    VARIABLES AND CONSTANTS:

    Variables:Its a named object that resides in the memory (RAM) and is capable of being examined and modified.

    Variable name is a name given to a location in memory of a computer where different constants are

    stored.

  • 7/26/2019 Programing in C - A Study Material

    7/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 6

    Variable Declaration:

    A variable must be declared before using it to make the compiler know the name and type of variable so

    that itll decide what type of values it can take and what will be the size itll take in memory.

    Syntax: ;(Storage class is optional)

    E.g.

    static int a;

    char a;

    Variable Initialization:

    Giving an initial value to a variable is called initialization of a variable.A variable should be initialized to avalue to be used in different operations.

    Syntax: = ;E.g.

    static int a=20;

    float b=2.23;

    Properties of Variables:The properties of variables are decided or affected by the following aspects and factors.

    Scope of the variables (local and global)

    Life span of the variable

    Default initial value of a variable

    Storage of the variable (in memory or in register)

    L value and R value of the variable

    Qualifier of the variable

    Use of Variables:

    Fixed value: value of a variable is fixed after initialization if its value does not change in the run time.

    Stepper/Counter: Used in loops.

    Most-recent holder: Repeatedly asks the user to input until the given value is valid in as per the predefined criteria and the variable holds the last valid input.

    Gatherer: The value of a gatherer accumulates all the values gone through so far in a cumulative

    effect.

    Transformation: In this case the variable always gets its new value from the value(s) of other

    variable(s) through the same calculation.

    One-way flag:Its a Boolean variable which once changed cant get its original value anymore.

    Follower:it always gets the old value of another known variable as its new value.

    Temporary: If the value of a variable is needed only for a short period.

    Organizer:Its an array which is used for recognizing its elements after organization.

    Naming Conventions:ANSI has formulated a set of rules for naming the variables in an efficient manner.

    The variable name must be within 32 characters.

    The first character must be an alphabet or an underscore (_) and the rest can be alphabets, digits or

    underscores.

    No space or special characters are allowed.

    No keyword can be a variable name.

    Declaration vs. Definition:

    Declaration is used to specify the name and type of an object to the compiler. It asserts that the object

    exists but does not actually allocate memory space for it. (Reuse of the variable from somewhere out ofscope).

    While definition is used to provide a value to a variable so that itll reserve memory space for itself.

    E.g.

    void main ( )

  • 7/26/2019 Programing in C - A Study Material

    8/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 7

    {

    extern int x; // variable declaration

    printf (%d, x);

    }

    int x = 5; // variable definition

    L-value and R-value:

    C compiler classifies the expressions into 2 categories: -

    L Value:

    Its an expression that refers to an object that has a location and can be changed or examined and be

    visible only at the left hand side of an assignment operator. E.g. int k=5; but not int 5=k;

    R Value

    Its an expression that permits examination but not alteration and is visible only in the right hand side

    of an assignment operator.

    E.g.

    int it ( );

    it=2; //wrong as it is a function not a variable.

    it=x; //wrong as it is a function not a variable.

    Qualifiers:

    Qualifiers improve the quality, efficiency and accessibility of the data objects or function objects.

    Volatile qualifier:

    E.g.int volatile x; orvolatile int x;

    Volatile is used to explicitly tell the compiler that a variables value may be changed at any time by

    some external source (from outside the program, may be a kernel code or device drivers).

    When the variable is declared as volatile, the compiler will examine the value of the variable each

    time its encountered to see whether any external alteration has changed the value or not.

    The volatile qualifier tells the compiler that a variable may be referenced in such a way that the

    values hidden from the compiler but known to the programmer.

    Value of the volatile qualifier gets refreshed every time its accessed and hence should be used to

    qualify variables which are very frequently accessed, like loop counters.

    In case of hardware mapping the variable must be declared to be volatile.

    Const qualifier:

    const qualifier tells the compiler, the variable value cannot be changed in the current file, but can be

    modified in another file.

    E.g.int const x=5; orconst int x=5;

    Aconst variable can be initialized only at the time of declaration.

    In case of a constant pointer (const *p) the address, the pointer refers to can never be changed as

    well the pointer cant be initialized in future. But the value at the address the pointer contains can be

    changed.

    Const in function parameter provides security to data while passing data as a parameter in a function.

    Global Identifiers:

    Turbo c uses many global variables for different purposes. All global variables are pre fixed with an

    underscore (_) character. E.g. _ _TIME_ _ (no space) will show the current time.

    Constants:A constant is an entity that does not change or alter. In C constants can be created using const, enum, or by

    using Macro expansion (#define c=11). There are different types of constants as follows.

    Integer Constant:

    Its of three types: Decimal integer constants: int x=15;

    Octal integer constant: int x=015;

    Hexadecimal constant:int x=0x15;

  • 7/26/2019 Programing in C - A Study Material

    9/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 8

    If the number is preceded with a 0 or 0x, its an octal or hexa-decimal integer constant respectively. If the

    number is succeeded with a L or u, its an long or unsigned integer constants respectively. (5L, 9u)

    Valid Character Constant:

    Its normally a character out of 256 characters enclosed with in a single quote ( ). Octal character

    constants usually preceded by a backslash (\a). Hexa-decimal character constants are preceded by a \x.

    e.g. char p=34;

    Escape Character Constant:

    All escape character constants start with \ and implicitly represented in the form of octal numbers.

    If the escape character range is more than 255, itll cause an error Numeric constant too large.

    \377 is a valid character constant as its by default an octal number with decimal value 255. But

    \378 is a not valid octal number hence not a character constant.

    \457 is a valid octal number but range is beyond 255 and hence invalid character constant.

    If the 1stcharacter followed by a \, is a valid octal digit (0 to 7), itll be considered as an octal number

    or else as any character constant.

    Some valid Escape Characters:

    Escape Character ASCII value Purpose

    \a 7 Bell character

    \b 8 Back space

    \t 9 Horizontal tab

    \n 10 New line

    \v 11 Vertical tab

    \f 12 Form feed

    \r 13 Carriage return

    Real Constant:

    Its the floating point constants. It could be written in two forms: Fractional form and exponential form.

    e.g.

    float x = 4.5; //4.5 is double constant.

    float x = 4.5f; //4.5f is float constant.

    float x = 4.5e+2; //4.5e+2 is exponential constant.

    float x = 4.5L; //4.5L is long double constant.

    Tips and Tricks:1. 2 types of variables: value type (int a;)and reference type (int a[5];).

    value type variables are created in the stack area while reference type variables are created in the

    heap area.

    2. Microprocessor generates the address for the variables and the storage class decides where it will

    be created and how many bytes itll occupy.

    3. When the sizeof ( ) operator is used with an object, parenthesis is not compulsory, but when used

    with any data type, its compulsory. E.g. sizeof x; sizeof 5; sizeof (int);

    4. Variables cant be initialized in the sizeof ( ) operator.

    5. An ordinary pointer may be used to point a pointer to volatile object, but for that an explicit type

    cast must be used to assign a pointer to a volatile object to an ordinary pointer.

    e.g.

    volatile int volatile_int;

    int *ordinary_ptr;

    volatile int *ptr_to_volatile;

    int *volatile volatile_ptr;

    ptr_to_volatile = ordinary_ptr; //valid

    ordinary_ptr = ptr_to_volatile; //invalidordinary_ptr = (int *) ptr_to_volatile; //valid

    6. 5 is a character constant while 5 is a string constant. 5Lis a long integer constant while 5.0Lis a

    long double constant.

  • 7/26/2019 Programing in C - A Study Material

    10/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 9

    7. constand volatile can be used together. E.g. const volatile int x=5; or volatile const int x=5;

    8. Function name can be used as a variable name inside that function only.

    main is a special type of function, not a keyword.

    9. The minimum octal character constant is \000 and maximum octal character constant is \377.10.All constants in C are R value category of objects.11.The number of constants and variables in C are equal.12.Constant variables, array name and function name; enum constants are R value category of objects

    and they should always be placed in the right side of an equal-to operators.

    13.All escape sequence characters are octal character constants.14.The size of the null string constant is 1 byte.15.\0 is null character constant whose ASCII value is 0.16.Every variable and function allocates memory in load time and run time, but how much memory will

    be allocated and where will be allocated that is decided during compile and linking time.

  • 7/26/2019 Programing in C - A Study Material

    11/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 10

    CHAPTER 2 (OPERATORS)

    Operatorsspecify the basic operations that are to be performed with the basic data objects (variables and

    constants). C consists of 45 operators. Expressions formulated with the help of them and are evaluated to

    get desired result.

    Operators are classified depending upon the number of operands, where an operand is the data item upon

    which the operators act. E.g. X+Y (X and Y: operands, +: an operator)

    Classifications:

    1. Unary (1 operand)2. Binary (2 operands)

    3. Ternary (3 operands)

    Precedence Table:

    Precedence Operator Associative

    1 ( ) [ ] -> . Left to Right

    2

    - ++ _

    ~ ! &

    * (Type) sizeof ( )

    Right to Left

    3 * / % Left to Right

    4 + - Left to Right5 > Left to Right

    6 < >= Left to Right

    7 == != Left to Right

    8 & Left to Right

    9 ^ Left to Right

    10 | Left to Right

    11 && Left to Right

    12 || Left to Right

    13 ? : Right to Left

    14= *= /= %=+= -= &= ^= |=

    =

    Right to Left

    15 , Left to Right

    Different Type of Operators:

    1. Arithmetic Operators: (+, -, *, / and % )

    + - unary dummy operator and binaryaddition operator.

    - - unary negation operator and binary subtraction operator.

    * - binaryproduct operator.

    / - binary division operator.

    % - modulo-division operator (binary).

    Types of arithmetic expressions:

    a) INTEGER MODE EXPRESSION: if all the operands used are integers (char, unsigned char, int,

    short, long, unsigned int), the expression is called an integer mode expression and the

    resultant value is always an integer.

    E.g. 9/5 = 1

    b) REAL MODE EXPRESSION: if all the operands used are real values (float, double, long double),

    the expression is called a real mode expression and the resultant value is always a float type.

    E.g. 5.0 + 4.0 = 9.0

    c) MIXED MODE EXPRESSION: if some operands are integer type and some are of real type in

    an expression, its called a mixed mode expression and the resultant value will always be offloat type. E.g. 5.0 + 4 = 9.0

    2. Relational Operators: (, ==, >=,

  • 7/26/2019 Programing in C - A Study Material

    12/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 11

    < - isless than operator

    > -is greater than operator

    == -is equals to operator

    >= -greater than equals to operator

    >= -less than equals to operator

    != - not equals to operator

    Relational expressions:

    Relational expressions always result either 0 (false) or 1(true non-zero).

    3. Logical Operators: (&&, ||, !)

    && - logicaland operator (if the values of both the objects are non-zero (true), it results 1 else

    0.)

    || - logicalor operator (if the values of both the objects are zero (false), it results 0 else 1.)

    ! - logical not operator (if the value of an object is 0, it results 1 else 0.)

    Logical expressions:

    Logical expressions also return either 0 or 1.

    4. Assignment Operators: (=, +=, -=, *=, /=, %=)

    = - assignment operator (its used to assign the value of an expression to a variable.)

    Short-hand arithmetic assignment operator: (op=)C has a set of short-hand assignment operators of the form

    v op=exp;

    Where vis a variable, expis an expression and opis c binary arithmetic operator. op= is known as

    shorthand assignment operator.

    The assignment statement v op=exp;

    is same as v = v op (exp); with v evaluated only once.

    e.g. x +=y+1; is same as x = x + (y+1);

    The short-hand operator += means add y+1 to x or increment x by y+1.

    Advantages of using short-hand assignment operator are:

    1. The left hand side is not repeated in the right hand side and hence easier to write.

    2. The statement is more concise and easier to read.

    3. The statement is more efficient.

    5. Increment/ Decrement Operators: (++, --)

    ++ - increment operator: adds 1 to the object.

    -- - decrementoperator: subtracts 1 from the object.Pre- increment/decrement: (++x, --x)

    Here first increment or decrement will be done and then the expression will be evaluated.

    E.g.

    a=5, b=9;

    ++a + b = 15, a == 6 and b == 9.Post- increment/decrement: (x++, x--)

    Here first the expression will be evaluated and then increment or decrement will be done.

    E.g.

    a=5, b=9;

    a++ + b = 14, a == 6, b == 9.

    6. Conditional Operators: ( ? : )

    Its a ternary operator pair used for conditional operation.

    Syntax: exp1 ? exp2 : exp3

    Here exp1, exp2, exp3 are expressions. exp1 is evaluated first. If its non-zero (true) then exp2 is

    evaluated and becomes the value of the whole expression. If exp1 is zero (false), then exp3 isevaluated and becomes the value of the whole expression.

    7. Bitwise Operators: (~, >>,

  • 7/26/2019 Programing in C - A Study Material

    13/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 12

    ~ -bitwise ones complement operator. E.g. int x= ~5; here x= -6. (~a = -(a+1))

    >> -bitwise Right shift operator. E.g. int x= 5>>1; here x= 2. (binary of 5 is shifted to right by1bit )

    - pointer to member access operator. (structure pointer operator)

    & -address of operator.

    * -value at address operator. (pointer operator)b. sizeof ( ) - gives a result equal to the size of the object, or expression or data type in bytes.

    c. (type) - forces the compiler to convert the value from one cast to another cast with out changingthe originality.

    d. , (comma operator) its used to link the related expressions together. It enjoys the low priorityand associativity is from left to right. So the value of the last variable will be the result of the

    expression. Its used in for and while loops also.

    Tips and Tricks:1. Precedence decides the priority of the operators while associativity determines the order of

    evaluation.

    2. Precedence and associativity of an operator is only implemented if expression is represented in INFIXnotation.

    3. The operator which requires three operands is called ternary operator. ?:is a conditional ternaryoperator.

    4. sizeof ( ) is a operator which is also a keyword but looks like a function. It does not evaluate any

    expression passed as an argument. Its applicable only to the variables, constants, data types but not

    to the functions.

    5. Modulus (%) works only with the integral operands and cant be applied to float or double (Error:

    Illegal use of floating point).

    6. C does not allow ** like ++ as ** is not an operator.

    7. Increment/ decrement operators can only be applied to the variables. Cant be applied to theconstants (5++; Error: Lvalue required.)

    8. Return keyword cant be used with conditional operator.

    e.g. p > 65540 ? return 1: return 0; //Error: expression syntax.

    9. Bitwise operators work with only integer and characters.

    e.g. float x=2.0&5; //Error: Illegal use of floating point.

    10.Continuous triple plus (+++) are allowed but not more. e.g. a+++5; //a++ + 5

    If more than three plus are used, then they must be separated by spaces.

    E.g.

    a++ + ++b; //valid

    a+++++b; //Error: L value required.11.If the left hand operand yields false value, the right operand is not evaluated in a logical expression

    using &&. E.g.

    int x, y = 2, a = 5;

    x = y-2 && a++;

  • 7/26/2019 Programing in C - A Study Material

    14/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 13

    printf (%d, a);

    Output: 5

    12.If the left hand operand yields true value, the right operand is not evaluated in a logical expression

    using ||. E.g.

    int x, a = 5;

    x = 5+3 || a++;

    printf (%d, a);

    Output: 5

    13.If two operands in an assignment expression are of different data types then the value of the righthand operand will automatically be converted to the type of the operand on left. The entire

    expression will then be of same data type.

    14.Floating-point values are truncated when assigned to integer variables.

    15.Double precision values are rounded when assigned to floating point single precision identifiers.16.Associativity of a comma ( , ) operator is left to right.17.# is a string forming operator that converts a non-string data to string and is used only in preprocessor

    directives.

    18.There is no operator in C to calculate the power of a number. 19.Return value of relational and logical operators is 0 or 1.

    20.x++ and ++x both are always same if they are used independently. They behave differently when theyform part of an expression.21.If ++ or - - operators occurs more than once, then first two makes a pair and are evaluated, then the

    result is added in next, then next

  • 7/26/2019 Programing in C - A Study Material

    15/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 14

    CHAPTER 3 (STANDARD INPUT/OUTPUT OPERATIONS)

    Accepting the required inputs from input devices and displaying the produced result on output devices are

    referred to as input/output operations.

    There are three types of I/O depending on the source devices for input and target devices for output. They

    are:

    a.Console I/O

    b.Disk I/O

    c. Port I/OThe standard library of I/O functions for a platform will be provided by the designer of the compiler for

    that platform.

    Since the prototypes of the functions are available in the header files (ex: stdio.h, conio.h, etc.), we need to

    include them as part of our source program file with the help of the preprocessor directive #include as:

    #include

    The instruction # include tells the compiler to search for a file named stdio.h and place its

    contents at this point in the program. The content of the header file become part of the source code when

    it is compiled.

    In this chapter we deal with console I/O only. Console I/O uses keyboard as the standard input device and

    screen as the standard output device.There are two types of console I/O operations such as:

    1. Unformatted Input/output Operation.

    2. Formatted Input/output Operation.

    Unformatted Input/Output OperationsUnformatted Input Operation:

    getc()Header fil e : stdi o. hPrototype : i nt get c(FI LE *st r eam) ;Description : Gets character from stream. getcreturns the next character on the given input stream andincrements the stream's file pointer to point to the next character.

    Note:For Win32s or Win32 GUI applications, stdin must be redirected.Return Value : On success, getcreturns the character read, after converting it to an in twithout sign extension. On

    end-of-file or error, it returns EOF.Example: #i ncl ude i nt mai n( voi d){

    char ch;pr i nt f ( " I nput a charact er: ") ;ch = get c( st di n) ; / / r eads a char act er f r om t he st andar d i nput st r eam

    pr i nt f ( "The char acter i nput was: ' %c' \ n", ch) ;r et ur n 0;

    }

    getch()Header fil e : coni o. hPrototype : i nt get ch( voi d) ; Description : Gets character from keyboard, does not echo to screen. getchreads a single character directly fromthe keyboard, without echoing to the screen.Note:Do not use this function for Win32s or Win32 GUI applications.Return Value : getchreturns the character read from the keyboard.Example: #i ncl ude

    #i ncl ude i nt mai n( voi d){

    i nt c ;i nt ext ended = 0;c = get ch( ) ;

  • 7/26/2019 Programing in C - A Study Material

    16/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 15

    i f ( ! c)ext ended = getch( ) ;

    i f ( ext ended)pr i nt f ( "The char acter i s ext ended\ n") ;

    el sepr i nt f ( "The char acter i sn' t ext ended\ n") ;

    r et ur n 0;}

    getchar()

    Header fil e : stdi o. hPrototype : i nt get char ( voi d) ; Description : Gets character from stdin. getcharis a macro that returns the next character on the named inputstream stdin. It is defined to be getc(stdin).Note:Do not use this function for Win32s or Win32 GUI applications.Return Value : On success, getcharreturns the character read, after converting it to an in twithout sign extension.On end-of-file or error, it returns EOF.Example: #i ncl ude i nt mai n( voi d)

    {i nt c ;

    / * Not e t hat get char r eads f r om st di n and i s l i ne buf f er ed; t hi s means i t wi l l notr et ur n unt i l you pr ess ENTER. */

    whi l e ( ( c = get char ( ) ) ! = ' \ n' )pr i nt f ( "%c", c) ;

    r et ur n 0; }

    getche()Header fil e : coni o. h

    Prototype : i nt get che( voi d) ; Description : Gets character from the keyboard, echoes to screen. getchereads a single character from the

    keyboard and echoes it to the current text window using direct video or BIOS.Note:Do not use this function for Win32s or Win32 GUI applications.Return Value : getchereturns the character read from the keyboard.

    Example:#i ncl ude #i ncl ude i nt mai n( voi d){

    char ch;pr i nt f ( " I nput a charact er: ") ;ch = getche( ) ;

    pr i nt f ( "\ nYou i nput a ' %c' \ n", ch) ;r et ur n 0;

    }

    gets()Header fil e : stdi o. hPrototype : char * get s( char * s) ;Description : Gets a string from stdin. getscollects a string of characters terminated by a new line from thestandard input stream stdin and puts it into s. The new line is replaced by a null character (\0) in s.getsallows inputstrings to contain certain whitespace characters (spaces, tabs). getsreturns when it encounters a new line; everything

    up to the new line is copied into s.Note:For Win32s or Win32 GUI applications, stdin must be redirected.Return Value :On success, getsreturns the string argument s. On end-of-file or error, it returns NULL

    Example:#i ncl ude i nt mai n( voi d)

  • 7/26/2019 Programing in C - A Study Material

    17/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 16

    {char str i ng[ 80] ;pr i nt f ( " I nput a s t r i ng: " ) ;get s(st r i ng) ;pr i nt f ( "The st r i ng i nput was: %s\ n", st r i ng) ;r et ur n 0;

    }

    Unformatted output Operation:

    putc()Header file : stdi o. hPrototype : i nt put c( i nt c, FI LE *str eam) ;Description :Outputs a character to a stream. putcis a macro that outputs the character cto the stream given bystream.Return Value :On success, putcreturns the character printed, c.On error, putcreturns EOF.

    putch()

    Hederfile : coni o. hPrototype : i nt put ch( i nt c) ;Description : Outputs character to screen. putchoutputs the character cto the current text window. It is a textmode function performing direct video output to the console. putchdoes not translate linefeed characters (\n) into

    carriage-return/linefeed pairs. The string is written either directly to screen memory or by way of a BIOS call,depending on the value of the global variable_directvideo.Note:This function should not be used in Win32s or Win32 GUI applications.Return Value :On success, putchreturns the character printed, c. On error, it returns EOF.

    Example:#i ncl ude #i ncl ude i nt mai n( voi d){

    char ch = 0;pr i nt f ( " I nput a s t r i ng: " ) ;whi l e ( ( ch ! = ' \ r ' ) ){

    ch = get ch( ) ;put ch( ch) ;

    }r et ur n 0;

    }

    putchar()Header fil e : stdi o. hPrototype : i nt put char ( i nt c) ;Description : putchar(c)is a macro defined to be putc(c, stdout).Note:For Win32s or Win32 GUI applications, stdoutmust be redirected.Return Value : On success, putcharreturns the character c. On error, putcharreturns EOF.

    Example:#i ncl ude / * def i ne some box- dr awi ng char act er s */#def i ne LEFT_TOP 0xDA#def i ne RI GHT_TOP 0xBF#def i ne HORI Z 0xC4#def i ne VERT 0xB3

    #def i ne LEFT_BOT 0xC0#def i ne RI GHT_BOT 0xD9i nt mai n( voi d){

    char i , j ;/ * draw t he t op of t he box */

  • 7/26/2019 Programing in C - A Study Material

    18/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 17

    put char ( LEFT_TOP) ;f or ( i =0; i

  • 7/26/2019 Programing in C - A Study Material

    19/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 18

    FORMAT SPECIFIERS FOR DIFFERENT DATA TYPES AVAILABLE IN C ARE:

    Format Specifier Meaning

    %c a character

    %d a decimal integer

    %f a floating point value

    %e a floating value

    %h a short integer

    %ld a long integer%s a string

    %u an unsigned integer

    %o an octal number

    %x an hexadecimal number

    %[..] a string of words

    scanf()Header file : stdi o. hPrototype : i nt scanf ( const char *f or mat [ , addr ess, . . . ] ) ;Description :Scans and formats input from the stdin stream.Note :For Win32s or Win32 GUI applications, stdin must be redirected.The scanffunction:

    scans a series of input fields one character at a timeformats each field according to a corresponding format specifier passed in the format string *format.vsscanfscans and formats input from a string, using an argument list.

    There must be one format specifier and address for each input field. scanfmight stop scanning a particular field beforeit reaches the normal end-of-field (whitespace) character, or it might terminate entirely.Warning :scanfoften leads to unexpected results if you diverge from an expected pattern. You must provideinformation that tells scanf how to synchronize at the end of a line. The combination of gets or fgets followed by sscanfis safe and easy, and therefore recommended over scanf.Return Value :On success, scanfreturns the number of input fields successfully scanned, converted, and stored.The return value does not include scanned fields that were not stored. On error: if no fields were stored, scanfreturns0. if scanfattempts to read at end-of-file or at end-of-string, it returns EOF.

    cscanf()Header file : coni o. hPrototype : i nt cscanf ( char *f or mat [ , addr ess, . . . ] ) ; Description : Scans and formats input from the console.cscanfscans a series of input fields one character at atime, reading directly from the console. Then each field is formatted according to a format specifier passed to cscanfinthe format string pointed to by format. Finally, cscanfstores the formatted input at an address passed to it as anargument following format, and echoes the input directly to the screen. There must be the same number of format

    specifiers and addresses as there are input fields.Note :cscanfmight stop scanning a particular field before it reaches the normal end-of-field (whitespace)character, or it might terminate entirely for a number of reasons. See scanffor a discussion of possible causes.Note :Do not use this function for Win32s or Win32 GUI applications.Return Value : cscanfreturns the number of input fields successfully scanned, converted, and stored; the returnvalue does not include scanned fields that were not stored. If no fields were stored, the return value is 0. If cscanfattempts to read at end-of-file, the return value is EOF.

    Example:#i ncl ude i nt mai n( voi d){

    char str i ng[ 80] ;/ * cl ear t he screen */

    cl r scr ( ) ;/ * Prompt t he user f or i nput */cpr i nt f ( "Ent er a st r i ng wi t h no spaces: ") ;/ * r ead t he i nput */cscanf ( "%s", str i ng) ;/ * di spl ay what was r ead */

  • 7/26/2019 Programing in C - A Study Material

    20/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 19

    cpr i nt f ( "\ r \ nThe str i ng ent er ed i s: %s", str i ng) ;r et ur n 0;

    }

    sscanf()Header file : stdi o. h

    Prototype : i nt sscanf ( const char * buf f er , const char *f or mat [ , addr ess, . . . ] ) ;Description :Scans and formats input from a string.Note :sscanfscans a series of input fields, one character at a time, reading from a string. Then each fieldis formatted according to a format specifier passed to sscanfin the format string pointed to by format. Finally, sscanfstores the formatted input at an address passed to it as an argument following format. There must be the samenumber of format specifiers and addresses as there are input fields. sscanfmight stop scanning a particular fieldbefore it reaches the normal end-of-field (whitespace) character, or it might terminate entirely, for a number ofreasons.Return Value :On success, sscanfreturns the number of input fields successfully scanned, converted, and stored;the return value does not include scanned fields that were not stored. If sscanfattempts to read at end-of-string, itreturns EOF. On error (If no fields were stored), it returns 0.

    Example:#i ncl ude #i ncl ude #i ncl ude char *names[ 4] = {"Pet er ", "Mi ke" , "Shea", "J er r y"};#def i ne NUMI TEMS 4i nt mai n( voi d){

    i nt l oop;char t emp[ 4] [ 80] ;char name[ 20] ;i nt age;l ong sal ar y;cl rscr( ) ; / / cl ear t he screen

    / * cr eat e name, age and sal ary data */f or ( l oop=0; l oop < NUMI TEMS; ++l oop)

    spr i nt f ( t emp[ l oop] , "%s %d %l d", names[ l oop] , r andom( 10) + 20, r andom( 5000) +27500L) ;/ * pr i nt t i t l e bar * /

    pr i nt f ( "%4s | %- 20s | %5s | %15s\ n" , "#" , "Name", "Age", "Sal ar y") ;pr i nt f ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n" ) ;

    / * i nput a name, age and sal ary dat a */f or ( l oop=0; l oop < NUMI TEMS; ++l oop)

    {sscanf ( t emp[ l oop] , "%s %d %l d", &name, &age, &sal ary) ;pr i nt f ( "%4d | %- 20s | %5d | %15l d\ n" , l oop + 1, name, age, sal ar y) ;}

    r et ur n 0;

    }

    Formatted output Operation:

    The printf ( ) is used to display data on the screen. The syntax of its usage is

    Syntax:

    printf ( control string , arg1 , arg2,..,argn ) ;

    Here arg1,arg2,,argn are the variables, the values of which are to be displayed on the screen.

    Control string consists of the following three items:

    a. Format specifiers similar to those discussed in the case of scanf( ).b. Some sequence of characters, which will be displayed on the screen as they are.

    c. Character like \n,\t and \b etc. These characters are called escape sequence characters.

    Example: To display the value of the variable n of int type.

    printf ( %d , n ) ; // %d is the format specifier for the int variable n.

  • 7/26/2019 Programing in C - A Study Material

    21/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 20

    printf ( %c , ch ) ; // ch is a variable of character .

    printf ( %f , f ) ; // f is a variable of float

    printf ( %d %f %c , i , f , c ) ;

    NOTE:

    1. The order of the format specifiers matches with that of the variables (arguments ).This is a

    must when we are displaying values of more then one variable.

    2. Many times, the printf ( ) is used to display just some messages.

    Format specifiers for other data types available in C are:

    Format Specifiers Meaning

    %c Character

    %d Decimal integer

    %ld Long integer

    %f Floating point value in decimal point notation

    %e Floating point value in exponential form

    %h Short integer

    %lf Long float

    %s String

    %u Unsigned integer%p Pointer

    %o Octal number without the prefix 0

    %x Hexadecimal number without the prefix 0x

    Escape Sequence Characters

    Escape

    sequence

    Meaning Escape

    sequence

    Meaning

    \n New line \a Alert character

    \t Horizontal tab \\ Backslash

    \v Vertical tab \? Question mark

    \f Form feed \ Single quote

    \b Back space \ Double quote

    printf()Header file : stdi o. hPrototype : i nt pr i nt f ( const char *f or mat [ , ar gument , . . . ] ) ;Description :Writes formatted output to stdout.printffunction:

    Accepts a series of arguments.

    Appllies to each argument a format specifier contained in the format string *format.Outputs the formatted data (to the screen, a stream, stdout, or a string).

    There must be enough arguments for the format. If there are not, the results will be unpredictable and likelydisastrous. Excess arguments (more than required by the format) are merely ignored.Note :For Win32s or Win32 GUI applications, stdoutmust be redirected.Return Value : On success, printfreturns the number of bytes output. On error, printfreturns EOF.

    cprintf()Header file : coni o. hPrototype : i nt cpr i nt f ( const char *f or mat [ , ar gument , . . . ] ) ;Description :Writes formatted output to the screen.cprintfaccepts a series of arguments, applies to each aformat specifier contained in the format string pointed to by format, and outputs the formatted data directly to thecurrent text window on the screen. There must be the same number of format specifiers as arguments. The string iswritten either directly to screen memory or by way of a BIOS call, depending on the value of the global variable

  • 7/26/2019 Programing in C - A Study Material

    22/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 21

    _directvideo. Unlike fprintfand printf, cprintfdoes not translate linefeed characters (\n) into carriage-return/linefeed

    character pairs (\r\n). Tab characters (specified by \t) are not expanded into spaces.Note :Do not use this function for Win32s or Win32 GUI applications.Return Value : cprintfreturns the number of characters output.

    Example:#i ncl ude i nt mai n( voi d){

    / * cl ear t he screen */cl r scr ( ) ;

    / * cr eat e a t ext wi ndow */wi ndow( 10, 10, 80, 25) ;/ * out put some t ext i n t he wi ndow */cpr i nt f ( " Hel l o wor l d\ r \ n" ) ;/ * wai t f or a key */get ch( ) ;r et ur n 0;

    }

    sprintf()Header file : stdi o. hPrototype : i nt spr i nt f ( char *buf f er , const char *f or mat [ , ar gument , . . . ] ) ;Description : Writes formatted output to a string.Note :sprintfaccepts a series of arguments, applies to each a format specifier contained in the formatstring pointed to by format, and outputs the formatted data to a string. sprintfapplies the first format specifier to thefirst argument, the second to the second, and so on. There must be the same number of format specifiers asarguments.Return Value : On success, sprintfreturns the number of bytes output. The return value does not include theterminating null byte in the count. On error, sprintfreturns EOF.

    Example:#i ncl ude #i ncl ude i nt mai n( voi d){

    char buf f er [ 80] ;spr i nt f ( buf f er , "An appr oxi mat i on of Pi i s %f \ n", M_PI ) ;put s(buf f er ) ;r et ur n 0;

    }

    Formatting of Outputs

    Formatting of outputs refers to displaying the outputs in more readable and comprehensible manner. Themain objective of formatting is to increase the degree of readability of outputs.

    Formatting of Integers

    Formatting of float point values

    Formatting of IntegersSuppose i is a variable of type int and its value is 3456. The value of i can be formatted by modifying the

    above control string. The modified control string would be %wd, where w is an interger specifying the

    width which the value of i has to be displayed.

    Different cases of representation of formatted output:

    1. printf ( %6d , i ) ;

    3 4 5 6

    Since, the width specified is six, six columns are allocated and the value of i is right justified in the specified

    width.

  • 7/26/2019 Programing in C - A Study Material

    23/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 22

    2. printf ( %3d , i ) ;

    3 4 5 6

    since , the width specified is less than the actual number of digit of the value in i ,the width is ignored and

    full value is displayed.

    Formatting of float point values:Suppose f is a variable of type float and its value is 3456.56. To display the value of f, we use the following

    printf( ) statements:

    printf(%f, f );As a result, the value of f will be displayed on the screen starting from the first column of the screen as

    follows:

    3456.560000

    The value of f can be formatted by modifying the above control string. The modified control string would

    be %w.pf, where w is an integer specifying the width within which the value of f has to be displayed and p

    denotes the number of digits to be displayed after the decimal point.

    1. printf( %7.2f, f );

    Since the width specified is seven, seven columns are allocated and the value of f is displayed as shownearlier. Note that the decimal point also occupies one location and only two digits are displayed after

    the decimal point.

    2. printf( %3.2f, f );

    Since the width specified is less than the actual number of digits of the value in f width is ignored

    and the full value is displayed.

    3. printf( %9.2f, f );

    3 4 5 6 . 5 6Since the width specified is nine which is greater than the number of digits in the given number, nine

    columns are allocated and the value of f is right justified in the specified width.

    4. printf( % - 9.2f, f );

    3 4 5 6 . 5 6

    Since the width specified is nine which is greater than the number of digits in the given number, nine

    columns are allocated and the value of f is left justified in the specified width because of the presence

    of symbol before the width specifier.

    5. printf( % 09.2f, f );

    0 0 3 4 5 6 . 5 6

    Since the symbol 0 is used before the width specifier, the leading blanks are filled with zeros. Thenumber is said to have been padded with zeros.

    6. printf( % 7.1f, f );

    3 4 5 6 . 6

    Since the number of digits to be displayed, which is one, is less than the actual number of digits (two)

    after the point in the given number, the value is rounded off to the first digit.

    7. printf( % e, f );

    3 . 4 5 6 5 6 0 e + 0 3

    Display the floating point number in exponentiation form with six digits after the point in the mantissa.

    8. printf( %10.2 e, f );

    3 . 4 6 e + 0 3Display the floating point number in exponentiation form with three after the point in the mantissa

    within the specified width. The display is right justified.

    9. printf( % - 10.2 e, f );

    3 4 5 6 . 5 6

    3 4 5 6 . 5 6

  • 7/26/2019 Programing in C - A Study Material

    24/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 23

    3 . 4 6 e + 0 3

    Display the floating point number in exponentiation form with three after the point in the mantissa

    within the specified width. The display is left justified because of the presence of minus symbol before

    the width.

    Formatting Of Characters:Suppose c is a variable of type char. To display the character stored in the variable C, we use the following printf ( )

    statement:

    printf ( %c , c ) ;

    As a result of the execution of the statement, the character stored in will be displayed on the screen in the currentposition of the cursor. Similar to formatting of integer s, characters also can be formatted. The modified control

    string to display a character is

    %wc, where w is the width specifier.

    The character will be displayed right-justified in the field of w columns. We can make the display left-justified by

    placing a minus sign before the integer w. The default value for w is 1.

    Example:

    1. printf ( %4c , c ) ;

    Since, the width specified is four, four columns are allocated and the character stored in c is displayed right justified

    in the width as follows:

    2. printf ( % -4c , c ) ;Since the width is four, four columns are allocated and the character stored in c is displayed left justified in the

    specified width because of the presence of symbol before the width specifier as follows:

    Formatting of Strings:The format specification for outputting strings is similar to that of real numbers. It is of the form

    %w.ps

    Where w specifies the field width for display and p instruct that only the first p characters of the string are to be

    displayed. The displayed is right-justified.

    The following example shows the effect of variety of specifications in printing a string NEW DELHI 110001,

    containing 16 characters (including blanks).

    Specification Output

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

    %s N E W D E L H I 1 1 0 0 0 1

    %20s N E W D E L H I 1 1 0 0 0 1

    %20.10s N E W D E L H I

    %.5s N E W D

    %-20.10s N E W D E L H I

    %5s N E W D E L H I 1 1 0 0 0 1

    Tips & Tricks:1. scanfreturns the number of input fields successfully scanned, converted, and stored. The return value does not

    include scanned fields that were not stored. On error: if no fields were stored, scanfreturns 0. if scanfattemptsto read at end-of-file or at end-of-string, it returns EOF.

    2. On success, printfreturns the number of bytes output. On error, printfreturns EOF.3. The conversion specifier p displays an address in an implementation-defined manner (on many systems,

    hexadecimal notation is used rather than decimal notation).

    4. To print a literal percent character (%), use %% in the format control string in the printf.5. If the field width is larger than the object being printed, the object is right justified in the field by default.

    6. The - flag left justifies its argument in a field.

    a

    a

  • 7/26/2019 Programing in C - A Study Material

    25/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 24

    7. The + flag prints a plus sign for positive values and a minus sign for negative values. The space flag prints aspace preceding a positive value not displayed with the + flag.

    8. The # flag prefixes 0 to octal values and 0x or 0X to hexadecimal values, and forces the decimal point to beprinted for floating-point values printed with e, E, f, g or G (normally the decimal point is displayed only if the

    value contains a fractional part).

    9. The 0 flag prints leading zeros for a value that does not occupy its entire field width.

    10.Precision used with conversion specifiers indicates the number of characters to be printed.

    11.scanf provides the assignment suppression character *. The assignment suppression character enables scanf to

    read any type of data from the input and discard it without assigning it to a variable.Ex:

    main()

    {

    int day1,month1,year1,da2,month2,year2;

    printf(Enter a date in the form mm-dd-yyyy:);

    scanf(%d%*c%d%*c%d,&month1,&day1,&year1);

    printf(month=%d\tday=%d\tyear=%d\n,month1,day1,year1);

    printf(Enter a date in the form mm/dd/yyyy:);

    scanf(%d%*c%d%*c%d,&month2,&day2,&year2);

    printf(month=%d\tday=%d\tyear=%d\n,month2,day2,year2);

    }

    Output:

    Enter a date in the form mm-dd-yyyy: 10-18-2011

    month=10 day=18 year=2011

    Enter a date in the form mm/dd/yyyy: 10/18/2011

    month=10 day=18 year=2011

    12.A sequence of characters can be input using a scan set. A scan set is a set of characters enclosedin square brackets, [ ], and preceded by a percent sign in the format control string.

    13.A scan set in a scanf scans the characters in the input, looking only for those characters thatmatch characters contained in the scan set. When a character is matched, it is stored in a

    character array. The scan set stops inputting characters when a character not contained in thescan set is encountered.

    14.To create an inverted scan set, place a caret (^) in the square brackets before the scan characters.This causes characters input with scanf and not appearing in the scan set to be stored until a

    character contained in the inverted scan set is encountered.15.Address values are input with scanf with the conversion specifier p.16.Conversion specifier n stores the number of characters input previously in the current scanf. The

    corresponding argument is a pointer to int.

    17.The conversion specifier %% with scanf matches a single % character in the input.

    18.A field width is used in scanf to read a specific number of characters from the input stream.

    19.Precision used with integer conversion specifiers indicates the minimum number of digits printed. If the valuecontains fewer digits than the precision specified, zeros are prefixed to the printed value until the number of

    digits is equivalent to the precision.

    20.Precision used with floating-point conversion specifiers e, E and f indicates the number of digits that appear

    after the decimal point. Precision used with floating-point conversion specifiers g and G indicates the number

    of significant digits to appear.

    21.Precision used with conversion specifier s indicates the number of characters to be printed.

    22.The field width and the precision can be combined by placing the field width, followed by a decimal point,followed by the precision between the percent sign and the conversion specifier.

    23.Its possible to specify the field width and the precision through integer expression in the argument list

    following the format control string. To use this feature, insert and asterisk (*) in place of the field width ofprecision. The matching argument in the argument list is evaluated and used in place of asterisk. The value of

    argument can be negative for the field width but must be positive for the precision.

  • 7/26/2019 Programing in C - A Study Material

    26/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 25

    CHAPTER-4 (CONTROL STRUCTURES)

    Decision Making Statements:

    ifelse construct:

    Simple if statement:

    The if statement is used to conditionally execute a block of code based on whether a test condition is

    true. If the condition is true then the block is executed, otherwise its skipped.

    Use of if statement:

    1. Checking range (e.g. age between 15 and 25)

    2. Checking yes/no or true/false problem (e.g. choice is no)

    Syntax:

    if ()

    {

    Statements;

    }

    E.g.:

    if(salary >= 5000)

    {

    bonus= (10*salary/100);

    }

    if else statement:The ifelse statement provides a way to execute one block of code if a condition is true and another block

    of code if its false.

    Syntax:

    if ()

    {

    Statements 1;

    }

    else

    {

    Statements 2;

    }

    E.g.:if(salary < 5000)

    {

    bonus=0;

    }

    else

    {

    bonus= (10*salary/100);

    }

    Conditional operator as replacement of if else:The conditional operator ? :sometimes replaces the ifelsestatement

    E.g.:

  • 7/26/2019 Programing in C - A Study Material

    27/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 26

    The above example can be replaced by:

    salary < 5000 ? bonus=0 : bonus = (10*salary/1000);

    Hanging statement in ifelse:The scope delimiter ({ }) of an ifstatement can be removed if the number of statements in the ifpart is

    one. If more than one statements written in the ifpart without scope delimiter, the very first statement

    will be part of the ifstatement, but others will not belong to the ifstatement and are called as hanging

    statement which is not allowed in c and causes

    Error: misplaced else.E.g.:

    1. if(a>b)

    a=0;

    else

    a=100;

    program is valid.

    2. if(a>b)

    a=0;

    b=1;

    else

    a=100;

    Error: misplaced else.

    Nested ifstatement:When one conditional statement will be executed under another conditional statement, in other words

    one ifconstruct within another ifconstruct, then we need a nested ifstatement.

    Syntax:

    if (){

    if ()

    {

    if ()

    {

    Statements;

    }

    }

    }

    E.g.:

    if(a==1)

    {

    if(b==2)

    {

    printf(hello);

    }

    }else-ifladder statement:When therell be more than two statements and only one has to be executed in accordance with a

    condition, else-if ladder is used.

  • 7/26/2019 Programing in C - A Study Material

    28/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 27

    Syntax:

    if ()

    {

    Statement 1;

    }

    else if (expression 2)

    {

    Statement 2;

    }

    else if (expression 2)

    {

    Statement 2;

    }

    :

    :

    else if (expression n)

    {

    Statement n;

    }

    else

    {

    Statements;

    }E.g.:

    If (a==1)

    printf(hello);

    else if (a==2)

    printf(hi);

    else if (a==3)

    printf(how r u);

    else

    printf(welcome);

    Tips and Tricks:

    1. If the expression is evaluated as true, its replaced by 1 and the code block will be executed.

    Otherwise its replaced by 0 and the code block will be skipped.

    2. For multiple statements are given in the ifexpression, the order of the evaluation is from left to right.

    The statements are separated by commas and hence the last evaluated expression will be treated as

    the if condition expression.

    3. Nested if can be replaced with logical && operator. e.g.

    if (a==1)

    If (b==2)

  • 7/26/2019 Programing in C - A Study Material

    29/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 28

    If (c==3)

    printf (great);

    this can also be written as

    if (a==1 && b==2 && c==3)

    printf (great);

    4. Hanging if is not allowed in C.

    switch case construct:

    When weve one value or expression that has to be exactly matched with a list of pre-defined values or

    options, the switchcase is used. Four keywords are used in switch control statement.

    switch - Its the control statement that allows us to make a decision from the no. of choices.

    case - This is the option to be selected or matched with the switchexpression value.

    default - The defaultcase is executed when none of the cases match with the value in switch.

    break -Its optional in switch case statement, but prevents unnecessary flowing of control to the

    statements subsequent to the case where a match has been found.

    Syntax:

    switch ( expression ){

    case :

    program statement;

    program statement;

    . . . . . .

    Break;

    case :

    program statement;

    program statement;

    . . . . . .

    Break;

    . . . . . .

    Default:

    program statement;

    program statement;

    }

    Tips and Tricks:

    1. The argument to a switch statement must be a byte, char, short or int.

    2. If the casematches with an expression, which is evaluated in the switch statement, then execution

    starts from that case.

    3. default case does not need a break. It also has no label. If any label is given to it, itll show an

    Error: a) Illegal use of default.

    b) expression syntax.

    4. Cases can occur in any order. E.g.

    switch (k)

    {

    default:

  • 7/26/2019 Programing in C - A Study Material

    30/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 29

    printf(default);

    case 25:

    printf(case 25);

    case 10:

    printf(case 10);

    }

    5. The continuekeyword cant be used in place of breakin switch statement. Itll generate an error.

    6. Case labels can never be identical. A duplicate case is not allowed.

    7. defaultcase is optional. If eliminated, therell be no error.

    8. The case expression can be integral constant or character constant etc. but can never be a variable.

    9. If 0 is given as an argument, switch evaluates it as an expression instead of false.

    10.switchstatement does not need braces if it has only one caseto execute.

    11.There must be a space between the case keyword and the option value. If the space is omitted, itll

    not show any error but will be considered as a goto label.

    12.Switch statements can be nested.

    13.No braces are required for the case block. But if given, itll not show any error.14.If theres no casethen therell be no error at all. E.g.

    switch (4)

    {

    }

    Looping Construct:

    Iteration (repeating a process) is achieved by loop control instructions in C. Looping means repeating an

    instruction set till a condition satisfies. There are 3 types of loop in C:for, while, do while.

    Every loop contains 3S:

    Start value (initialization)

    Stop value (condition)

    Step value (increment/ decrement)

    for loop:

    Its used to loop a portion of program for finite number of times. All parts of it are optional and hence

    cause an infinite loop.

    Syntax:

    for (Expressionopt; Expressionopt; Expressionopt){

    ;

    }

    Use offor loops:

    Infinite number of times. E.g. for ( ;;);

    Finite number of times. E.g. for (i=1;i

  • 7/26/2019 Programing in C - A Study Material

    31/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 30

    At least once. E.g.

    int i = 100;

    for ( ; ; )

    {

    printf (hello);

    if (i>=5)

    break;

    i++;

    }

    Unpredictable number of times/ odd loop. E.g.

    int i;

    for ( ; i

  • 7/26/2019 Programing in C - A Study Material

    32/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 31

    {

    printf (hello:); //unpredictable times as i is not initialized/ unknown

    i++;

    }

    do -while loop:

    Its used to loop a portion of program at least once as the condition checking is being done at the end of

    the loop.Syntax:

    do

    {

    ;

    } while (Expression);

    Use of dowhile loops:

    Infinite number of times. E.g.

    do

    printf (hello);

    while ( 1 );

    Finite number of times. E.g.

    int i=1;

    do

    {

    printf (hello\n);

    i++;

    }while ( i

  • 7/26/2019 Programing in C - A Study Material

    33/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 32

    Jumping Statements:

    To transfer the control from one portion of a program to another portion, jumping statements are allowed.

    Three types of jumping keywords are used: break, continueand goto.

    break:

    Its used in loops and switchcase to transfer the control to outside the block. In loops its usually

    associated with if statement. E.g.

    int i = 100;

    while ( 1 )

    {

    printf (hello);

    if (i>=5)

    break;

    i++;

    }

    continue:

    Its used in loops to transfer the control to the beginning of the loop by skipping the subsequent sequences

    in the loop allowing the control to jump to the next iteration skipping the present. E.g.int i;

    for (i=1; i=5)

    {

    printf (hi);

    continue;

    }

    printf (hello);i++;

    }

    goto:

    Its an unconditional branching statement. It causes the control to be transferred from one part to another

    part of the function.

    Syntax:

    goto label; //where label is a valid c identifier and marks a place where

    //the control has to be transferred in a function.

    The statement to which the control has to be transferred is preceded by a label and a colon.

    E.g.

    Forward jumping:

    goto abc;

    s1;

    s2;

    abc: s3;

    s4;

    Forward jumping:

    abc: s1;

    s2;

    goto abc;

  • 7/26/2019 Programing in C - A Study Material

    34/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 33

    Its mostly avoided in C programming as it makes the program difficult to understand. Its

    generally used in nested loops to transfer the control to the end of all loops from the innermost loop.

    Tips and Tricks:

    1. Zero (0) is treated as FALSE in loops.

    2. If 0 is used in conditions, itll be false and program will not execute (in whileloop and inforloop

    {except turbo c}) or the program will execute at least once (in dowhileloop and inforloop {in turbo

    c only}).

    3. Infor loop, all parts are optional and hence can be dropped but in whileand dowhile all parts are

    compulsory and if omitted itll show error.

    4. If a loop is terminated with a semicolon (;), aforloop is finite, a whileloop is infinite, but a dowhile

    loop is work normally as semicolon is a must to a dowhileloop but after whilekeyword only. If after

    do ; will be given, itll show a parse error.

    int i;

    for (i=0;i

  • 7/26/2019 Programing in C - A Study Material

    35/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 34

    17.break in loop transfers the control outside of the loop.

    18.continue transfers the control to the beginning of loop.

    19.Every loop has a start value; step value and stop value.

    20.Loop is faster than function recursion.

    21.Only one statement falls under the default scope of the control structure.

  • 7/26/2019 Programing in C - A Study Material

    36/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 35

    MODULE II

    CHAPTER 5 (FUNCTIONS)

    Functions are the small and self-contained components of a program, which have some unique identifiable purpose.

    Every C function composed of same things: name, return type, arguments and a body. These are used to break down

    large programs into smaller modules. These modularize the program and this is called as the modular property of

    function which makes debugging easier i.e. improves the programs readability, enhances the programming

    structure and helps the programmer to detect the errors faster and more easily.

    Use of Functions: Code Reusability: saves repetition of common routines. Functions once written can be reused in different

    programs without having to rewrite them again.

    Program portability: This is a benefit arising from re-usability of code. Because programs will become smaller

    in size and subsequent packaging or programs will become easier and faster.

    Maintaining large programs become easier because of the following reasons:

    Different modules work independently of each other.

    We just need to understand and monitor what the large pieces or modules or functions as a whole

    will do, individual statements or the program are not important.

    Unnecessary details are hidden.

    Changing one modules or functions code should have limited effects on other parts.

    Modularizing the program: easier to debug the program. Allows function recursion or recursive execution of a module or functionality.

    TYPES OF FUNCTIONS:

    1. Standard Library Functions :These are technically not a part of the C language. But theres a wide prepackaged

    functions available in the standard library to reduce program development time and make programs more

    portable. To use a standard library function we have to include its header file, which contains the header

    information such as prototype, macros, typedef names, global variables. E.g. scanf ( ), printf ( ), strlen ( ), etc.

    2. User Defined Functions :These are defined by the programmer to perform specific tasks. E.g.

    main ( )

    {

    int a, b;

    printf (sum = %d,add(a,b)); /*function call*/}

    int add (int x, int y) /*function definition*/

    {

    return x+y;

    }

    Here add ( )is a user defined function, which is used to add two numbers.

    PARTS OF FUNCTIONS:

    1. Return Type: It tells the compiler which type of data will be returned from the called function. The default return

    type of a function is an integer.

    2. Function Name:Its a constant pointer that gives the address of the function, where its defined.

    3. Function Argument:These specify to the compiler which type of data transmitted to the called function from

    the calling function.

    Actual Argument: The arguments passed from the calling function are called actual arguments. In

    the above example a, b are the actual arguments.

    Formal Arguments: The arguments that receive the values passed from the calling function to the

    called function are called formal arguments. In the above example x, y are the formal arguments. USING A FUNCTION:

    Functions are classified as one of the derived data type in C. Therefore we can define functions and use them like

    any other variable in C.

    Both function name and variable names are considered identifiers.

    int add (int, int)

    Function

    ArgumentFunction

    NameReturn

    Type

  • 7/26/2019 Programing in C - A Study Material

    37/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 36

    Like variables, functions have types (such as int) associated with them.

    Like variables, function names and their types must be declared and defined before use.

    1. Function Prototype Declaration: Like variables, all functions in a c program must be declared, before they are

    invoked. A function declaration, also known as function prototype.

    Syntax: ();

    E.g.

    int add ( int, float);

    2. Function Definition: Function need to be defined. Function definition contains a function declarator followed by

    function body.

    Syntax:

    () //declarator

    { //function body start

    statements;

    return statement;

    } //function body end

    E.g.

    int add ( int x, float y)

    {

    int z;

    z = x + y;

    return z;

    }

    3. Function Call: A function can be called by the function name followed by a list of actual argument. A function

    is a latent body. It gets activated only when a call to function is invoked.

    Syntax:

    ();

    E.g.

    add ( x, y ); or

    add ( 2, 4); or

    add ( a, 7) ;

    Key Notes:

    i. Function declaration tells the compiler about the availability of the function and helps the compiler to checkthe return and argument type of the function.

    ii. The declarator of function definition must be similar to its prototype declaration.

    iii. The type of parameters in declaration must match the type of parameters in the definition both in number

    and order.

    iv. The function can be defined anywhere. If the function is defined before its caller, then its prototype

    declaration is optional.

    v. When a function reaches its return statement, the control is transferred back to the calling program. In

    absence of a return statement, the closing braces act as a void return.

    vi. A local variable is a variable that is defined inside a function and used without having any role in the

    communication between functions.

    vii. When the compiler encounters a function call, the control is transferred to the function definition with samefunction name. This function is then executed and a value is returned to the calling function when a return

    statement is encountered. And then the program continues its execution.

    viii. A function can be called as much number of times.

    ix. At each call, the control passes to the subroutine at a specified address in the memory. The CPU stores the

    memory address of instruction following the function calls into the stack and also pushes the values of actual

    arguments in the stack area. The compiler then pops the values to formal arguments and runs the function,

    stores the return value in a memory location or register.

    FUNCTION CONVENTIONS:

    1. pascal: Declare a variable or a function usingpascalstyle naming convention. When its applied to a function

    header, the first parameter is pushed to the stack first.E.g.

    void main(){void pascal show();

    int x=0;

    show(x++,x++);

    void pascal show(int x, int y)

  • 7/26/2019 Programing in C - A Study Material

    38/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 37

    {

    printf (%d %d, x, y);

    }

    output: 0 1

    2. cdecl: Here the last parameter is pushed to the stack first, and the calling function cleans up the stack.E.g.

    void main(){

    void cdecl show();

    int x=0;

    show(x++,x++);

    void cdecl show(int x, int y)

    {

    printf (%d %d, x, y);

    }

    output: 1 0

    FUNCTION COMMUNICATION:

    1. Forward communication: When data is transferred from calling function to called function, its called forward

    communication and possible only due to function parameters.

    2. Backward communication: When data is returned from called function to calling function, its called backward

    communication and possible only due to the function return statement.

    CATEGORY OF FUNCTION:

    1. Return type having argument: Hereboth forward and backward communication occurs. E.g.

    int add (int x, int y)

    {

    return (x + y);

    }

    2. Return type having void as argument:Here onlybackward communication occurs. E.g.

    int add (void)

    {

    int x, y;

    scanf (%d %d, x, y);

    return (x + y);

    }3. No return type having argument:Hereonly forward communication occurs. E.g.

    void add (int x, int y)

    {

    printf (%d, x + y);

    }

    4. No return type having no argument :Hereneither forward nor backward communication occurs. E.g.

    void add (void)

    {

    int x, y;

    scanf (%d %d, x, y);

    printf (%d, x + y);}

    NOTE:A function can return multiple values, but the arguments must be of reference type i.e. pointers to the

    variable.

    FUNCTION CALL:

    1. STD CALL: When function call and the function definition are both in the same program, then the function call is

    called STD call.

    2. ISD CALL: When function definition is present in another file and that file is included in source file, such a

    function call is called STD call.

    3. Local CALL: When the same function is called by itself, its called local call or technically function recursion.

    FUNCTION STANDARDS:

    1. ANSI Standard:void add (int, int);

    void main ( )

    {

    add (5, 6);

  • 7/26/2019 Programing in C - A Study Material

    39/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 38

    }

    void add (int x, int y) //ANSI standard

    {

    printf (%d, x + y);

    }

    2. K & R Standard:

    void add (int, int)

    void main ( )

    {

    add (5, 6);

    }

    void add (x, y)

    int x, y; //K & R standard

    {

    printf (%d, x + y);

    }

    PARAMETER PASSING:

    The technique used to pass data from one function to another is known as parameter passing. Parameter passing

    can be done in two ways:

    1. Call by Value: In this type, value of actual argument is passed to the formal argument and operation is done on

    the formal arguments. Any change in the formal argument does not affect the actual argument because formal

    arguments are only the photocopies of actual arguments. Changes made in the formal arguments are local to the

    block of called function. Once control returns back to the calling function the changes made vanish.

    Point to Note: The addresses of actual and formal arguments are different. Thus changes made with the

    variables are temporary.

    Example:

    void change ( int, int);

    void main ( )

    {

    change ( x, y) ;

    }

    void change ( int a, int b){

    //statements

    }

    2. Call by Address:

    In this type, instead of passing values, addresses are passed. Function operates on addresses rather than values.

    Here the formal arguments are pointers to the actual arguments. Hence changes made in the arguments are

    permanent.

    The formal arguments receive the addresses of actual arguments. The function operates of actual arguments trough

    pointers.

    Point to Note: The addresses of actual arguments and formal arguments are same. Hence, the changes made in thevalues are permanent.

    Example:

    void change ( int ,int ) ;

    void main ( )

    {

    change ( &x , &y ) ;

    }

    void change ( int *a , int *b )

    { //statements

    }

  • 7/26/2019 Programing in C - A Study Material

    40/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 39

    DYNAMIC FUNCTIONS (FUNCTIONS WITH VARIABLE NUMBER OF ARGUMENTS)

    Some functions have a variable number of arguments and data types which can not be known at compile time, are

    called as dynamic functions. The printf and scanf functions are typical examples. The ANSI standard proposes new

    symbol called the ellipsis to handle such functions. The ellipsis consists of three periods () and used as shown

    bellow:

    int printf(const char *format, );

    Both the function declaration and definition should use ellipsis to indicate that the arguments are arbitrary both in

    number and type. To work with dynamic functions the following macros and typedef names play a vital role.

    va_list //typedef name

    va_args //macro

    va_start //macro

    va_end //macro

    These are defined in the header file stdarg.h for ANSI and vargs.h for UNIX-V.

    typedef void * va_list;

    va_list p;

    Here p is a variable of type va_list (generic pointer).

    #define va_start(ap, parmN) ((void) ((ap) = (va_list)((char *) (&parmN) +__size(parmN))))

    Load the argument list into memory and set the pointer to point to the base address of a variable number of

    argument list.

    #define va_arg (ap, type) (*(type *) ((( * (char **) & (ap)) += __size (type)) (__size(type))))

    Reads the argument from the argument list and the pointer is shifted to the next argument.

    #define va_end(ap) ((void) 0)

    Unload the arguments list from memory.

    Example:

    #include stdarg.h

    int sum(char *, );

    main()

    {

    int x;

    x = sum(total:, 2,5,3,5,7,0);

    printf(%d,x);

    }

    int sum(char *r, )

    {

    int k, s=0;

    va_list p;

    va_start(p,r);

    while (( k=va_arg(p, int)) !=0)

    s = s+k;

    va_end(p);

    return s;

    }

    Output: 22

    Working with variable numbers of argument without Macros:

    Example:

    int sum();

    main()

    {

    int x;

    x = sum(2,5,3,5,7,0);

    printf(%d,x);

    }

    int sum()

    {

    int s=0;

    void *p;

    p = ;

  • 7/26/2019 Programing in C - A Study Material

    41/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 40

    while( *(int *) p !=0)

    s = s+*((int *)p)++;

    return s;

    }

    Output: 22

    RECURSIONNesting of the function calls can be to any level depending on the requirement. The phenomena of a function callingitself directly or indirectly is called recursion (direct recursion or indirect recursion). The function involved in the

    process is referred to as a recursive function.

    Example: WAP to find factorial of a number using recursive function.

    #include

    int fact ( int );

    void main( )

    {

    int number,f;

    printf ( enter a number \n) ;

    scanf ( %d,&number) ;

    f = fact ( number ) ;

    printf ( fact = %d \n,f) ;

    }

    int fact ( int number)

    {

    int f;

    if ( number == 0)

    return 1;

    else

    f = number * fact (number -1); // fact ( ) call itself

    return f;

    }

    OUTPUT:

    Enter a number

    4

    factorial of 4 = 24.

    Properties of function recursion:

    i. Alternative to looping constructs.

    ii. Nature of function recursion is always an infinite loop or stack overflow.

    iii. Expensive in both processor time and memory space as compare to loop.

    iv. Helps in writing cryptic codes.

    v. Used for some specific purpose, like in-order, pre-order and post-order traversal of a tree, tower of Hanoi,

    Quick sort, etc.

  • 7/26/2019 Programing in C - A Study Material

    42/90

    PROGRAMING IN C - A STUDY MATERIAL

    VIGNAN INSTITUTE OF TECHNOLOGY AND MANAGEMENT 41

    CHAPTER 6 (STORAGE CLASSES)

    Depending on where a variable is allocated required storage (CPU register or RAM), the area of existence in a

    program (scope) and its longevity (lifetime), variables are classified into what are called storage classes. They help to

    determine four properties, namely lifetime, storage, visibility (scope) and default initial value. Following are four

    storage classes:

    1. automatic 2.static 3.register 4.extern

    Automatic Storage Class:

    The variable declares with in a function are by default of an automatic storage class. The keyword auto can also be

    used to explicitly specify it.void fun()

    {

    int i; // storage class of variable i would be auto

    auto int j; // storage class of variable j explicitly auto

    }

    Automatic variables are characterized by the following properties:

    i) Automatic variables are stored in memory.

    ii) The default initial value of automatic variable is garbage.

    iii) They are visible within the block in which they are defined.

    iv) Their lifetime is the duration of the function or block only.

    v) Every local variable is by default auto variables.vi) They can not be declared outside of functions.

    Static storage class:

    Variable can be made to belong to static storage class by explicitly using the keyword static while declaring them.

    The variable of static storage class may be declared either within or outside the functions.

    void fun()

    {