Ecs C_prog Material

Embed Size (px)

Citation preview

  • 8/9/2019 Ecs C_prog Material

    1/126

    PROGRAMMING IN C

    Staff Handled By : D.Mythili

  • 8/9/2019 Ecs C_prog Material

    2/126

    PROGRAMMING IN C

    SYLLABUS

    Unit-I

    Structure of a C program C character set Delimiters Keywords identifiers Constants variables rules for definingVariables data types Declaring and initializing variables typeConversion. Operators and expressions

    Unit-II

    Formatted and Unformatted Input and output functions Decision Statements loop Control Statements.

    Unit-III

    Arrays : Array initialization definition characteristics- one dimensional array, predefined streams- Two- dimensional array Three or multi dimensional arrays. Strings and Standard functions:-Declaration and initialization of string- Display of string with differentformats String standard functions Application of strings. Pointers:Features, Pointer declaration, Arithmetic Operations with pointers-Pointers and Array Pointers and Two-dimensional array Array of

    pointers Pointers to pointers Pointer and Strings Void pointers.Functions: Definition, Declaration, The return statement, Types offunctions, Call by value and Call by reference, Functions returningmore values, Functions as an argument. Functions with Arrays andpointers Recursion Preprocessor Directives.

    Unit-IV

    Structure and Union: Features of structure, Declaration andinitialization of structure, Structure within structure, Array of structure,Pointer to structure, Bit fields, Union.

    Unit-V

    Files: Streams and file types, Steps for file operation, File I/O,Structures read and write, other file functions, Command linearguments, I/O redirection

  • 8/9/2019 Ecs C_prog Material

    3/126

    DEPARTMENT OF ELECTRONICS AND COMMUNICATIONSYSTEM

    STUDY MATERIAL

    COURSE : II YEAR A, B.Sc ECSSEMESTER : IIIUNIT : ISUBJECT NAME : PROGRAMMING IN CLECTURER NAME : D.MYTHILINUMBER OF PAGES : 18DATE OF ISSUE :

    Unit-IIntroduction to C programming - Structure of a C program C characterset Delimiters Keywords identifiers Constants variables rules

    for defining Variables data types Declaring and initializing variables type Conversion. Operators and expressions

    Introduction to C programmingC was an offspring of Basic Combined Programming

    Language(bcpl) called B, developed in the 1960s at Cambridgeuniversity. B language was modified by Dennis Ritchie and wasimplemented at Bell Laboratories in 1972.The new language wasnamed as C. since it was developed along with UNIX operatingsystem, it is strongly associated with UNIX. It can run undervarious operating systems including MSDOS.

    Importance of C:1. It is robust language.2. Rich set of built-in functions and operators are available.3. Easy to create complex programs.4. Suitable to write both application software as well as systemsoftware.5. It is highly portable. Because C programs written for onecomputer

    can be run on another with little or no modification.6. It is well suited for structured programming. So that it is easy to

    debug, test and maintain a module.7. It can extend itself.

    Basic structure of C programming:

    Documentation sectionlink section

  • 8/9/2019 Ecs C_prog Material

    4/126

    Definition sectionGlobal declaration sectionMain( ) function section{

    declaration part

    executable part

    }

    Subprogram sectionfunction 1function 2function 3

    .

    .function n

    a) Include header file section:A C program depends upon some header files for function

    definition that are used in the program. Each header file has .hextension. Eg. #include b) Global declaration:

    This section declares some variables that are used in morethan one function. These variables are known as global variables. Thissection must be declared outside of all the functions.

    c) Function main ( ): Every program in C must contain main ( ) function. Emptyparenthesis after main is necessary. The function main ( ) is a startingpoint of every C program. The execution of the program always beginswith the function main ( ).d) Declaration Part:

    It declares the entire variables that are used in theexecutable part. Initializations of variables are also done in thissection. Initialization means providing initial value to the variables.e) Executable Part:

    This part contains the statement following the declarations

    of the variables. This part contains a set of statements or a singlestatement. These statements are enclosed between braces.f) User-defined function:

    The functions defined by the user are called user-definedfunctions. These functions are generally defined after the main ( )function. They can be also be defined before main ( ) function. Thisportion is not compulsory.g) Comments:

  • 8/9/2019 Ecs C_prog Material

    5/126

    It is not compulsory in a program. However to understandthe flow of a program, the programmer can include comments in theprogram. Comments can be inserted by the programmer. These areuseful for documentation. The clarity of the program can be followed ifit is properly documented.

    Example/ * This is a single comment * // * This is an example of / * nested comments * / * // * This is an example ofcomments with multiple lines * / / * It can be nested * /C Character Set The characters are used to form words, numbers andexpressions depending upon the computer on which the program runs.The characters in C are classified into the following characteristics.1. Letters 2. Digits 3. White Spaces 4. Special characters.

    Character Set

    1) Letters 2) Digits 3) WhiteSpaces

    Capital A toZ

    All decimal digits 0 to 9 Blank Space

    Small a to z Horizontal TabVertical TabNew LineForm Feed

    4) Special Characters:

    , Comma & Ampersand. Period or dot ^ Caret; Semi colon * Asterisk: Colon - Minus` Apostrophe + Plus Quotation

    mark< Less than

    ! Exclamationmark

    > Greater than

    Vertical bar ()

    Parenthesis left /right

    / Slash []

    Bracket left /right

    \ Back slash {}

    Braces left / right

    ~ Tilde % Percent_ Under score # Number sign or

    hash$ Dollar = Equal to

  • 8/9/2019 Ecs C_prog Material

    6/126

    ? Questionmark

    @ At the rate

    Delimiters:Language pattern of C uses special kinds of symbols, which are

    called as delimiters. They are given as under.

    Delimiters Use: Colon Useful for label; Semi Colon Terminates statement( )Parenthesis

    Used in expression andfunction

    [ ] Squarebracket

    Used for arraydeclaration

    { } Curlybrace

    Scope of statement

    # Hash Preprocessor directive, Comma Variable separator

    The C keywords:The C keywords are reserved words by a compiler. They are

    assigned a fixed meaning. The keywords cannot be used as variablenames because they have been assigned fixed jobs. However, fewcompilers allow to construct a variable name, which exactly coincideswith the keywords. For utilizing the keywords in a program no headerfile is to be included. The description of the keywords is given below.

    auto double

    int struct

    break else long switchcase enu

    m

    regist

    er

    typede

    fchar exter

    nreturn

    union

    const float short unsigned

    continue

    for signed

    void

    default

    goto sizeof volatile

    do if static whileAdditional keywords for

    Borland Casm if static while

    Identifiers:Identifiers are names of variables, functions and arrays. They

    are user-defined names, consisting of sequence of letters and digits,with the letter as the first character. Lower case letters are preferred.However, the upper case letters also permitted. The underscore ( _ )

  • 8/9/2019 Ecs C_prog Material

    7/126

    symbol can be used as an identifier.Example: 1. #define N 10

    2. #define a 15Here N and a are user-defined identifiers.

    Constants: The constants in C are applicable to the values that do notchange during the execution of a program. There are several types ofconstants in C. They are classified as follows.

    A. Numerical constants:1) Integer constants:It refers to a sequence of digits from 0 to 9 without decimal

    points or fractional part or other symbols. It requires minimum twobytes and maximum 4 bytes. Integer constants can either bepositive, negative or maybe zero. The number without a sign isassumed as positive.Example: 10, 20, +30, -152) Real constants:The numbers with fractional part is called real or floating-pointconstants. Many parameters or quantities are defined not only inintegers but also in real numbers.Example: 1) 54.98

    2) 25.75

    B. Character constants:1. Single character constants:

    A character constant is a single character. They are alsorepresented with a single digit or a single special symbol or whitespace enclosed within a pair of single quote marks.Examples: 1) a

    2) #3) 2

  • 8/9/2019 Ecs C_prog Material

    8/126

    4) 2. String Constants:

    They are a sequence of characters enclosed within a doublequote marks. The string may be a combination of all kinds ofsymbols.

    Example: Hello, India, 444, a.

    Variables:A variable is a data name that may be used to hold a data

    value. A variable may take different values at different timesduring the program execution.

    Rules for forming a variable:1. The starting character should be a letter. The first character may be

    followed by a sequence of letters or digits.2. The maximum number of characters in a variable may be 8

    characters. The number of characters differs from compiler tocompiler.3. Upper and lower case are significant. Example: TOTAL is notsame as total or Total.4. The variable should not be a keyword.5. White space is not allowed.6. Special characters except _(underscore) symbol are notallowed.

    C Data Types:Data is a collection of characters, digits, symbols etc., the

    data are used to represent information. The data are classified invarious types. C data types are classified into the followingcategories.a. Basic data typeb. Derived data typec. User-defined data typed. Void data type

  • 8/9/2019 Ecs C_prog Material

    9/126

    Basic Data types:The basic data types supported by C are described with their size

    in bytes and ranges.Data Type Size in

    BytesRange

    char 1 -128 to 127unsignedchar

    1 0 to 255

    signed char 1 -128 to 127Int 2 - 32768 to 32767unsigned int 2 0 to 65535signed int 2 - 32768 to 32767

    short int 2 - 32768 to 32767unsignedshort int

    2 0 to 65535

    signed shortint

    2 - 32768 to 32767

    long int 4 - 2147483648 to2147483647

    signed longint

    4 - 2147483648 to2147483647

    unsignedlong int

    4 0 to 4294967295

    float 4 3.4E- 38 to 3.4E+38double 8 1.7E 308 to 1.7E +

    308long double 10 3.4E 4932 to 1.1E

    +4932enum 2 - 32768 to 32767

    Derived Data type:

  • 8/9/2019 Ecs C_prog Material

    10/126

    The derived data types are of the following types:1. Pointers2. Functions3. Arrays1. Pointers:

    A pointer is a memory variable that stores a memory address.Pointers can have any name that is legal for other variables and itis declared in the same fashion like other variables but it is alwaysdenoted by * operator.int *x;float *f;char *y;

    In the first statement x is an integer pointer that tells tothe compiler that it holds the address of any integer variable. Inthe same way f is a float pointer that stores the address of anyfloat variable and y is a character pointer that stores the address

    of any character variable.2. Functions:A function is a self-contained block or a sub-program of one ormore statements that perform a special task when called. In figfunA( ) and funB( ) are two user-defined functions. These areinvoked from the body of main. After execution of funA( ) andfunB( ) the program control returns back to the calling functionmain( ).

    3. ArraysAn array is a collection of elements of similar data types in

    which each element is located in separate memory location.Eg. int b[4];Variables:

    A variable is a data name that may be used to hold a datavalue. A variable may take different values at different timesduring the program execution.Rules for forming a variable:

    1.The starting character should be a letter.

  • 8/9/2019 Ecs C_prog Material

    11/126

    2.The maximum number of characters may be 8 characters. itdiffers

    3.Upper and lower case are significant. Example: TOTAL is notsame as total or Total.

    4.The variable should not be a keyword.

    5.White space is not allowed.6.Special characters except _(underscore) symbol is notallowed.

    Valid examples:1. john2. value3. tot_amt4. a1

    Invalid examples: Reason

    1. 1868 1) The first letter should be a letter2. (area) 2) Special characters notallowed3. 27th 3) Number should not be afirst character4. % 4) Special characters not allowedData types:1. Primary data types.2. User- defined data type3. Derived data type

    4. empty data set

    Primary data types:1. Integral type:

    a. Integer sizei. signed int 16 bitsii.short signed int 8 bitsiii.long signed int 32 bitsiv.unsigned int 16 bitsv.unsigned short int 8 bitsvi.unsigned long int 32 bits

    b. Characteri. signed char 8 bitsii. unsigned char 8 bits

    2. Floating-point typei. float 32 bitsii. double 64 bits

  • 8/9/2019 Ecs C_prog Material

    12/126

    iii. long double 80 bits

    Declaration of variables:Purpose:1. It tells the compiler what the variable name is.

    2. It specifies what type of data the variable will hold.

    Syntax:

    v1,v2,v3.vn- variables

    Example:1. int count;2. int a,b;

    3. float area,volume;4. char array;5. double a1;

    data type keyword equivalent character charunsigned character unsigned charsigned character signed charsigned integer signed int to intsigned short integer signed short intsigned long integer signed ling int

    unsigned integer unsigned int or unsigned intunsigned short integer unsigned short intunsigned long integer unsigned long intfloating point floatdouble precision doubleextended double precision long double

    User defined declaration:Types:1. type definition2. enumerated data type

    Type definition:Purpose:This allows the user to define the identifier that would representan existing data type. The user-defined type is later used todeclare variables.General form:

  • 8/9/2019 Ecs C_prog Material

    13/126

    Typedef - keyword Type - exiting data typeIdentifier new name given to the data type

    Typedef cannot create a new type. Using identifier the variablescan be declared using the following syntax:

    Examples:Typedef int units;Units batch1,batch2;Units name[10],name1[20];

    Enumerated data type:

    It is defined as follows

    It is used to declare the variables that can have one of the valuesenclosed within braces(known as enumerated constants).we candeclare variables to be of this new type as below:

    The enumerated variables v1,v2,vn can have one of the

    values value1,value2,value n.Examples:

    1. enum day {monday,tuesday,sunday};enum day week_beg,week_end;we can assign values like

    2. week_beg=sunday;week_end=saturday;We can compare the values like

    3.if (week_beg == friday)week_end=thursday;

    The compiler automatically assigns integer digits beginning

    with 0 to all the enumeration constants. Thus the enumerationconstants assign value1 as 0,value2 as 1 and so on. However theautomatic assignments can be overridden by assigning valuesexplicitly to the enumeration constants.Example:

    enum day {monday=1,tuesday=5,.sunday};In the above Wednesday will take the value of 6,Thursday willtake 7 and so on.

  • 8/9/2019 Ecs C_prog Material

    14/126

    enummonth(Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec)this statement creates user defined data type. the keyword enum isfollowed by the tag name month. The enumerators are the identifiers Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec. Their values are

    constant unsigned integers and start from 0. the identifier jan refers to0, feb to 1 and so on. The identifiers are not to be enclosed with inquotation marks.Write a program to create enumerated data type for 12months. Display their values in integer constants.#include #include Void main(){enum month(Jan,Feb,Mar.Apr,May.Jun,Jul,Aug,Sep,Oct,Nov,Dec);clrscr();

    printf(\nJan=%d,Jan);printf(\nFeb=%d,Feb);printf(\nJune=%d,June);printf(\nDec=%d,Dec);}

    OUTPUT:Jan=0Feb=1June=5Dec=11

    Explanation: In the above program enumerated data type month isdeclared with 12-month names within two curly braces. The compilerassign 0 value to first identifier and 11 to last identifier. Using printf()statement the constants are displayed for different identifier. Bydefault the compiler assign value from 0 onwards. Instead of 0 theprogrammer can initialize his/her own constant to each identifier.

    Global and local variables:Global variable is visible to all functions in the file. It is necessaryto declare the variable before the main function. No need todeclare the global variables in all functions. It is also known

    external variable. Local variable is visible and meaningful onlyinside the function in which they are declared.Example:

    /*example of storage classes*/int m;main( ){

    int I;

  • 8/9/2019 Ecs C_prog Material

    15/126

    float balance;....function1( );

    }

    function1( ){int i;float sum;

    }

    Storage classes:Purpose:It provides the information about location and visibility of

    variables.

    Types meaning1. auto local variable known only to the functionwhere it is declared

    default is auto.2.static local variable which exists and retains it svalue even after

    control is transferred to the calling function.3.extern global variable known to all function sin the file4.register local variable which is stored in the register.

    Example:auto int count;register char ch;static int x;extern long total;

    Assignment statement:Purpose : values can be assigned to variables using the

    assignment operator = as follows

    Examples:

  • 8/9/2019 Ecs C_prog Material

    16/126

    It is possible to assign the values during declaration time asfollows:

    Example:

    Declaring a variable as Constant :Purpose :

    To maintain the value of variable throughout the programexecution we are declaring the variable as constant.Example:

    Reading the data from the keyboard:Another way of giving values to variables is to input data

    through keyboard using the scanf function.Syntax:

    The control string contains the format of data beingreceived. The ampersand symbol & before the variable name isan operator that specifies the variable names addressExample :

    %d- represents integer value%f- float number%c- character

    %lf - double%u - unsigned int

    Output using printf:Purpose :

    It is used to display the output as well as to create aninteractive program .Syntax:

  • 8/9/2019 Ecs C_prog Material

    17/126

    Operators :Purpose :

    It is used to tell the computer to manipulate dataand variables.Types:

    1. Arithmetic operators2. Relational operators

    3. Logical operators4. Assignment operators5. Increment and decrement operators6. Conditional operators7. Bitwise operators8. Special operators

    Arithmetic operators:

    Arithmetic operators are used to perform arithmeticoperations like addition , subtraction, multiplication and divisionand to find the remaindering division. The corresponding symbolsare +(addition or unary plus),- (subtraction or unary minus),*,/,%(modulo division).C does not have an operator exponentiation.

    Relational operators:Purpose:

    To relate any two or more quantities.

    Operator Meaning< is less than> is greater than

    > is greater than orequal to

  • 8/9/2019 Ecs C_prog Material

    18/126

    to this c hasshorthand operators.

    Syntax:

    Statement with simple Statementwith short

    Assignment operator. Handoperator.

    a=a+1 a+=1a=a-1 a-=1a=a*1 a*=1a=a/1 a/=1a=a%b a%=b

    Advantages: 1. No need to repeat the operator again in the righthand side.

    2. The statement is more concise and clear.3. The statement is more efficient.4. It is easy to read.

    Increment and Decrement operators:Purpose:

    To decrement the value of the variable by one or toincrement the value of the variable by one.

    Operators:++ - adds 1 to the operand-- - subtracts 1 unary operators

    Example:++m; (++ used as prefix operator)m++; (++ as postfix operator)If they are used independently then meaning is same.

    Consider the followingm=5;y=++m;In the above case m and y would be 6.

    m=5;y=m++;

    In the above case m would be 6 and y would be 5.Similarly for the --operator.

    Conditional operator:Purpose:

    A ternary operator pair ?: is used to construct

  • 8/9/2019 Ecs C_prog Material

    19/126

    conditional expressionsSyntax:

    Example :x=(a>b)?a:b;In the above the condition is evaluated first .if true

    then a will be assigned to x or else b will be assigned to x. Theabove syntax is equivalent to if else statement.

    Bitwise operators:Purpose:

    Manipulating the data at bit level.

    Operator Meaning

    & bitwise AND| bitwise OR^ bitwise EXCLUSIVE OR> shift right~ ones complement

    Special operators:sizeof - to determine the size of the variable,(comma) - to link the related expressions togetherexample : value=(x=10,y=17,x+y)

    . and -> - member selection operator& and * - pointer operator

    Expressions:Combination of both operand and operator.

    Types:1. Arithmetic2. Relational3. Logical

    Arithmetic expression:

    Operand combined with arithmetic operators called asarithmetic expressions

    Examples:a+bc-d

    Types:1. Integer arithmetic2. Real arithmetic

  • 8/9/2019 Ecs C_prog Material

    20/126

    3. Mixed arithmetic Integer arithmetic:

    Arithmetic operator combined with integer operands. Example:

    a + b; where a and b are of type integer.

    Real arithmetic:Arithmetic operator combined with real operands.

    Example:a + b where a and b are of type real.

    Mixed mode arithmetic:Expression consists of both integer and real operands.

    Example:a-b where a is of type integer and b is of type real.

    Evaluation of expression:Expression evaluation based on the priority of

    operators.High priority * / % left to rightLow priority + -

    Logical expression:

    Whenever the logical operators combine any two relationalexpressions then it is called logical expression.

    Example:((ad))

    Operator precedence:1. Logical NOT2. Logical AND3. Logical OR

    Type conversions in expressions:If operands are of different types then the lower type

    is automatically converted into higher type before the operationproceeds. The result is of higher type.1. All short and char to int.

    2. If one of the operand is long double then other will beconverted into long double.3. Else if one is double then other will be converted into double.4. Else if one is float then other will be float.5. Else if one is unsigned long int then other will be unsigned longint.6. If one is unsigned long int and other one is long int then

    a. Unsigned long int will be converted into long int or

  • 8/9/2019 Ecs C_prog Material

    21/126

    b. Long int will be converted into unsigned long int.

    Casting a value:If we need to force the type conversion explicitly then

    it is called as coercion.

    Example: ratio=(float) number1/number2;Where number 1 and number2 are of type integer type,

    ratio is of type float. General form of Casting:

    Suggested Questions

    3. What are unary operators?4. Give an example for short hand assignment operator.5. Where was C orginally developed and by whom?6. What is the name for data type conversion?7. Explain about mixed mode arithmetic operations8. Write short notes on logical operators.9. Explain about operators supported by C10.Explain data types supported by C11.Give the hierarchy of operator precendences covering all of the

    operators in C12.Explain arithmetic & relational operators?

    13.Explain Structure of C Program with suitable examples.14.What is variables. List out the rules to declare a variables.15.What is Identifiers.16.What is type casting.17.Write a program Which combine all the operators.

  • 8/9/2019 Ecs C_prog Material

    22/126

    STUDY MATERIAL

    COURSE : II YEAR A, B.Sc ECSSEMESTER : IIIUNIT : II

    SUBJECT NAME : PROGRAMMING IN CLECTURER NAME : D.MYTHILINUMBER OF PAGES : 7DATE OF ISSUE :

    Unit-II

    Decision Statements loop Control Statements.

    Control/Decision making statements:

    1.If statement2.Switch statement3.Conditional operator statement4.Goto statement

    If statement:Purpose:

    It is a powerful decision making statement to controlthe flow of execution. It is basically two-way decision statementand is used in conjunction with and expression. Syntax:

    It allows the system to evaluate the expression firstand then, depending on whether the value is true or false ittransfers the Control to the particular statement.

    entry

    false

    true

    Different forms of IF statement:1. Simple if statement

  • 8/9/2019 Ecs C_prog Material

    23/126

    2. If else statement3. Nested if else statement4. Else if ladder

    Simple if statement:

    Syntax:

    In the above statement if test expression is true thenstatement block

    will be executed else statement block will be skipped.

    If else statement:

    Syntax:

    Above statement if the test expression is true then true blockstatement, immediately following by the If statement areexecuted; otherwise the false block statement are executed. Ineither case either true block will be executed or false block will beexecuted but not both.

    Nesting of if else statement:Syntax:

  • 8/9/2019 Ecs C_prog Material

    24/126

    In the above statement if the condition 1 is true then thesecond if condition 2 will be tested and if it is also true then thestatement 1 will be executed. if the second condition is false thenthe statement 2 will be executed. If the first condition is false thenthe statement 3 will be executed.

    Else if ladder:Syntax:

    The condition are evaluated from the top to bottom as soon as atrue condition is found, the statement associated with it isexecuted and the control is transferred to the statement x. Whenall the n conditions become false then the final else containingthe default-statement will be executed.

    The Switch statement:Purpose:

    Using the value of any variable or expression uses it to selectone branch among several alternatives. The switch tests the value

    of given variable (or) expression against a list of case values andwhen a match is found, a block of statements associated with thatcase is executed. Syntax:

  • 8/9/2019 Ecs C_prog Material

    25/126

    In the above syntax the expression is an integer expressionor characters the value-1,value-2,. are constants or constantexpressions and are known as case labels.

    Each of these values should be unique within a switchstatement. block-1, block-2,.. are statements contain zero ormore statements. There is no need to put braces around theseblocks. The case labels must end with a colon. When a switch is

    executed, the value of expression is compared with case values, ifmatches, then the block of statements that follows the case areexecuted. The break statement is used to exit from the switchstatement.Example:--------------------switch(n){

    case 1: c=a+b;break;

    case 2: c=a-b;break;

    default: c=a/b;break;

    }printf(%d,c);----------------------------------

    Loop constructs:Purpose:

    It is used to repeat the block of statements for n number oftimes.Process involved in looping statement is as follows:-

    1. Setting and initialization of counter.2. Execution of the statements of the statements in the loop.3. Test for a specified condition for execution of the loop.4. Incrementing the counter.

  • 8/9/2019 Ecs C_prog Material

    26/126

    Types:1. While statement2. Do statement3. For statement

    1) While statement:a. The while is an entry- controlled loop statement.b. The test -condition is evaluated first and if thecondition is true, then the body of

    loop is executed. Again the test-condition is tested and bodyof the loop will be

    repeated until the condition becomes falsec. If at the entry condition itself the test-condition is false thenbody of loop will beskipped.Syntax:

    Example:#include < stdio.h>void main(){

    int i=1;while (i

  • 8/9/2019 Ecs C_prog Material

    27/126

    -----------------------------------do{

    printf(well done!);

    }while(number

  • 8/9/2019 Ecs C_prog Material

    28/126

    for (i=1;i

  • 8/9/2019 Ecs C_prog Material

    29/126

    24.What sre symbols used for logical operators AND & OR?25.Give the conversion specifications used for printing octal & hexa

    decimal values.26.every line in c programming should end with a semi colon.- say

    true or false

    27.in c language , lowercase letters are significant- say true or false28.every c program end with and END word.29.main() is where the program begins its execution.30.a line in c program may have more than oneline of output.31.a printf() statement can generate only one line of output.32.syntax error will be detected by the compiler.33.what are trigraph characters? How are they useful?34.what is variable.35.what is initialization? Why it is important?36.what are enumeration variables? How are they declared?37.describe the purpose of the qualifiers const and volatile.

    38.which of the following are invalid constant and why?0.00015x1.59999912.34239.which of the following are invalid variable names and why?MaximumLast.rollnoMn+meRow total40.which of the following arithmetic expressions are valid? If invalid,

    give reason.25/3%212.4%221 %(int)3.241.write the c assignment statements to evaluate the following

    equations.42.Area= IIr2+22/7rh43.Torque=2m1m2

    44.m1+m245.determine the valueof each of the following logical expressions if

    a=10,b=25and c=-7a>b&&a12&&c

  • 8/9/2019 Ecs C_prog Material

    30/126

    48.write the syntax of if.. statement . write the difference betweenwhile statement and dowhile statement

    Suggested Questions:49.Explain if statement with an example

    50.Differentiate while & do...while statement51.?52.write a program to check whether the given year is a leap year

    or not53.write a program to find largest among three given numbers.54.write a program to find reverse of the given digit55.write a program to do arithmetic operations for any two given

    numbers using switch case statement.56.write important features of for statement.57.write a program to convert the given farenheit temperature to

    Celsius temperature.

    58.write a program to generate fibanocci numbers59.write a program to generate prime numbers.60.write a program to calculate simple and compound interest

    Essay Answers61.Explain about looping statements with suitable examples62.Write a program to print the fibonacci series63.Write a program to print the prime numbers between 1 to 10064.Write a program in c to solve a quadratic equation to check all

    possibilities of their coefficients

    STUDY MATERIAL

    COURSE : II YEAR A, B.Sc ECSSEMESTER : IIIUNIT : IIISUBJECT NAME : PROGRAMMING IN CLECTURER NAME : D.MYTHILINUMBER OF PAGES : 56DATE OF ISSUE :

    Unit-IIIArrays : Array initialization definition characteristics- one dimensional array, predefined streams- Two- dimensional array Threeor multi dimensional arrays. Strings and Standard functions:-Declaration and initialization of string- Display of string with differentformats String standard functions Application of strings. Pointers:Features, Pointer declaration, Arithmetic Operations with pointers-

  • 8/9/2019 Ecs C_prog Material

    31/126

    Pointers and Array Pointers and Two-dimensional array Array ofpointers Pointers to pointers Pointer and Strings Void pointers.Functions: Definition, Declaration, The return statement, Types offunctions, Call by value and Call by reference, Functions returningmore values, Functions as an argument. Functions with Arrays and

    pointers Recursion Preprocessor Directives.

    ARRAYSDefinition :An array is a group of related data items that share a common name.Example:An array name salarycan be used to represent a set of salaries of agroup of employees.A particular value in an array is called an element and can be writtenas follows

    salary [10] represents the salary of the 10th person.

    TYPES :1. One dimensional arrays / Single subscripted array2. Two dimensional array3. Multi dimensional array

    ONE DIMENSIONAL ARRAY:Definition :

    A list of related data items with one variable and only one subscript iscalled single- subscripted array.

    DECLARATION OF ARRAYS:Syntax:

    wheretype - int, float ,double, longint,char

    variable_name - valid c programming variablesize - no. of elements

    Example:1. int a[10];2. float height[20];3. char name[10];

    Explanation:1. In the first declaration we can store atmost 10 elements

  • 8/9/2019 Ecs C_prog Material

    32/126

    of type integers.2. The second declaration can hold 20 elements of realnumbers.3. In third we can store atmost 9 characters. Whiledeclaring character array the last character must be a null

    character(\0). This character is automatically included while assigningvalues to these variables. While mentioning about the size we mustinclude one extra space with maximum number of characters.

    INITIALIZATION OF ARRAYS: Syntax:

    We can initialize the array variable like ordinary variableswhen they are declared. In the above list of values are separated by

    comma. Suppose the value is not given then automatically it will beassigned as zero.

    Example:a. static float total[5] = {0.5,15.63,-20};

    In the above the first three elements are set to 0.5, 15.63, -20and the remaining elements are set to

    zero.b. static int count[]= {1,1,1,1};

    In the above the size is omitted. The compiler itself allocatesenough space for all initialized

    elements.

    DRAW BACKS IN INITIALIZATION OF ARRAYS:

    1. There is no convenient way to initialize only selectedelements.2. There is no shortcut method for initializing a large numberof array elements like the one available in FORTRAN.

    TWO DIMENSIONAL ARRAYS: Definition :

    A list of related data items withone variable and subscriptsrepresenting the row value and column value is called two dimensionalarray.

    DECLARATION OF ARRAYS:Syntax:

  • 8/9/2019 Ecs C_prog Material

    33/126

    wheretype - int, float ,double, longint,charvariable_name - valid c programming

    variablesize - no. of elements

    Example:1. int a[10][10];2. float height[20][2];3. char name[10][10];

    Explanation:1. In the first declaration we can store atmost 100 elements ofintegers.2. The second declaration can hold 40 elements of real numbers.3. In third we can store almost 10 names of 9 characters. While

    declaring character array the last character must be a nullcharacter(\0). This character is automatically included while assigningvalues to these variables. While mentioning about the size we mustinclude on extra space with maximum number of characters.

    INITIALIZATION OF ARRAYS:Syntax:

    We can initialize the array variable like ordinary variables when

    they are declared. In the above list of values are separated by comma.Suppose the value is not given then automatically it will be assigned aszero.

    Example:

    a. static float mat[2][3] = {{0.5,15.63,-20},{10.2}};In the above the first row elements are set to 0.5 , 15.63 , -20 and inthe second row the first element is 10.2 and the remaining elementsare set to zero.

    MULTI DIMENSIONAL ARRAYS: Definition :

    A list of related data items with one variable and more than 2two subscripts is called multi-dimensional array.

    DECLARATION OF ARRAYS:Syntax:

  • 8/9/2019 Ecs C_prog Material

    34/126

    wheretype -- int , float , double , longint , char

    array_name -- valid c programming variable

    si -- size of ith dimension where i =1,2,3n

    SAMPLE PROGRAM USING ARRAY:(ascending order)

    #include #include main(){

    int i, a[10], n, t;/*INPUT THE NUMBER OF ELEMENTS*/

    printf(Enter the total no of elements \n);scanf(%d,&n);/*ENTER THE VALUES TO BE SORTED*/printf(Enter elements \n);for(i=1;i

  • 8/9/2019 Ecs C_prog Material

    35/126

    Definition:String is an array of characters. Any group of characters

    enclosed between double quotes is a string constant.Example:

    Where there is will there is way

    Operations performed on strings:1. Reading and writing strings.2. Combining strings together.3. Copying one string to another.4. Comparing strings for equality.

    5. Extracting a portion of string.

    DECLARATION AND INITIALIZATION OF STRING VARIABLES:Syntax:

    Example:1. char city[10];2. char name[30];3. static char city[9]= new york;4. static char city[9]={n,e,w,,,y,o,r,k,\o};

    In the above 3 and 4 initializations are same. In character array thecompiler automatically includes the null character at the end of thestring.

    If the size is not mentioned then the compiler itself defines the size ofthe array variable depending upon number of elements in theinitialization statement.

    READING STRINGS FROM THE TERMINAL:The scanf function can be used with the control string %s

    to read in a string of characters.

    Example:char name[15];

    scanf(% s,name);

    In the above example & is not required before the variable name.

    Drawback:1. We cannot read a line of text from the terminal.

    Reading a line of text:We can read the entire line of text using the function getchar().

    By using the above function it terminates the input process whenever

  • 8/9/2019 Ecs C_prog Material

    36/126

    it receives the newline character.

    Example:/**************************************//* program to read a line of text from terminal*/

    /**************************************/#include main(){char line[81],character;

    int c;c=0;

    printf(enter text .press at end\n);do{

    character=getchar();

    line[c]=character;c++;}while (character!=\n);

    c=c-1;line[c]=\0;printf(\n%s\n,line);}

    WRITING STRINGS TO THE SCREEN:Printf statement with control string %s is used to display the

    string value.Example:

    Printf(%s,name); (or) printf(%Total columns.Totalcharacters s,name);

    EFFECT OF VARIOUS %S SPECIFICATION :1. When the field width is less than the length of the string , theentire string is printed.2. The integer value on the right side of the decimal pointspecifies the number of number of characters to be printed.3. When the number of characters to be printed is specified as

    zero, nothing is printed.4. The minus sign in the specification causes the string to beprinted left- justified.

    ARITHMETIC OPERATIONS ON CHARACTERS:C allows us to manipulate the characters in the same way as numbers.Whenever a character constant or character variable is used it isautomatically converted into integer value by the system. The integer

  • 8/9/2019 Ecs C_prog Material

    37/126

    value depends on the local character set of the system.Example:X=a;Printf(%d\n,x);

    The output of the above statement will be 97.

    Similarly it is also possible to perform all the arithmetic operations likeaddition ,subtraction , multiplication , division etc. To convert integerto ascii as well as ASCII to integer is done by using library functionslike itoa(integer),atoi(string).

    PUTTING STRINGS TOGETHER: Just as we cannot assign one string another directly, we cannot jointwo strings together by the simple arithmetic addition like as follows:

    Str3=str1+str2;

    Str2=str1+good; invalid

    The characters from str1 and str2 should be copied into thestr3 one after another. The size of the array str3 should be largeenough to hold the total characters. Example:

    PROGRAM FOR CONCATENATION OF TWO STRINGS:#include

    #include #include main( )

    {int i , j , k;static char f_str[10]={hello};static char s_str[10]={world};char t_str[20];for(i=0;f_str[i]!=/0;i++)

    t_str[i]=f_str[i];t_str= ;for(j=0;s_str[j]!=/0;j++)

    t_str[i+j+1]=s_str[j];t_str[i+j+1]= ;

    printf(%s,t_Str);}Output:

    hello worldSTRING HANDLING FUNCTIONS:C library supports a large number of string-handling functions that canbe used to carry out many of string manipulations like concatenation ,

  • 8/9/2019 Ecs C_prog Material

    38/126

    comparison , copy , finding length of the given string etc.

    Functions

    Description

    srlen ( ) Determines length of a stringsrcpy ( ) Copies a string from source to destinationsrncpy()

    Copies character of a string to another string upto thespecified length.

    srcmp( )

    Compares characters of two strings

    sricmp()

    Compares two strings

    srncmp()

    Compares characters of two strings upto specified length

    srnicmp

    ( )

    Compares characters of two strings upto specified length.

    Ignores case.srlwr( ) Converts uppercase characters of a string to lowercasesrupr( ) Converts lower characters of a string to upper`srdup( ) Duplicates a string.strchr( ) Determines first occurrence of a given character in a stringstrrchr()

    Determines last occurrence of a given character in a string

    strstr ( ) Determines first occurrence of a given string in anotherstring

    strcat( ) Appends source string to destination string.strncat(

    )

    Appends source string to destination string upto specified

    length.strrev( ) Reverses all characters of a string.strset( )

    Sets all characters of string with a given argument orsymbol.

    strnset ()

    Sets specified numbers of characters of string with a givenargument or symbol.

    strspn( ) Finds upto what length two strings are identical.strpbrk()

    Searches the first occurrence of the character in a givenstring and then it displays the string starting from thatcharacter.

    STRCAT( ) FUNCTION:Syntax:

    Example:Part1=computer ;

  • 8/9/2019 Ecs C_prog Material

    39/126

    Strcat(part1,science);In the given syntax string1,string2 are character arrays. When

    the function is executed string2 is appended to string1 by removingnull characters at the end of string1. thus in the given example theoutput should be computer science. Thus the resultant value is

    stored in part1.

    STRCMP( ) FUNCTION:Syntax:

    Example:Part1=computer ;Strcmp(part1,computer );

    The above function compares the two given strings string1 and string2and return value 0 if both are equal .if not it will return the numericaldifference between the mismatching characters in the strings. In theabove example it return o as a value.STRCPY( ) FUNCTION:Syntax:

    Example:Strcpy(part1,science);In the given syntax string1,string2 are character arrays.

    When the function is executed string2 is copied to string1. Thus in thegiven example the output should be science. Thus the resultantvalue is stored in part1.

    STRLEN( ) FUNCTION:Syntax:

    Example:Part1=computer;N = Strlen(part1);In the given syntax string1 is character array. When the

    function is executed it counts and returns number of characters in astring. The counting ends at the first null character. Thus in the givenexample the output should be 8. Thus the resultant value is stored in

  • 8/9/2019 Ecs C_prog Material

    40/126

    N.

    USER-DEFINED FUNCTIONS:

    DEFINITION:

    A function is a self-contained block of code that performs a particulartask. once a function is designed and blocked it is called as black-boxthat takes some data from the main program and returns value.

    Example:Printline(){

    int a;for(a=1;a

  • 8/9/2019 Ecs C_prog Material

    41/126

    ______________abc(x,y,z); Function call

    Actual argument______________

    }abc(l,k,j) Function definition{

    Formal argument________________

    return();}

    Actual argumentThe arguments of calling function are actual arguments In theabove example, x , y and z are actual arguments.Formal argumentsThe arguments of called function are formal arguments. In theabove example, l , k and j are formal arguments.Function name

    Here, abc is a function name.Argument list

    Variable names enclosed within parenthesis arecalled argument list.

    Function callA function can be called by its name, terminated by

    a semicolon.Example

    function fact (int n1){

    int f1;for(i =1;i

  • 8/9/2019 Ecs C_prog Material

    42/126

    Local and Global variablesThere are 2 kinds of variables.

    Local variables The local variables are defined within the body of thefunction. The variable defined is local to that function only. Otherfunctions can not access these variables.Global variables

    Global variables are defined outside the main( ) function.Multiple functions can use them.local variables: Global variables:

    Can be accessed only in thefunction where it has been

    declared.

    Can be accessed by all thefunctions in the program.

    Needs to be declared inside thefunction where it is to be used.

    Needs to be declared in the globaldeclaration section outside allprograms.

    Variables are secure. Can be used by many functionsand so are not secure.

    Stored in separate locations , soaccessing will change the valueonly in the function where itsused.

    Stored in one location, so anyfunction accessing can changeits value.

    Example:int m;main( ){

    int i;float balance;....function1( );

    }function1( )

    {int i;float sum;

    }In the above example, variable m is a global variable and

    can be accessed anywhere in the program where as variable i is a

  • 8/9/2019 Ecs C_prog Material

    43/126

    local variable and should be accessed only in the function in whichit is declared. The variables balance and sum are local variablesand can be accessed in the functions main and function1respectively.7The Return Statement

    The user defined functions uses a return statement to return thevalue to the calling function. Exit from the called function to thecalling function is done by the use of a return statement. Whenthe return statement is executed it always returns 1.Eg. Write a program to use a return statement in differentways.#include#includemain( ){int pass(int);

    int x,y;clrscr( );printf( enter the value of x:);scanf(%d,&x);if(x= =1|| x

  • 8/9/2019 Ecs C_prog Material

    44/126

    whether a value is returned or not, may belong to one of thefollowing categories.1. Functions with no arguments and no return values.2. Functions with arguments and no return values.3. Functions with arguments and return values.

    4. Functions with no arguments and return values.

    No Arguments and no return values:When a function has no arguments, it does not receive any datafrom the calling function. Similarly, when it does not return avalue, the calling function does not receive any data from thecalled function. So there is only a transfer of control between thecalling and the called function, but not a data transfer.

    Example:/* addition of two numbers*/#include

    main( ){

    add ( );}

    /* function definition*/add(){

    int a,b;a=a+b;printf(%d,a);return(0);

    }With Arguments but no return values:

    In the previous category there is no data communication betweenthe functions. So this approach is not better. To make it efficientlywe could make the calling function to read data from the terminaland pass it on to the called function. The nature of datacommunication between the calling function and the calledfunction is with arguments but no return values.

  • 8/9/2019 Ecs C_prog Material

    45/126

    Example:

    /* addition of two numbers*/#includemain( )

    {int a=2,b=3;add (a,b);

    }

    /* function definition*/add(int a1,int b1){

    a1=a1+b1;printf(%d,a1);return;

    }The arguments that we are using in the main function are calledactual arguments. The arguments that we are using in thecalled function instead of the actual arguments are called asformal arguments.When a function call is made, only a copy of the values of actualarguments is passed into the called function. Changes inside thefunction will have no effect on variables used in the actual

    argument list.With Arguments and return values:In the previous category the calling function sends some data tothe called function, but the called function does not returnanything to the calling function. So it is like one-waycommunication. To make it more effective, both send and receivedata in this category. If there is any change of values in calledfunction, it has to be shown in the main function also.

    Example:/* addition of two numbers*/#include

    main( )

  • 8/9/2019 Ecs C_prog Material

    46/126

    {int a,b,c;c=add (a,b);printf(%d,c);getch();

    }/* function definition*/add(int a1,int b1){

    a1=a1+b1;return(a1);

    }With no arguments and return values:

    Eg. Program without passing any value through main( )#includemain( ){int sum( ), a,s;

    clrscr( );s=sum( );printf(Sum =%d, s);return 0;}sum( ){int x,y,z;printf( Enter the values);scanf(%d%d%d,&x,&,&z);return(x+y+z);

    }Output:Enter three values: 3 5 4Sum = 13Call by value and ReferenceThereare 2 ways in which we can pass arguments to the function.Call by value69.Values of actual arguments are passed to the formal

  • 8/9/2019 Ecs C_prog Material

    47/126

    arguments and the operation is done on the formal arguments.70.Any change made in the formal argument does not affect the

    actual arguments.71.Example/* swapping of two numbers*/

    #includemain( ){

    int a=3,b=4;swap(a, b);

    printf(In main);printf(a=%d, b=%d, a, b);

    getch();}/* function definition*/

    swap(int a, int b)

    { int t;t=a;a=b;b=t;printf(In function swap);printf(a=%d, b=%d, a, b)

    }OUTPUT

    In function swapa=4, b=3

    In maina=3, b=4

    Call by Reference72.Instead of passing value, addresses are passed.73.Function operates on addresses rather than values.74.Any change made in the formal argument will affect the actual

    arguments.Example/* swapping of two numbers*/

    #includemain( )

    {int a=3,b=4;swap(&a, &b);

    printf(In main);printf(a=%d, b=%d, a, b);

    getch();}/* function definition*/

  • 8/9/2019 Ecs C_prog Material

    48/126

    swap(int *a, int *b){

    int t;t=*a;*a=*b;

    *b=t;printf(In function swap);printf(a=%d, b=%d, a, b)

    }OUTPUT

    In function swapa=4, b=3In maina=4, b=3

    Function Returning More values:Eg:Write a program to return more than onevalue from a

    user-defined function.#include

    #includemain( ){int x,y, add, sub, change(int *, int *, int *, int *);clrscr( );printf( Enter values of X and Y:));scanf(%d%d, &x, &y);change(&x,&y, &add, &sub);printf(Addition:%d, add);

    printf(Subtraction: %d, sub);return 0;}change(int * a, int * b, int *c, int *d){*c=*a+*b;*d= *a-*b;}Output:Enter values of X and Y: 5 4Addition:9

    Subtraction: 1

    Function as an argument:Eg: Write a program to pass a user-defined function as anargument to another function:main ( ){int y=2, x;

  • 8/9/2019 Ecs C_prog Material

    49/126

    x= double(square(y));printf(x=%d, x);}double(m){

    return(m*2);}square(k){return(k*k);}Output:x=8

    Functions with Array and pointersa) Initialization of an array using a function::

    Like the values of simple variables, it is also possible to passthe values of an array to a function. To pass an array to a calledfunction, it is enough to list the name of the array, without anysubscripts and the size of the array as arguments.Example:Lar(a,n);

    Array size of the arrayName

    /* program to find smallest element among given set of

    elements*/#includemain(){

    float smallest(float,int);static float a[5]={1.0 , 4.0 , 50.34 , 60.3 , 1.0};printf(%f,smallest(a,5));

    }/* function definition*/float smallest (float a[], int m){

    int i;float small;small=a[0];for(i=1;i

  • 8/9/2019 Ecs C_prog Material

    50/126

    b) Passing array elements to a function:Eg:Void main( ){int k, show(int, int);

    int num[ ] ={ 12,13,14,15,16,17,18};clrscr( );for (k=0;k

  • 8/9/2019 Ecs C_prog Material

    51/126

    num[2] = 14num[1] = 13num[0] = 12d) Copying an array:Void main( )

    {int cpy(int *, int *), h;int a1[ ] ={ 1,2,3,4,5};clrscr( );cpy(&a1[0], &a2[0]);printf(:Source Target);for (h=0;h

  • 8/9/2019 Ecs C_prog Material

    52/126

    static int k;int b[5]={1,2,3,4,5};return(b[k++];}Output:

    1 2 3 4 5Output:1 2 3 4 5

    Recursion:75.Recursion is the process where a function is called repetitively

    by itself.76.The recursion can be used directly or indirectly.Direct recursionA function calls itself till the condition is true.Example 1:

    //program to find the factorial of a number#includemain(){

    int n;scanf(%d,&n);printf(%d,factorial(n));

    }

    factorial(int n){

    int fact;if(n==1)

    return 1;else

    fact=n*factorial(n-1);return(fact);

    }

    Steps:1.When n=3, fact=3*factorial(2)2.When n=2, fact=2*factorial(1)

    3.When n=1, 1 is returned & control goes to step 1where fact = 2*1=2 & control is returned to step 1where fact = 3*2=6 & value is given to the calling

    functionIndirect RecursionA function calls another function then the called function calls thecalling function.Example.

  • 8/9/2019 Ecs C_prog Material

    53/126

    Void main(){

    add();}add()

    { static int i=0;while (i

  • 8/9/2019 Ecs C_prog Material

    54/126

    Example:main(){

    int a=1000;function2();

    printf(%d\n,a);}function2(){

    int a=10;function1();

    printf(%d\n,a);}function1(){

    int a=100;

    printf(%d\n,a);}Output:

    100101000

    EXTERNAL VARIABLES:

    Variables that are both alive and active throughout the program areexternal or global variables.

    They can be accessed by any function within the program. They are declared outside a function. Once a variable is declared as global any function can change its

    value. Therefore these are generally used when values are to beshared between functions.

    A global variable is visible only from the point where it is declared.main()

    {y=5;

    }int y;f1(){

    y=y+1;}

    This will cause the compiler to generate an error message since y hasnot been defined in the function main.To avoid this we use the storage class extern.

  • 8/9/2019 Ecs C_prog Material

    55/126

    main(){

    extern int y;

    }f1(){

    extern int y;

    } The keyword extern informs the compiler that thevariable y has

    been declared somewhere and asks to perform a lookup for thevariable. The extern declaration does not allocate storage space forthe variables.

    Multiple files can share a variable provided it is declared as enexternal variable (i.e) it is declared as a global variable in one fileand specified as an extern in the other.

    Example:int a;main(){

    a=10;function2();printf(%d\n,a);

    }

    function2(){

    a=a*10;function1();printf(%d\n,a);

    }function1(){

    a=a*10;printf(%d\n,a);

    }

    Output:100010001000

    STATIC VARIABLES: The value of static variables persist until the end of the program.

  • 8/9/2019 Ecs C_prog Material

    56/126

    Can be of internal or external type depending on the place ofdeclaration.

    Internal static variables are those that are declared inside afunction.They are similar to auto variables but are alive throughoutthe entire program. They are used to retain values between function

    calls. External static variables are those that are declared outside

    functions. A static external variable is available only within the file where it is

    declared. A static variable is initialized only once.Example:/*Static variable example*/main(){

    int i;

    for( i = 0; i

  • 8/9/2019 Ecs C_prog Material

    57/126

    VISIBILITY AND LIFETIME OF VARIABLES:

    Storageclass

    Place of Declaration Visibility Lifetime

    None Before all functionsin a file Entire file + other fileswhere variable isdeclared as extern.

    EntireProgram(Glal)

    Extern Before all functionsin a file

    Entire file + other fileswhere variable isdeclared as extern andthe file where it isoriginally declared asglobal.

    Global.

    Static(external)

    Before all functionsin a file Only in that file

    Global

    None orauto

    Inside a function Only in that function Until end function

    Register Inside a function Only in that function Until end function

    Static(internal)

    Inside a function Only in that function Global

    POINTERS:A pointer is a variable that contains an address which is a

    location of another variable in memory.

    Advantages of using pointers:1. A pointer enables us to access a variable that is defined outsidethe function.2. Pointers are more efficient in handling the data tables.3. Pointers reduce the length and complexity of a program.4. They increase the execution speed.5. The use of a pointer array to character strings results in saving ofdata storage space in memory.

    REPRESENTATION OF A VARIABLE:

  • 8/9/2019 Ecs C_prog Material

    58/126

    The computers memory is a sequential collection ofstoragecells called as a byte. Each byte has a unique address associatedwith it. Whenever a variable is declared the value will be stored in amemory location in the given name. Thus it may have some addressthe above quantity is a variable name with the content 100 stored in

    the location 5000. If we use a pointer variable for indicating thiscontent then the pointer variable itself contains the address 5000 as itsvalue. Thus pointer variable is a variable which contains the address ofanother variable. Using pointer variable p the memory representationwill be as like as follows

    Accessing a variable using pointers: The address of a variable can be accessed by using the

    symbol & which is called as address of the variable. In our scanffunction we use this operator to indicate the address of a variable.Thus to assign the address of a variable to the pointer variable we canuse this operator.Example:

    p = &quantity;Thus in the above example p is a pointer variable which holds the

    address of the variable quantity.

    DECLARING AND INITIALIZING POINTERS:In C , every variable must be declared for its type. Since

    pointer variables contain the address of a variable , they must bedeclared before we use them. The declaration of pointer variable takesthe followingformSyntax:

    The above tells the compiler three things about the variable pt_name.1. The asterisk (*) tells that the variable pt_name is a pointervariable.2. pt_name needs a memory location.3. pt_name points to a variable of type data type.Example:

    int *p;

  • 8/9/2019 Ecs C_prog Material

    59/126

    declares the variable p as a pointer variable that points to an integerdata type. The type int refers to the data type of the variable beingpointed to by p and not the type of the value of the pointer. Similarlythe statement

    float * x;

    declares x as a pointer to a floating point variable. Once a pointer hasbeen declared , it can be made to point to a variable using anassignment statement such as

    p = &quantity;Thus p now contains the address of the variable quantity. This ascalledpointer initialization.

    ACCESSING VALUE OF A VARIABLE THROUGH POINTERS:Once a pointer has been assigned the address of a variable ,

    we can access the content using the indirection operator (*).Example:

    int quantity, *p, n;quantity = 100;p = &quantity;n = *p;

    Statements Quantity pn

    5000 5010 5020

    int quantity, *p, n;

    quantity = 100;

    p = &quantity;

    n = *p;

    Thus in the above example the first statement declares the pointervariable p ,which points to integer data type. In the second statement100 is assigned to quantity. In the third statement the address isassigned to the pointer variable p. In the fourth statement the contentis assigned to the variable n.

    POINTER EXPRESSIONS:Like other variables, pointer variables can be used in

    expressions. For example , if p1 and p2 are properly declared andinitialized pointers, then the following statements are true.

    y = *p1 * *p2;sum =sum+ *p;p1++;

  • 8/9/2019 Ecs C_prog Material

    60/126

  • 8/9/2019 Ecs C_prog Material

    61/126

    requires two bytes, the first element will be stored as follows.

    elements x[0] x[1] x[2] x[3] x[4]valueaddress 1000 1002 1004 1006 1008

    base addressThe name x is defined as a constant pointer pointing to the first

    element ,x[0] and therefore the value of x is 1000,the location wherex[0]is stored. That is

    x = &x[0] = 1000If we declare p as a pointer , then we can make the pointer p to thearray x by the following assignment:

    p=x;That is equivalent to

    p=&x[0];

    Suppose if we want to access the next element then we canincrement the address by p++ to move from one element to another.The relationship between p and x is shown below:

    P= &x[0] (=1000)P+1=&x[1] (=1002)

    P+2=&x[2] (=1004)P+3=&x[3] (=1006)P+4=&x[4] (=1008)

    The formula for calculating the effective address of ith element if

    Example:/*Program to calculate the sum of numbers in an array using

    pointers*/#includeMain()

    {int x[10], *p, i, sum=0;printf(Enter the elements\n);for(i=0;i

  • 8/9/2019 Ecs C_prog Material

    62/126

    }printf(Sum = %d,sum);

    }

    Pointers to two dimensional array:

    0 1 2

    (1,1)

    (2,0)(3,0)

    (3,2)

    p pointer to the first row

    p+i pointer to the ith row*(p+i) pointer to first element in the ith

    row*(p+i)+j pointer to jth element in the ith

    row*(*(p+i)+j) value stored in the cell(i,j)

    Example:/*Program to find the transpose of a matrix*/

    #include

    main()

    {

    int a[5][3],i,j;

    printf(Enter the values of the 5*3 matrix\n);

    for(i=0;i

  • 8/9/2019 Ecs C_prog Material

    63/126

    scanf(%d,&a[i][j]);

    }

    }

    printf(Original Matrix\n);

    for(i=0;i

  • 8/9/2019 Ecs C_prog Material

    64/126

    }

    getch();

    }

    POINTERS AND CHARACTER STRINGS:A string is an array of characters , terminated with null

    character. Like in one dimensional arrays, we can use a pointer toaccess the individual characters in a string.Example:

    #includeMain( ){

    char*name;int length;char *cptr =name;name=delhi;while (*cptr!=\0){

    printf(%c is stored at address %u,*cptr,cptr);cptr++;

    }length=cptr-name;printf(length %d,length);

    }Thus the above program finds the length of the given string.Pointers can also be used to handle tables of strings.Example: Static char *name[3]={Delhi,Bombay,Chennai}Declares name to be an array of three pointers to characters as shownbelow

    Name[0]-delhiName[1]-Bombay

    Name[2]-Chennai*(name[I]+j) is used to access the jth character in the ith row .

    Thus *p[3] denotes p as an array of three pointers.(*p)[3] denotes p as a pointer to an array of three elements.

    POINTERS AND FUNCTIONS:The address of a variable can be passed on to a function. When

    we the address to a function the parameters should be declared as

  • 8/9/2019 Ecs C_prog Material

    65/126

    pointers of the appropriate datatype.The process of calling a function

    using pointers to pass the address of a variable is known as call by

    reference. The function that can be called by reference van change the

    value of the variable used in the call.

    Example:

    #include

    Main(){

    int x=100,y=200;

    printf(Before exchange : x = %d y = %d\n,x,y);exchange(&x,&y);printf(After exchange : x = %d y = %d\n,x,y);

    }exchange(int *a, *b){

    int t;t=*a;*a = *b;*b = t;

    }

    Output:Before exchange : x=100 y=200

    After exchange : x=200 y=100Thus, call by reference provides a mechanism by which the functioncan change the stored values in the calling function.Note:

    The function parameters are declared as pointers and are used inthe function body.

    When a function is called, the addresses are passed as actualparameters.

    Pointers to functions:A function also has an address in the memory. So it is possible to

    declare a pointer to a function.

    Syntax:

  • 8/9/2019 Ecs C_prog Material

    66/126

    Example:

    /*Program to calculate 2*x*x*/

    #include

    void Main()

    {

    int exp(),val(),I,v;

    for(I=1;I

  • 8/9/2019 Ecs C_prog Material

    67/126

    {

    return(I*I);

    }

    ARRAY OF POINTERS:

    Similar to an array of integers or an array of characters, we can

    have an array of pointers. Since a pointer variable contains the address

    of an another variable, an array of pointers contains a collection of

    addresses. The addresses of array elements can be the addresses of

    isolated variables or the addresses of other array elements.

    Example:

    /*Array of pointers to isolated variable*/

    #include

    main()

    {

    int *arr[3],i=10,j=20,k=30,m;

    arr[0]=&I;

    arr[1]=&j;

  • 8/9/2019 Ecs C_prog Material

    68/126

    arr[2]=&k;

    for(m=0;m

  • 8/9/2019 Ecs C_prog Material

    69/126

    7000 7002 7004

    A multidimensional array can be expressed in terms of array of

    pointers. Thus a two dimensional array can be declared as a series of

    one dimensional arrays as follows.

    Datatype *array[expression1];

    In general a n-dimensional array can be declared as follows

    Syntax:

    Example:

    /*Array of pointers to one dimensional arrays*/

    #include

    void main()

    {

    int *p[3],I,j;

    int a[]={1,2,3},b[]={4,5,6},c[]={7,8,9};

    p[0]=a;

    p[1]=b;

    p[2]=c;

  • 8/9/2019 Ecs C_prog Material

    70/126

    printf(the values are\n);

    for(I=0;I

  • 8/9/2019 Ecs C_prog Material

    71/126

    Preprocessor Directives :

    Introduction of Preprocessor Directives:The steps for execution of any program:

    77.C program is written in the editor.

    78.Compilation79.Linking80.The executable code is generated. In between these stages there also involves one stage i.ePreprocessor. One of the most important features of C language isto offer preprocessor directives. The preprocessor is a program that processes the sourceprogram before it is passed on to the compiler. The program typed in the editor is the source code to thepreprocessor. The preprocessor then passes the source code tothe compiler.

    The preprocessor is a program that processes the sourcecode before it passes through the compiler.81.It operates under the preprocessor directives or preprocessor

    command lines. Preprocessor directives are placed before themain() function.

    Rules:

    Preprocessor directives begin with #. They are placed before the main() function. They do not require a semicolon at the end.

    The #define DirectiveThe syntax of #define directive is as follows:#define identifier

    OR#define identifier (argument 1.. argument N)

    substitute textExample:

    # define PI 3.14 This statement defines macro templates. During

    preprocessing the preprocessor replaces every occurrence of PIwith 3.14 . Here PI is the Macro template and 3.14 is its macro

    expansion. The macro templates are generally declared in capitalletters.The macro definition can be terminated with semi-colon and it isoptional. The words followed by # are not keywords and theprogrammer can use these words for variable names.Program:

    #include#define M 5

  • 8/9/2019 Ecs C_prog Material

    72/126

    #define AND &define EQUALS ==void main(){

    int a=5;

    printf(Value = %d,M*5);}Output:Value = 25Program:

    #include#define CUBE(x) x*x*xvoid main(){

    int a,res;printf(Enter value);

    scanf(%d,&a);res=CUBE(a);printf(Result = %d\n,res);

    }Example:Write a program to define macros for logical operators.

    #include#include# define equal = =# define larger >void main ()

    {int a,b,c;clrscr();printf(Enter three Numbers:);scanf(%d %d %d ,&a,&b,&c);if (a larger b and a larger c)

    printf(%d is the larger number ,a);elseif(b larger a and b larger c)

    printf(%d is the larger number,b);else

    if(c larger a and c larger b)printf(%d is the larger number,c);elseif(a equals b and b equal c)printf(\n Numbers are same);

    }Output:Enter three numbers: 5 4 8

  • 8/9/2019 Ecs C_prog Material

    73/126

    8 is the larger numberUndefining a macro:

    A defined macro can be undefined, using the statement#undef identifer

    Example:

    Write a program to undefined a macro.#include#include#define wait getche()void main(){

    int k;# undef wait getche();clrscr();for(k=1;k

  • 8/9/2019 Ecs C_prog Material

    74/126

    Write a program to find the larger of the two numbers usingmacro with arguments.

    #include#include# define MAX(x,y) if (x>y) c=x; else c=y;

    void main(){int x=5,y=8,c;clrscr();MAX(x,y);printf(\n Larger of two numbers = %d,c);

    }Output:Larger of two numbers = 8Explanation:

    In the above program macro MAX() is defined with two

    arguments x and y. When a macro is called, its correspondingexpression is executed and result is displayed .The expressioncontains if statement that determines the largest number andassigns it to variable c.

    The # include Directive The # include directive loads specified file in the

    current program. The macros and functions of loaded file can becalled in the current program. The included file is also compiledwith current program.The syntax is

    # include file nameor #include where # is a symbol used with directives.1) The filename is included in the double quotation marks whichindicates that the search for the file is made in the currentdirectory and in the standard directories .Example:Write a program to call the function defined in udf.c file

    #include#include# include udf.cvoid main()

    {clrscr();display();

    }Output:Function calledContents of udf.c fileint display();

  • 8/9/2019 Ecs C_prog Material

    75/126

    display(){

    printf(\n Function called);return0;

    }

    Explanation:In the first program the udf.c is included .It is a user-defined function file .It is compiled before the main program iscompiled. The complete programs along with the included one areexecuted. The output of the program Function called isdisplayed.Conditional Compilation

    The most frequently used conditional directives are:82.#if83.#else84.#endif etc.

    These directives allow programmer to include the portions of thecodes based on the conditions. The compiler compiles selectedportion of the source codes based on the conditions.Syntax of #ifdef#ifdef{

    statement1;statement2;

    }#else{

    statement3;statement4;

    }#endif

    The #ifdef preprocessor tests whether the identifier hasdefined substitute text or not. If the identifier is defined then #ifblock is compiled and executed. The compiler ignores #else blockeven if errors are intentionally made. Error messages will not bedisplayed . if identifier is not defined then #else block is compiledand executed.Example:

    Write a program with conditional compilation as to whether theidentifier is defined or not.

    #include#include#define E =void main(){

    int a,b,c,d;

  • 8/9/2019 Ecs C_prog Material

    76/126

    clrscr();#ifdef E{

    a E2;b E 3;

    printf(A=%d &B=%d,a,b);}#else{

    c=2;d=3;printf(C=%d & D=%d,c,d);

    }#endifgetche();}

    Output:A=2 &B=3Explanation:

    The compiler search for the identifier E . The compilersearches for the identifier E. If it is found then execution of #ifblock takes place otherwise #else block. The #endif statementindicates the end of #if-#endif block.

    The #ifndef DirectiveThe syntax of #ifndef directive is given below

    #ifndef

    {statement 1;statement 2;

    }#else{

    statement 3;statement 4;

    }#endif

    The #ifndef works exactly opposite to that of #ifdef. The #ifndef

    preprocessor tests whether the identifier has defined substitutetext or not. If the identifier is defined then #else block is compiledand executed and the compiler ignores #If block even if errorsare intentionally made. Error messages will not be displayed. Ifidentifier is not defined then #if block is compiled and executed.Example:Write a program to check conditional compilation directives using#ifndef .

  • 8/9/2019 Ecs C_prog Material

    77/126

    #include#include#define T 8void main(){

    clrscr();#ifndef Tprintf(\n Macro is defined ,);#elseprintf(\n Macro is defined);#endif

    }OutputMacro is defined.Explanation:

    In the above program #ifndef checks for the identifier

    T. If it is defined the #else block is executed. On execution of theblock the output of the program is Macro is defined. In case theidentifier is undefined the #else block is executed and output isMacro is not defined.The #error directive

    The # error is used to display user defined messageduring compilation of the program. The syntax is# if !defined (identifier)# error # endifExample:

    Write a program to display user-defined error message using#error directive.

    #include#include#define B 1void main(){

    clrscr();#if !defined(A)#error MACRO A IS NOT DEFINED#else

    printf(Macro found);#endif

    }Explanation:

    In the above program identifier B is defined. In theabsence of identifier an error is generated and the #errordirective displays the error message. The error message is userdefined and displayed in the message box at the bottom of the

  • 8/9/2019 Ecs C_prog Material

    78/126

    editor. The # defined directrive will work opposite to the #!defineddirective. The syntax is

    # if defined{

    }#else# error # endif

    The #line directiveThe syntax is

    #line []This causes the compiler to imagine the line number of

    the next source line is given by and gives the current input file. If is absent , then the

    cuurent file name remains unchanged.Example : # line 15 add.cThe INLINE directive

    Reports the compiler that the source code has in lineasm statements. The source code will contain the assemblycode.The #pragma SAVEREGS

    It guarantees that a huge function will not modify thevalue of any of the registers when it is entered. Place thisdirective immediately preceding the function definition.The #pragma DIRECTIVE

    The ANSI-C and TURBO-C provide pragma directives >these # pragma directives are defined with #(hash) and these arethe preprocessor directives. It sets/resets certain warning anderrors during compilation of C program.Syntax:

    # pragma warn +xxx# pragma warn xxx

    ANSI Violations and #pragma

    # pragma name Warning On Warning off

    Hexadecimal oroctal constant toolarge

    +big -big

    Redefinition notidentical

    +dup -dup

    Both return andreturn of a valueused

    +ret -ret

  • 8/9/2019 Ecs C_prog Material

    79/126

    Not part of structure

    +str -str

    Undefinedstructure

    +stu -stu

    Suspicious pointer

    conversion

    +sus -sus

    Void functionscannot return avalue

    +voi -voi

    Zero lengthstructure

    +zst -zst

    Common errors and #pragma#pragma name Warning On Warning

    offAssigned a value but neverused

    +aus -aus

    Possible use before definition +def -def Code has no effect +eff -eff Parameter never used +par -parPossibly incorrect assignment +pia -piaUnreachable code +rch -rchFunction should return avalue

    +rvl -rvl

    Ambiguous operators needparenthesis

    +amb -amb

    Less Common Errors and #pragma#pragma name Warning On Warning Off

    Superfluous &with function orarray

    +amp -amp

    No declarationfor function

    +nod -nod

    Call to functionwith noprototype

    +pro -pro

    Structure passedby value

    +stu -stu

    Declared but

    never used

    +use -use

    Portability Warnings and #pragma#Pragma name Warning On Warning Off Nonportablepointerassignment

    +apt -apt

    Constant is long +cln -cln

  • 8/9/2019 Ecs C_prog Material

    80/126

    Non-portablepointercomparison

    +cpt -cpt

    Constant out ofrange in

    comparison

    +rng -rng

    Non-portablepointerconversion

    +rpt -rpt

    Conversion canlose significantdigits

    +sig -sig

    Mixing pointersto signed andunsigned char

    +ucp -ucp

    Example:Write a program to set off certain errors shown by the programusing #pragma directive

    #include#include#pragma warn-aus#pragma warn-def#pragma warn-rvl#pragma warn-usemain (){

    int x=2,y,z;printf (\n y=%d,y);

    }

    Explanation:The above program contains following warnings

    85.Possible use of y before definition in function.86.Z is declared but never used in function main.87.x is assigned a value which is never used in function.88.Function should return a value in function main.The display of these errors can be made on/off by using

    the pragma options.Standard i/o predefined Streams in Stdio.h

    The predefined streams automatically opens when the programis started.

    Standard i/o predefined macros in stdio.hMacros Function Definition in stdio.h

  • 8/9/2019 Ecs C_prog Material

    81/126

    Stdin Standard input device #define stdin(&streams[0])

    Stdout Standard outputdevice

    #define stdout(&streams[1])

    Stderr Standard error output

    device

    #define stderr

    (&streams[2])Stdaux Standard auxiliarydevice

    #define stdaux(&streams[3])

    Stdprn Standard printer #define stdprn(&streams[4])

    Example:Write a program to enter text and display it using macroexpansions.

    #include#includevoid main()

    {char ch[12];int i;clrscr();printf(input a text:);for(i=0;i

  • 8/9/2019 Ecs C_prog Material

    82/126

    ispunct(d) d is a punctuationIsprint(d) d is a printable characterisgraph(d) d is a printable but not a spaceiscntrl(d) d is a control characterisascii(d) d is an ascii code

    DYNAMIC MEMORY ALLOCATION:

    C requires the number of elements to be specified at the compile

    time. Sometimes our initial judgement of the size of the arrays may be

    wrong (i.e) space may be wasted or more space will be required . To

    avoid such problems C allows the user to specify the size of the array

    at run time. This is called dynamic memory management. Thus the

    process of allocating memory at run time is known as dynamic memory

    allocation.C uses four library functions to support dynamic memory

    allocation. They are

    Malloc allocates requested size of bytes and returns a pointer tothe first byte of the allocated space.

    Calloc allocates space for an array, initializes them to zero andthen returns a pointer to the memory.

    Free frees previously allocated memory. Realloc modifies the size of the previously allocated array.

    Storage of a C program

    Stack

    Heap

  • 8/9/2019 Ecs C_prog Material

    83/126

    Permanent storage area

    The global variables and the instructions are stored in the

    permanent storage area. Local variables are stored in the stack. The

    free region is called the heap and is used for dynamic memory

    allocation. The heap keeps changing when the program is executed

    when the variables are created and destroyed. Therefore memory

    overflows can occur. In that case the memory allocation processes

    returns a NULL pointer to denote a failure to allocate the requested

    memory space.

    Malloc():

    A block of mamory can be allocated using malloc() function. This

    allocates a block of the specified size and returns a void pointer.

    Syntax:

    Example:

    X=(int *)malloc(100 * sizeof(int));

    This statement allocates a memory space equivalent to 100 times the

  • 8/9/2019 Ecs C_prog Material

    84/126

    size of an int and returns the address of the first byte to the pointer x.

    If the function cannot allocate memory it returns a NULL pointer.

    Calloc():

    Calloc() allocates multiple blocks of storage each of the same

    size and initializes them to 0.

    Syntax:

    Example:

    ..

    ..

    struct student

    {

    char name[25];

    float age;

    long int id;

    };

    typedef struct student record;

    record *st_ptr;

  • 8/9/2019 Ecs C_prog Material

    85/126

    int class=30;

    ..

    ..

    st_ptr=(record*)calloc(class,sizeof(record));

    Free():

    With dynamic allocation, the user has to release the memory

    when it is not used. This is important when the storage space is

    limited. The function Free() releases the memory.

    Syntax:

    Example:

    Free(p);

    Realloc():

    There are 2 cases when we require to realter the memory

    already allocated

    1. When the previously allocated memory is not sufficient and the userrequires additional space.2. When the memory allocated is larger and the user wishes to reduceit.In both the cases the memory size can be changed with the use of

  • 8/9/2019 Ecs C_prog Material

    86/126

    realloc().

    Syntax:

    This function allocates a new memory space of size new-size to

    the pointer variable ptr and returns a pointer to the first byte of the

    new memory block if the memory allocation operation is successful.

    The newsize may be smaller or larger than the original size. The

    realloc() function does not modify the original contents. If the function

    fails in allocating the required space, then it returns a NULL pointer

    and the origunal block is lost.

    Program:

    /*Program to access a 2 dimensional array using malloc()*/

    void main()

    {

    int *p[3], I, j,c;

    printf(Enter the no of cols\n,&c);

    p[0]=(int*)malloc(c*sizeof(int));

    p[1]=(int*)malloc(c*sizeof(int)); allocates space for c

    cols

  • 8/9/2019 Ecs C_prog Material

    87/126

    p[2]=(int*)malloc(c*sizeof(int));

    for(I=0;I

  • 8/9/2019 Ecs C_prog Material

    88/126

    How they are treated?91.Can the names of formal parameters coincide with actual

    parameters?92.Can multiple return statements be included in a function?93.What is a null statement? Explain its usefulness.

    94.Write the syntax of goto statement.95.Write the purpose of break and continue statement.96.Explain and give example for predefined functions.97.Write the disadvantages of using goto statement.98.Write the advantages of using user defined functions.99.In what way ,a switch statement differ from an if statement?100.Say true or false:

    when if statements are nested, the last else getsassociated with the nearest if without an else.

    One if can have more than one else clause. A switch statement can always be replaced by a series

    of if..else statements. A switch expression can be of any type A program stops its execution when a break statement

    is encountered.101.How the end of the string is recognized?102.Explain the need for array variables.103.Declaration int a[10][10] creates how many elements.104.What is the value returned by a strcmp() function?105.Define array.106.Identify errors,if any, in each of the following array declaration

    statements. Float values [10,13] Char name[ROW],[COLUMN];

    107.Identify errors ,if any ,in each of the following initializationstatements.

    Static int number[ ]={0,0,0,0,} Static char word[ ]={a,rr,r,y};

    108.Define string.109.Write the common operations performed on character strings.110.Write the purpose of getchar function.111.Write the purpose of putchar function.

    112.Write the function to convert the given string to integer .113.Which function is used to convert the given integer value tostring?

    114.Write any four string handling functions.115.Describe the limitations of using getchar and scanf functions for

    reading strings.116.What is recursive function?117.What happens when actual arguments are less than formal

  • 8/9/2019 Ecs C_prog Material

    89/126

    arguments in a function?118.What happens when data type of one of the actual arguments

    does not match with the type of the function.119.What happens when same variable is used in two different

    functions?

    120.Say true or false Function should be arranged in the order in which they

    are called. We can pass any number of arguments to a function. A function in c should have atleast one argument.

    121.What are the different storage classes?

    Section B

    122.Write short notes on functions123.Differentiate local and global variables124.Write short notes on different types of arguments

    125.Explain string handling functions in detail with examples.126.Write a program which will read a text and count all

    occurrences of a particular word.127.Explain the usage of break & continue statement128.Write short notes on conditional operatorWrite short notes

    on multidimensional arrays129.Write a program to search an element using linear search.130.Write a program to sort the given set elements using

    selection sort131.Write a program to arrange the given set of element using

    ascending order.

    132.Write a program to arrange the given set numbers indescending order.

    133.Write a program to add two given matrices of order m x n134.Explain about switch statement135.Distinguish between local and global variables136.Distinguish between formal and actual arguments.137.Distinguish between automatic and static variables.138.Distinguish between global and extern variables.139.Is the main user defined function? If yes means how it differs

    from the other user defined functions?140.Write a program to calculate npr using user defined function.

    141.Write a recursive program to generate fibonacci nubers142.Write shorts notes on auto storage class143.Explain about register & extern variables144.Write a recursive program to calculate the factorial of a

    given number.145.Write a program to find if a string is a palindrome or not.

    Section C

  • 8/9/2019 Ecs C_prog Material

    90/126

    146.Explain recursion with an example147.Explain about user defined functions148.Write a program to sort a set of numbers and to print

    minimum & maximumof the set

    149.Explain multidimentional arrays.150.Write a program to find sum of positive & negative realnumbers seperatelyfrom a given set of real numbers using continue and while

    statement151.Explain any 4 string functions with examples152.Discuss on different storage classes

    8. Write a program to print the set of names in alphabeticalorder

    9. Write a program