13878_C-Language (All Concepts)

download 13878_C-Language (All Concepts)

of 129

Transcript of 13878_C-Language (All Concepts)

  • 8/8/2019 13878_C-Language (All Concepts)

    1/129

    C Programming BasicsC Programming Basics Introduction to C Data types in C Variables Type conversions Standard input/output

    Arithmetic, relational, logical operators Header files and libraries Loops and decisions Scope of variables Strings

    Functions, call by value, call by reference Arrays Structures Unions

    Pointers Files

  • 8/8/2019 13878_C-Language (All Concepts)

    2/129

    History of CHistory of C--LanguageLanguage Developed by Dennis M.Ritchie and BrianDeveloped by Dennis M.Ritchie and Brian

    Kernighan of AT&T Bell Labs in 1972Kernighan of AT&T Bell Labs in 1972

    In 1983 the American National StandardsIn 1983 the American National StandardsInstitute began the standardisation processInstitute began the standardisation process

    In 1989 the International StandardsIn 1989 the International StandardsOrganisation continued the standardisationOrganisation continued the standardisation

    processprocess

    In 1990 a standard was finalised, knownIn 1990 a standard was finalised, knownsimply as Standard Csimply as Standard C

  • 8/8/2019 13878_C-Language (All Concepts)

    3/129

    Why teach C?Why teach C? C isC is smallsmall (only 32 keywords).(only 32 keywords).

    C isC is commoncommon (lots of C code about).(lots of C code about).

    C isC is stablestable (the language doesnt change much).(the language doesnt change much).

    C isC is quick runningquick running..

    C is theC is the basis for many other languagesbasis for many other languages (Java, C++,(Java, C++,

    awk, Perl).awk, Perl). It may not feel like it but C is one of the easiestIt may not feel like it but C is one of the easiest

    languages to learn.languages to learn.

    NOTE: Obviously programmers will find this courseNOTE: Obviously programmers will find this course

    easier than everyone else. BUT, this course is for noneasier than everyone else. BUT, this course is for non--programmers. If you cannot understand what I say,programmers. If you cannot understand what I say,please please ask me either in the lecture orplease please ask me either in the lecture orafterwards.afterwards.

  • 8/8/2019 13878_C-Language (All Concepts)

    4/129

    Why use C?Why use C? C is not "safe"C is not "safe"

    It assumes you know what you're doingIt assumes you know what you're doing

    It has a lot of scope for bugsIt has a lot of scope for bugs

    It's a good systems programmingIt's a good systems programminglanguagelanguage

    Not much is hiddenNot much is hidden Faster than Java, more predictableFaster than Java, more predictable

    performanceperformance

    It has all the lowIt has all the low--level operationslevel operations

  • 8/8/2019 13878_C-Language (All Concepts)

    5/129

    Strengths:

    C-Language

    Weaknesses:

    1. Efficiency

    2. Portability

    3. Power

    4. Flexibility

    5. Standard library

    6. Integration with UNIX

    1. C programs can be error-prone

    2. C programs can be difficult to understand

    3. C programs can be difficult to modify

  • 8/8/2019 13878_C-Language (All Concepts)

    6/129

    The Benefits And Pitfalls Of CThe Benefits And Pitfalls Of C

    BenefitsBenefits Its a powerful language (doesnt restrictIts a powerful language (doesnt restrict

    you)you)

    FastFastA practical language (real applications)A practical language (real applications)

    PitfallsPitfalls

    Its a powerful language (No programmerIts a powerful language (No programmerfailfail--safes)safes)

    Compiled code is not portableCompiled code is not portable

  • 8/8/2019 13878_C-Language (All Concepts)

    7/129

    Structured ProgrammingStructured Programming C, Pascal, Fortran areC, Pascal, Fortran are proceduralprocedural programming languages.programming languages. A program in a procedural language is a list of instructions,A program in a procedural language is a list of instructions,

    augmented with loops and branches.augmented with loops and branches.

    For small programs no other organizational principleFor small programs no other organizational principle(paradigm) is needed.(paradigm) is needed.

    Larger programs are broken down into smaller units.Larger programs are broken down into smaller units.

    A procedural program is divided intoA procedural program is divided into functionsfunctions, such that, such thatideally each has clearly defined purpose and interface toideally each has clearly defined purpose and interface toother functions.other functions.

    The idea of breaking a program into functions can beThe idea of breaking a program into functions can befurther extended by grouping functions that performfurther extended by grouping functions that performsimilar tasks intosimilar tasks into modulesmodules..

    Dividing a program into functions and modules is the keyDividing a program into functions and modules is the keyidea ofidea of structured programmingstructured programming..

  • 8/8/2019 13878_C-Language (All Concepts)

    8/129

    Compiling and Linking

    1. Preprocessing. The program is first given to a preprocessor,

    which obeys commands that begin with # (known as directives).

    #include (include the info in before compiling)

    test.c ---> (compiled) ---> test.obj (linked) ---> executable file

    2. Compiling. The modified program now goes to a compiler,which translates it into machine instructions (object code).

    3. Linking. A linker combines the object code produced by the

    compiler with any additional code needed to yield a complete

    executable program.

  • 8/8/2019 13878_C-Language (All Concepts)

    9/129

    Some programmer jargonSome programmer jargon

    Source code:Source code: The stuff you type into the computer. TheThe stuff you type into the computer. Theprogram you are writing.program you are writing.

    Compile (build):Compile (build): Taking source code and making a programTaking source code and making a programthat the computer can understand.that the computer can understand.

    Executable:Executable: The compiled program that the computer can run.The compiled program that the computer can run.

    Language:Language: (Special sense) The core part of C central to writing(Special sense) The core part of C central to writingC code.C code.

    Library:Library:Added functions for C programming which are bolted onAdded functions for C programming which are bolted on

    to do certain tasks.to do certain tasks. Header file:Header file: Files ending in .h which are included at the start ofFiles ending in .h which are included at the start of

    source code.source code.

  • 8/8/2019 13878_C-Language (All Concepts)

    10/129

    Contd.Contd.

    Compiler:Compiler: Translates program written in "source"Translates program written in "source"

    language to "target" languagelanguage to "target" language

    Interpreter:Interpreter: Translate and immediately executeTranslate and immediately execute

    Assembler:Assembler:

    Translate into machine language forTranslate into machine language forparticular machineparticular machine

    MacroProcessor:MacroProcessor:

    Textual substitutionsTextual substitutions

  • 8/8/2019 13878_C-Language (All Concepts)

    11/129

    Keywords

    In Standard C, the keywords in Table 2.1 have special significanceto the compiler and therefore can not be used as identifiers.

    Table 2.1 - Keywords

    auto double int struct

    break else long switch

    case enum register typedef

    char extern return union

    const float short unsignedcontinue for signed void

    default goto sizeof volatile

    do if static while

  • 8/8/2019 13878_C-Language (All Concepts)

    12/129

    The Format of CThe Format of C

    Statements are terminated with semicolonsStatements are terminated with semicolons Indentation is ignored by the compilerIndentation is ignored by the compiler

    C is case sensitiveC is case sensitive -- all keywords and Standardall keywords and StandardLibrary functions are lowercaseLibrary functions are lowercase

    Strings are placed in double quotesStrings are placed in double quotes

    Newlines are handled viaNewlines are handled via \\nn

    Programs are capable of flagging success orPrograms are capable of flagging success or

    error, those forgetting to do so have one orerror, those forgetting to do so have one orother chosenother chosen randomly!randomly!

  • 8/8/2019 13878_C-Language (All Concepts)

    13/129

    VariablesVariables

    Variables must be declared before useVariables must be declared before useimmediately after {immediately after {

    Valid characters are letters, digits and _Valid characters are letters, digits and _

    First character cannot be a digitFirst character cannot be a digit

    31 characters recognised for local variables31 characters recognised for local variables(more can be used, but are ignored)(more can be used, but are ignored)

    Some implementations recognise only 6Some implementations recognise only 6

    characters in global variables (and functioncharacters in global variables (and functionnames)!names)!

    Upper and lower case letters are distinctUpper and lower case letters are distinct

  • 8/8/2019 13878_C-Language (All Concepts)

    14/129

    printfprintf andandscanfscanfprintfprintf writeswrites integervalues to screen whenintegervalues to screen when%iisused%iisused

    scanfscanf readsreads integervalues from theintegervalues from the

    keyboardwhen %i isusedkeyboardwhen %i isused

    & VERY important with& VERY important with scanfscanf (required to(required tochangechange the parameter, this will bethe parameter, this will beinvestigated later)investigated later) -- absence will makeabsence will makeprogram very illprogram very ill

    & not necessary with& not necessary with printfprintf becausebecause

    current value of parameter is usedcurrent value of parameter is used

  • 8/8/2019 13878_C-Language (All Concepts)

    15/129

    The Basic Structure Of A C ProgramThe Basic Structure Of A C Program

    example_program.c

    int

    main ()

    {

    }

    Global variables

    Local variables

    /* Program documentation */

    #Preprocessor directives

    Function prototypes

    Function definitions

    Global constants

  • 8/8/2019 13878_C-Language (All Concepts)

    16/129

    Hello World ProgramHello World Program

    #include // input#include // input--output libraryoutput library

    int main()int main() // function main// function main

    {{

    printf(Hello Worldprintf(Hello World\\n); // send string to standard outputn); // send string to standard outputreturn 0;return 0;

    }}

    Compile the source file helloworld.c with the commandCompile the source file helloworld.c with the commandgcc helloworld.cgcc helloworld.c o helloworldo helloworld

  • 8/8/2019 13878_C-Language (All Concepts)

    17/129

    Hello World ProgramHello World Program#include #include

    includes the standard I/O library which allows you to read from theincludes the standard I/O library which allows you to read from thekeyboard (standard in) and write to the screen (standard out)keyboard (standard in) and write to the screen (standard out)

    int main()int main()

    declares the main function. Every Cdeclares the main function. Every C--program must have a functionprogram must have a functionnamed main somewhere in the codenamed main somewhere in the code

    { ... }{ ... }

    The symbols { and } mark the beginning and end of a block of code.The symbols { and } mark the beginning and end of a block of code.

    printf(Hello Worldprintf(Hello World\\n)n)

    Sends output to the screen. The portion in quotes ... is the formatSends output to the screen. The portion in quotes ... is the format

    strings and describes how the data is formatted.strings and describes how the data is formatted.return 0;return 0;

    This causes the function main to return an error code of 0 (no error)This causes the function main to return an error code of 0 (no error)to the shell that started the program.to the shell that started the program.

  • 8/8/2019 13878_C-Language (All Concepts)

    18/129

    Compilation & LinkingCompilation & Linking

    helloworld.cstdio.h

    #include

    helloworld.o

    helloworld

    header file

    compiler

    linker

    executable file

    object file

    source file

  • 8/8/2019 13878_C-Language (All Concepts)

    19/129

    Variable DeclarationVariable Declarationint b;int b;

    double x;double x;

    unsigned int a;unsigned int a;

    char c;char c;

    C is a typed language that means a variable has aC is a typed language that means a variable has a namename

    typetype

    C standard typesC standard types

    int, double, char, float, short, long, long doubleint, double, char, float, short, long, long double unsigned char, unsigned short, unsigned int,unsigned char, unsigned short, unsigned int,

    unsigned longunsigned long

  • 8/8/2019 13878_C-Language (All Concepts)

    20/129

    Primitive DataPrimitive Data--TypesTypes

    integer data-types :char, short, int, long, unsigned char, unsigned short,

    floating point data-types :

    float, double, long double character data-type :charcharacter constants in single quotes : a, \n

  • 8/8/2019 13878_C-Language (All Concepts)

    21/129

    Primitive DataPrimitive Data--TypesTypesTypeType LowLow HighHigh Digits of Digits of

    PrecisionPrecisionBytesBytes

    charchar --128128 127127 -- 11

    shortshort --3276832768 3276732767 -- 22intint --21474836482147483648 21474836472147483647 -- 22

    longlong --21474836482147483648 21474836472147483647 -- 44

    floatfloat 3.4x103.4x10--3838 3.4x103.4x103838 77 44

    doubledouble 1.7x101.7x10--308308 1.7x101.7x10308308 1515 88

    longlongdoubledouble

    3.4x103.4x10--49324932 3.4x103.4x1049324932 1919 1010

  • 8/8/2019 13878_C-Language (All Concepts)

    22/129

    Variable DefinitionsVariable Definitions

    int a;double x = 5.9;

    char answer = n;

    double y=x;

    A declaration introduces a variables name into aprogram and specifies its type A definition is a declaration which also sets asidesmemory for that variable (which is usually the case)

    In C it is possible to initialize a variable at the sametime it is defined, in the same way one assigns a valueto an already defined variable.

    Examples of variable definitions:

  • 8/8/2019 13878_C-Language (All Concepts)

    23/129

    ConstantsConstants constants can be specified using the preprocessordirective #define

    example:#define PI 3.14159

    the preprocessor replaces the identifier PI by the text

    3.14159 throughout the program the major drawback of #define is that the data type ofthe constant is not specified

    the preprocessor merely replaces all occurences of thestring PI with 3.14159

    CONVENTION: reserve CAPITAL letters for constants and usesmall caps for variables and functions

  • 8/8/2019 13878_C-Language (All Concepts)

    24/129

    CommentsComments comments are always a good thing to use because

    not everyone is as smart as you are and needs moreexplanation in order to understand your program

    you may not be as smart next month when you have

    to change your program comments should clarify your code and explain therational behind a group of statements

    comment syntax (C style) /* *//* this is a comment

    which can go across multiplelines of code */

  • 8/8/2019 13878_C-Language (All Concepts)

    25/129

    Type ConversionsType Conversions

    double pi=3.14;

    char c=x;

    C is a hard-typed language, meaning that each variable hasa fixed type that does not change and which determines thepossible assignments and applicable operators

    Some type conversions occur automatically for example intto float or float to double, but also char to intint i = 17;

    float x = i; /* assigns 17 to x */

    int j = 2;

    float y = i/j; /* assigns 17/2 = 8 to y not 8.5 */ Type conversions can be forced by a programmer througha type castfloat z = (float) i / j; /* casts i into float before division */

  • 8/8/2019 13878_C-Language (All Concepts)

    26/129

    Library FunctionsLibrary Functions Many functionalities in C are carried out by library functions. These functions perform file access, data conversion andmathematical computations.

    #include /* include header file for math functions */

    int main(){

    double x;

    double y;

    y=1.57;x=sin(y);

    }

  • 8/8/2019 13878_C-Language (All Concepts)

    27/129

    Header FilesHeader Files a header file contains the declaration of functions

    you want to use in your code the preprocessor directive #include takes care ofincorporating a header file into your source file

    example:#include

    #include myprog.h

    the brackets indicate that the compiler first searchesthe standard include directory which contains thestandard C header files first

    the quotation marks indicate that the compiler first searchesfor header files in the local directory if you do not include the appropriate header file

    you get an error message from the compiler

  • 8/8/2019 13878_C-Language (All Concepts)

    28/129

    Header and Library FilesHeader and Library Files

    myprog.cmath.h

    myprog.h

    #include

    #include myprog.h

    myprog.o

    myprog

    libm.a

    user header file

    compiler

    linker

    library header file

    library fileobject file

    executable file

  • 8/8/2019 13878_C-Language (All Concepts)

    29/129

    Input / OutputInput / Output/*Program for print the different data types*//*Program for print the different data types*/

    #include #include int main()int main()

    {{

    int a;int a;

    double x;double x;

    char c;char c;printf(Enter integer:);printf(Enter integer:);

    scanf(%d,&a);scanf(%d,&a);

    printf(printf(\\nEnter double:);nEnter double:);

    scanf(%lf,&x);scanf(%lf,&x);

    printf(printf(\\nEnter character:);nEnter character:);

    scanf(%c,&c);scanf(%c,&c);printf(printf(\\nThe value of a is %d, of x is %lf, of c is %cnThe value of a is %d, of x is %lf, of c is %c\\n,a,x,c);n,a,x,c);

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    30/129

    Input / OutputInput / Output A stream isan abstraction thatrefers to a flow of data.

    standardoutput

    device

    stdout variable aprintf(%d,a);

    standardinput

    device

    stdin variable ascanf(%d,&a);

  • 8/8/2019 13878_C-Language (All Concepts)

    31/129

    Input / OutputInput / Output

    printf allows you to send output to standard out (screen)printf allows you to send output to standard out (screen)

    The special character The special character \\n represents carriage return line feedn represents carriage return line feed The symbol %d is a placeholder for an integer variable in theThe symbol %d is a placeholder for an integer variable in the

    format stringformat string

    printf(the value of a is %dprintf(the value of a is %d\\n,a)n,a)

    that will be replaced by the value of the variable a when thethat will be replaced by the value of the variable a when the

    printf statement is executedprintf statement is executed Placeholders:Placeholders:

    integer %dinteger %d

    long %ldlong %ld

    float %ffloat %f

    double %lfdouble %lf

    char %cchar %c

    string %sstring %s

  • 8/8/2019 13878_C-Language (All Concepts)

    32/129

    Input / OutputInput / Output

    scanf allows you to read input from standard inscanf allows you to read input from standard in

    (keyboard)(keyboard) scanf uses the same placeholders as printfscanf uses the same placeholders as printf

    scanf (%d,&a)scanf (%d,&a)

    the program reads an integer value from thethe program reads an integer value from thekeyboard and places its value into the integerkeyboard and places its value into the integervariable avariable a

    Notice to put an & in front of the variable, theNotice to put an & in front of the variable, the

    reason becomes clear when you learn morereason becomes clear when you learn moreabout pointersabout pointers

  • 8/8/2019 13878_C-Language (All Concepts)

    33/129

    Arithmetic andIncrement OperatorsArithmetic andIncrement Operators

    int a=4;int a=4;int b=3;int b=3;

    b=b+a;b=b+a;

    b+=3; /* arithmetic assignment operator,b+=3; /* arithmetic assignment operator,same as b=b+3 */same as b=b+3 */

    a++; /* increment operator, same as a=a+1;a++; /* increment operator, same as a=a+1;

    */*/a=b++, /* postfix operator */a=b++, /* postfix operator */

    a=3 * ++b; /* prefix operator */a=3 * ++b; /* prefix operator */

  • 8/8/2019 13878_C-Language (All Concepts)

    34/129

    Arithmetic OperatorsArithmetic Operators

    multiplication, summation, subtraction, divisionint i = 1/3; /* integer division result 0 */float x = 1.0/3; /* floating point division result 0.3333 */

    int j = 7 % 3; // modulo operator remainder of 7/3

    prefix and postfix-increment operator ++

    int i=3;int j=7;

    printf(%d,10 * i++); /* outputs 30, i has value 4 afterwards */

    Printf(%d,10 * ++j); /* outputs 80, j has value 8 afterwards */

    arithmetic assignment operatorsfloat x=6.0;

    x+=3.5;

    is equivalent tox=x+3.5;

  • 8/8/2019 13878_C-Language (All Concepts)

    35/129

    Relational OperatorsRelational Operators

    In C there is no special boolean type. InsteadIn C there is no special boolean type. Insteadint is used for boolean expression with theint is used for boolean expression with theconvention that 0 is false, everything else isconvention that 0 is false, everything else istrue.true.

    Relational operatorsRelational operators > greater> greater < less< less >= greater or equal>= greater or equal

  • 8/8/2019 13878_C-Language (All Concepts)

    36/129

    Relational OperatorsRelational Operators

    a relational operator compares two values of primitivein data types such as char, int, float

    typical relationships are equal to, less than and greater than the result of a comparison is either true or false, where 0 is

    false and any value different from 0 is true C provides the following relational operators

    , ==, !=, = example:

    int x=44;int y=12;

    (x == y) /* false */

    (x >= y) /* true */

    (x != y) /* true */

  • 8/8/2019 13878_C-Language (All Concepts)

    37/129

    increment expression

    test expression

    initialization expression

    a loop causes a section of the program to be repeatedmultiple times while the loop condition remains true

    C knows three kinds of loops for loop

    while loop do loop the for loop repeats a code segment a fixed number of times the for statement contains three expressions usually

    refering to the same loop variable separated by semicolons

    LoopsLoops

    for ( i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    38/129

    For LoopFor Loop

    increment expressiontest expressioninitialization expression

    for ( i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    39/129

    For LoopFor Loop

    #include #include

    int main()int main()

    {{

    int a;int a;

    int i;int i;

    a=1;a=1;

    for (i=0;i

  • 8/8/2019 13878_C-Language (All Concepts)

    40/129

    For LoopFor Loopfor (i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    41/129

    For LoopFor Loop#include #include

    int main()int main()

    {{

    int number;int number;

    int i;int i;

    long fact;long fact;

    fact=1;fact=1;

    printf(Enter number:);printf(Enter number:);

    scanf(%d,&number);scanf(%d,&number);

    for (i=number; i>0; ifor (i=number; i>0; i----))fact*=i;fact*=i;

    printf(Factorial of %d is %ldprintf(Factorial of %d is %ld\\n,number,fact);n,number,fact);

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    42/129

    Indendation and Loop StyleIndendation and Loop Style it is good programming practice to indent loops there is some variation of the style used for loops

    whatever style you use do it consistently

    for (i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    43/129

    While / DoWhile / Do--While LoopWhile Loop

    while (a>b)while (a>b){{

    }}

    the body of the loop is executed as long as the testthe body of the loop is executed as long as the teststatement is true (possibly zero times)statement is true (possibly zero times)

    dodo

    {{

    } while (a>b);} while (a>b);

    the body of the loop is executed and then repeated asthe body of the loop is executed and then repeated aslong as the test statement is true (at least once)long as the test statement is true (at least once)

  • 8/8/2019 13878_C-Language (All Concepts)

    44/129

    While LoopWhile Looptest expressionwhile ( c != y )

    {

    }

    body of loop

    testexpression exit

    true

    false

  • 8/8/2019 13878_C-Language (All Concepts)

    45/129

    While LoopWhile Loop#include #include

    int main()int main()

    {{

    int number;int number;

    int i;int i;

    long factlong fact

    fact=1;fact=1;

    printf(Enter number:);printf(Enter number:);

    scanf(%d,&number);scanf(%d,&number);

    i=number;i=number;while (i>0)while (i>0)

    fact*=ifact*=i----;;

    printf(Factorial of %d is %ldprintf(Factorial of %d is %ld\\n,number,fact);n,number,fact);

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    46/129

    While LoopWhile Loop

    the while loop is used when the number of iterationsis unknown before the loop is started

    the while loop is repeated as long as the test expressionremains true

    char c=n;

    while ( c != y)

    {

    printf(Do you want to continue: (y/n)\n);scanf(%c,&c);

    }

  • 8/8/2019 13878_C-Language (All Concepts)

    47/129

    Do LoopDo Loop

    test expressiondo{ }

    while ( c != y );

    body of loop

    testexpression exit

    true

    false

  • 8/8/2019 13878_C-Language (All Concepts)

    48/129

    DoDo -- While LoopWhile Loop#include #include

    int main()int main()

    {{

    i=number;i=number;dodo

    {{

    fact*=ifact*=i----;;

    } while (i>0); /* do not forget the semicolon */} while (i>0); /* do not forget the semicolon */printf(Factorial of %d is %ldprintf(Factorial of %d is %ld\\n,number,fact);n,number,fact);

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    49/129

    Do LoopDo Loop

    in the do loop the test expression is evaluated at theend of the loop, therefore the body is executed atleast once

    char c;

    do

    {

    printf(Do you want to continue: (y/n)\n);

    scanf(%c,&c);}

    while ( c != y);

  • 8/8/2019 13878_C-Language (All Concepts)

    50/129

    If Else StatementIf Else Statement

    test expressionif ( x > 100){

    }

    else{

    }

    body of if

    testexpression

    exit

    true

    false

    body of else

  • 8/8/2019 13878_C-Language (All Concepts)

    51/129

    If Else StatementIf Else Statement

    depending on whether the test condition is true or falseeither the if or the else branch is executed

    int x;

    Printf(Enter a number: );Scanf(%d,&x);

    if ( x > 100)

    printf(%d is greater than 100\n,x);

    else

    printf(%d is smaller or equal than 100\n,x);

  • 8/8/2019 13878_C-Language (All Concepts)

    52/129

    IfElse StatementIfElse Statement#include #include int main()int main()

    {{

    int a,b;int a,b;

    scanf(%d %d,&a,&b);scanf(%d %d,&a,&b);if (a>b)if (a>b)

    printf(%d is larger than %dprintf(%d is larger than %d\\n,a,b);n,a,b);

    elseelse

    if (a==b)if (a==b)printf(%d is equal to %dprintf(%d is equal to %d\\n,a,b);n,a,b);

    elseelse

    printf(%d is smaller than %dprintf(%d is smaller than %d\\n,a,b);n,a,b);

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    53/129

    IfElse StatementIfElse Statement

    if (a>b)if (a>b){{

    }}

    elseelse

    {{

    }}

    the if part is executed if the test statement isthe if part is executed if the test statement istrue, otherwise the else part is executed.true, otherwise the else part is executed.

  • 8/8/2019 13878_C-Language (All Concepts)

    54/129

    Nested IfElse StatementNested IfElse Statementif (a>b)if (a>b){{

    if (b>c)if (b>c)

    printf(sorted = %d %d %dprintf(sorted = %d %d %d\\n,a,b,c);n,a,b,c);

    elseelse

    if (a>c)if (a>c)

    printf(sorted = %d %d %dprintf(sorted = %d %d %d\\n,a,c,b);n,a,c,b);

    elseelse

    printf(sorted = %d %d %dprintf(sorted = %d %d %d\\n,c,a,b);n,c,a,b);

    }}

    elseelse

    {{if (a>c)if (a>c)

    printf(sorted = %d %d %dprintf(sorted = %d %d %d\\n,b,a,c);n,b,a,c);

    elseelse

  • 8/8/2019 13878_C-Language (All Concepts)

    55/129

    Logical OperatorsLogical Operators

    logical and : &&(x >= 5) && ( x

    if (alpha < beta)min = alpha;

    else

    min = beta;

    min = (alpha

  • 8/8/2019 13878_C-Language (All Concepts)

    56/129

    Switch StatementSwitch Statement

    variableequalsconst 1

    exit

    true

    false

    first case body

    variableequals

    const 2

    true

    false

    second case body

    default body

  • 8/8/2019 13878_C-Language (All Concepts)

    57/129

    Switch StatementSwitch Statement the switch statement is used if there are more thantwo alternatives and the decision depends on the valueof the same variable

    the switch statement can replace a ladder of multiplenested if..else statements

    switch()

    {

    case :

    break;case :

    break;

    default :

    }

  • 8/8/2019 13878_C-Language (All Concepts)

    58/129

    Switch StatementSwitch Statement

    char c;

    printf(Enter your choice (a/b/c) : );

    Scanf(%c,&c);

    switch (c)

    {

    case a:printf(You picked a!\n);

    break;

    case b:

    printf(You picked a!\n);

    break;

    case c:

    printf(You picked a!\n);

    break;

    default:

    printf(You picked neither a,b,c !\n);

    }

  • 8/8/2019 13878_C-Language (All Concepts)

    59/129

    Scope of VariablesScope of Variables a block is a section of code delimited by a pair

    of brackets { }

    a declaration introduces a variable into a scope( a specific part of program text)

    the scope of a variable is the block within whichthe variable is declared

    a variable declared outside a function is global.

    a declaration of a variable in an inner block can hidea declaration in an enclosing block or a global variable

  • 8/8/2019 13878_C-Language (All Concepts)

    60/129

    lifetime of outer i

    visibility of outer i

    Scope of VariablesScope of Variables

    int i; /* global variable */

    int main()

    {int i=3; /* local variable */

    {

    int j=5; /* local variable */

    int i=7; /* local i hides outer i */

    printf(%d\n i); /* outputs 7 */} /* end of scope of j and inner i */

    printf(%d\n i); /* outputs 3 */

    } /* end of scope of outer i */

  • 8/8/2019 13878_C-Language (All Concepts)

    61/129

    CharactersCharacters

    TypeType charchar

    Characters are small integers (0Characters are small integers (0--255)255)

    Character constants are integers thatCharacter constants are integers thatdenote corresponding charactersdenote corresponding characters

    '0','1','A','B','a','b',''0','1','A','B','a','b','\\nn

    ''

    ASCII code maps characters to integersASCII code maps characters to integers

  • 8/8/2019 13878_C-Language (All Concepts)

    62/129

    ASCII CodeASCII Code

    00 11 22 33 44 55 66 77 88 99

    4848 4949 5050 5151 5252 5353 5454 5555 5656 5757

    AA BB CC DD EE FF GG HH II JJ

    6565 6666 6767 6868 6969 7070 7171 7272 7373 7474

    aa bb cc dd ee ff gg hh ii jj

    9797 9898 9999 100100 101101 102102 103103 104104 105105 106106

    NULLNULL((\\0)0)

    BELBEL((\\g)g)

    TABTAB((\\t)t)

    NEWLINENEWLINE((\\n)n)

    SPACESPACE

    00 77 99 1010 3232

    S iS i

  • 8/8/2019 13878_C-Language (All Concepts)

    63/129

    StringsStrings

    String is collection of Characters (or )String is collection of Characters (or )group of elements.group of elements.

    Character arrays that are NULLCharacter arrays that are NULL

    terminated.terminated.ExampleExample

    char arr[4] = hi;char arr[4] = hi;

    hh i i NULNULLL

    ??

    [0] [1] [2] [3]

  • 8/8/2019 13878_C-Language (All Concepts)

    64/129

    StringsStrings

    Two interpretationsTwo interpretations Arrays whose elements are charactersArrays whose elements are characters

    Pointers pointing to charactersPointers pointing to characters

    Strings are always terminated with a NULLStrings are always terminated with a NULLcharacter ('character ('\\0' or 0)0' or 0)

    char a[]="hellochar a[]="hello\\n"; /* size? */n"; /* size? */

    char* b=hellochar* b=hello\\n;n;

    olleh \n null

    *b

    111108108101104 10 0

    *(b+1) *(b+2) *(b+3) *(b+4) *(b+5) *(b+6)a[0] a[1] a[2] a[3] a[4] a[5] a[6]

  • 8/8/2019 13878_C-Language (All Concepts)

    65/129

    String InitializationString Initialization

    InitializationInitialization

    char m[char m[99] = I like C;] = I like C;

    char m[ ] = I like C;char m[ ] = I like C;

    char m[] = { I, , l, i, k, e, ,C };char m[] = { I, , l, i, k, e, ,C };

    I l i k e C \0

    m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7] m[8]

  • 8/8/2019 13878_C-Language (All Concepts)

    66/129

    char s[char s[3030] = "c programming "; // ok, preferred] = "c programming "; // ok, preferred

    char s[char s[3030] = {"c programming "}; // ok, redundant] = {"c programming "}; // ok, redundant

    char s[char s[3030] = {c programming }; // illegal] = {c programming }; // illegalchar s[char s[3030] = {c,p,i};] = {c,p,i}; // illegal// illegal

    char s[char s[3030] = {S',I',I',T'}; // ok, inconvenient] = {S',I',I',T'}; // ok, inconvenient

    char string_var[char string_var[3030];]; // ok, not initialize// ok, not initialize

    char* s = c++; //s[char* s = c++; //s[00]=c,s[]=c,s[11]=+,s[]=+,s[22]=+, s[]=+, s[33]=]=00; // ok, initialize; // ok, initializechar str[char str[2020] = Initial value; // ok, initialize] = Initial value; // ok, initialize

    tI n i i

    va l a \0l u e ?

    ?? ? ? ?

    Null character

    String InitializationString Initialization

  • 8/8/2019 13878_C-Language (All Concepts)

    67/129

    Null is the end of itNull is the end of it

    #include #include

    #include #include

    #include #include

    #include #include

    int main()int main()

    {{

    char x[ ];char x[ ];

    strcpy(x,"Snoopy is not a cat");strcpy(x,"Snoopy is not a cat");

    x[x[1111] = '] = '\\00';';

    printf("x = %s",x);printf("x = %s",x);

    getch();getch();

    }}

  • 8/8/2019 13878_C-Language (All Concepts)

    68/129

    char s[char s[55]="SIIT";]="SIIT";

    char dept[char dept[55], *d=dept;], *d=dept;

    char name[char name[2020]];;

    name = name = Peter PanPeter Pan"";;

    strcpy(name,strcpy(name,Peter PanPeter Pan")");;strcpy(dept,"IT");strcpy(dept,"IT");

    printf("%s %s %sprintf("%s %s %s\\n",d,s,dept);n",d,s,dept);

    d = strcpy(s,"EE");d = strcpy(s,"EE");

    printf("%s %s %s %sprintf("%s %s %s %s\\n",name,d,s,dept);n",name,d,s,dept);

    char cchar c11[[3030], c], c22[[3030]=This is new c]=This is new c11 string;string;

    char s[char s[3030] = "c programming ";] = "c programming ";char strchar str11[[3030]];;

    char *str;char *str;

    strcpy(cstrcpy(c11, c, c22));;

    str = strcat(s,"is great!!");str = strcat(s,"is great!!");

    strstr11 = strcat(s,"is great!!");= strcat(s,"is great!!");

    Make sure that you haveMake sure that you have

    enough memory space toenough memory space to

    assign the string,assign the string,

    otherwise some chars willotherwise some chars will

    be lost.be lost.

    String AssignmentString Assignment

  • 8/8/2019 13878_C-Language (All Concepts)

    69/129

    InIn--Class ExampleClass Example

    void main()void main()

    {{ char first[100], last[100];char first[100], last[100];

    int i;int i;

    strcpy(first,"Peter");strcpy(first,"Peter");

    sprintf(last, "Pan");sprintf(last, "Pan");

    printf("my name is %s, %sprintf("my name is %s, %s\\n", last, first);n", last, first);

    for (i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    70/129

    FunctionsFunctions

    a function groups a number of program statementsinto a unit and gives it a name

    the function can be invoked from other parts of the program dividing a program into functions is one way to structure

    your program (structured programming)

    a function declaration specifies the name of the functionthe type of the value returned and the number andtype of arguments that must be supplied in a call ofthe function

    a function definition contains the body of the function

    typically function declarations take place in header files (.h)whereas the function definitions are stored in sourcefiles (.c)

    h i f ih i f i

  • 8/8/2019 13878_C-Language (All Concepts)

    71/129

    What is a function?What is a function?

    TheThe functionfunction is one of the most basic thingsis one of the most basic thingsto understand in C programming.to understand in C programming.

    AA functionfunction is a subis a sub--unit of a program whichunit of a program whichperforms a specific task.performs a specific task.

    We have already (without knowing it) seen

    We have already (without knowing it) seenone function from the C libraryone function from the C library printf.printf.

    We need to learn to write our own functions.We need to learn to write our own functions.

    Functions takeFunctions take argumentsarguments (variables) and(variables) and

    may return anmay return an argument.argument. Think of a function as extending the CThink of a function as extending the C

    language to a new task.language to a new task.

    A l f tiA l f ti

  • 8/8/2019 13878_C-Language (All Concepts)

    72/129

    An example functionAn example function#include

    int maximum (int, int); /* Prototype see later in lecture */

    int main(int argc, char*argv[]){

    int i= 4;int j= 5;

    int k;k= maximum (i,j); /* Call maximum function */

    printf ("%d is the largest from %d and %d \n",k,i,j);printf ("%d is the largest from %d and %d \n",maximum(3,5), 3, 5);return 0;

    }

    int maximum (int a, int b)/* Return the largest integer */

    {

    if (a > b)return a; /* Return means "I am the result of the function"*/

    return b; /* exit the function with this result */}

    Prototype the function

    Call the function

    The function itself

    function header

  • 8/8/2019 13878_C-Language (All Concepts)

    73/129

    Factorial program (and thoughts)Factorial program (and thoughts)int main()

    {

    int number=4;

    int answer;

    int count;

    answer=1;count= number;

    while (count >=0) {

    answer=answer* count;

    count--;

    }

    printf ("%d!=%d\n",

    number,answer);

    return 0;

    }

    number=4

    answer=1

    count=4

    enter whileloop

    answer=1*4=4

    count=3

    enter whileloopanswer=4*3=12

    count=2

    enter whileloop

    answer=12*2=24

    count=1

    enter whileloop

    answer=24*1=24

    count=0

    enter whileloop

    answer=24*0=0

  • 8/8/2019 13878_C-Language (All Concepts)

    74/129

    FunctionsFunctions

    int fac(int n); /* function declaration */

    int x=7;

    printf(fac(%d)=%d\n,x, fac(x)); /* call function fac()*/

    int fac(int n) /* function definition */

    {

    int i;

    int result=1;for (i=1; i

  • 8/8/2019 13878_C-Language (All Concepts)

    75/129

    FunctionsFunctions

    int pow(int a, int b); /* function declaration */

    int a=3;

    Int b=4;

    printf(%d ^ %d =%d\n,a,b,pow(a,b)); /* call function fac()*/

    int pow(int a, int b) /* function definition */

    {

    int result=1;

    int i;for (i=1; i

  • 8/8/2019 13878_C-Language (All Concepts)

    76/129

    Pointers are variables that containPointers are variables that contain memorymemory addressesaddresses

    as their values.as their values.

    A variable nameA variable name directlydirectly references a value.references a value.

    A pointerA pointer indirectlyindirectly references a value. Referencing areferences a value. Referencing avalue through a pointer is calledvalue through a pointer is calledindirectionindirection..

    A pointer variable must be declaredbefore it can beA pointer variable must be declaredbefore it can be

    used.used.

    POINTERSPOINTERS

    POINTERSPOINTERS

  • 8/8/2019 13878_C-Language (All Concepts)

    77/129

    POINTERSPOINTERS

    A pointer is an address of a storage locationA pointer is an address of a storage location

    By convention, zero represents the "null"By convention, zero represents the "null"pointerpointer

    A pointer is a number, and must itself beA pointer is a number, and must itself be

    storedstored The size of a pointer depends on the amountThe size of a pointer depends on the amount

    of memory to be addressedof memory to be addressed

    A 16A 16--bit pointer can address 64K locationsbit pointer can address 64K locations

    A 32A 32--bit pointer can address 4 trillionbit pointer can address 4 trillionlocationslocations

    POINTERSPOINTERS

  • 8/8/2019 13878_C-Language (All Concepts)

    78/129

    POINTERSPOINTERS Examples of pointer declarations:Examples of pointer declarations:

    intint *a*a;;

    floatfloat*b*b;;

    charchar *c*c;;

    TheThe asteriskasterisk, when used as above in the declaration,, when used as above in the declaration,tells the compiler that the variable is to be a pointer,tells the compiler that the variable is to be a pointer,and the type of data that the pointer points to, butand the type of data that the pointer points to, butNOTNOT the name of the variable pointed to.the name of the variable pointed to.

    PointersPointers

  • 8/8/2019 13878_C-Language (All Concepts)

    79/129

    PointersPointers

    Each variable in a program occupies a part ofEach variable in a program occupies a part ofthe computers memory, for example anthe computers memory, for example aninteger variable occupies 2 bytes of memoryinteger variable occupies 2 bytes of memory

    The location of the piece of memory used toThe location of the piece of memory used to

    store a variable is called the address of thatstore a variable is called the address of thatvariablevariable

    An address is some kind of number similar toAn address is some kind of number similar to

    house numbers in a street that is used tohouse numbers in a street that is used tolocate the information stored in thatlocate the information stored in thatparticular variableparticular variable

  • 8/8/2019 13878_C-Language (All Concepts)

    80/129

    PointersPointers

    Pointers are used to:Pointers are used to: Access array elementsAccess array elements

    Passing arguments to functions when thePassing arguments to functions when the

    function needs to modify the original argumentfunction needs to modify the original argument Passing arrays and strings to functionsPassing arrays and strings to functions

    Obtaining memory from the systemObtaining memory from the system

    Creating data structures such as linked listsCreating data structures such as linked lists

  • 8/8/2019 13878_C-Language (All Concepts)

    81/129

    Use of & and *Use of & and * When is & used?When is & used?

    When is * used?When is * used?

    && ---- "address operator" which gives or produces the"address operator" which gives or produces thememory address of a data variablememory address of a data variable

    ** ---- "dereferencing operator" which provides the"dereferencing operator" which provides thecontents in the memory location specified by a pointercontents in the memory location specified by a pointer

    /*Program to swap the values of two variables in memory/*Program to swap the values of two variables in memory

  • 8/8/2019 13878_C-Language (All Concepts)

    82/129

    #include#includevoid exchange(int*,int*)void exchange(int*,int*)int main()int main(){{ int a,b;int a,b;

    pf(Enter values of a and b); sf(%d%d&a,&b);pf(Enter values of a and b); sf(%d%d&a,&b);pf(Before exchange a=%d b=%d,a,b);pf(Before exchange a=%d b=%d,a,b);

    exchange(&a,&b); pf(After exchange a=%d b=%d,a,b);exchange(&a,&b); pf(After exchange a=%d b=%d,a,b);return 0;return 0;

    }}void exchange(int *aptr, int *bptr)void exchange(int *aptr, int *bptr){{ int temp;int temp;

    temp=*aptr;temp=*aptr;

    *aptr=*bptr;*aptr=*bptr;*bptr=temp;*bptr=temp;

    }}

    POINTER VARIABLESPOINTER VARIABLES

  • 8/8/2019 13878_C-Language (All Concepts)

    83/129

    POINTER VARIABLESPOINTER VARIABLES A pointer variable is a variable that holds address valuesA pointer variable is a variable that holds address values

    Each data type has its own pointer variable, pointer toEach data type has its own pointer variable, pointer tointint, pointer to, pointer to doubledouble, pointer to, pointer to charchar, ,

    C uses theC uses the addressaddress--ofof operator& to get the address ofoperator& to get the address ofan variablean variable

    C uses theC uses the indirectionindirection oror contentscontents--ofof operator* tooperator* toaccess the value of the variable pointedbyaccess the value of the variable pointedby

    int i=17;int i=17;

    int* ptr; /* defines a pointer variable for integer variables */int* ptr; /* defines a pointer variable for integer variables */

    ptr= &i; /* assign the address of i to pointer */ptr= &i; /* assign the address of i to pointer */printf(the value of i can be printed as %d or %dprintf(the value of i can be printed as %d or %d\\n, *ptr, i);n, *ptr, i);

    printf(the address of i is %dprintf(the address of i is %d\\n, ptr);n, ptr);

  • 8/8/2019 13878_C-Language (All Concepts)

    84/129

    Pointer VariablesPointer Variables

    0x1054int i;

    17int *ptr;

    ptr=&i;

    printf(value of i = %d\n,*ptr);

  • 8/8/2019 13878_C-Language (All Concepts)

    85/129

    Pointer VariablesPointer Variables

    int v; // defines variable v of type intint v; // defines variable v of type int

    int w; // defines variable w of type intint w; // defines variable w of type int

    int *p; // defines variable p of type pointer to intint *p; // defines variable p of type pointer to int

    p=&v; // assigns address of v to pointer pp=&v; // assigns address of v to pointer p

    v=3; // assigns value 3 to vv=3; // assigns value 3 to v

    *p=7; // assigns value 7 to v*p=7; // assigns value 7 to v

    p=&w; // assigns address of w to pointer pp=&w; // assigns address of w to pointer p

    *p=12; // assigns value 12 to w*p=12; // assigns value 12 to w

    Using the indirection operator *p to access theUsing the indirection operator *p to access thecontents of a variable is calledcontents of a variable is called indirect addressingindirect addressing

    oror dereferencingdereferencing the pointerthe pointer

  • 8/8/2019 13878_C-Language (All Concepts)

    86/129

    PassPassbyby--ValueValue

    when passing arguments by value, the function createsnew local variables to hold the values of the variableargument

    the value of the original variable are not changed

    void f(int val) /* the parameter val holds a local copy of thevariable argument */

    {

    val++;

    }

    int x=4;

    f(x); /* call function f passing x by value */

    printf(x=%d\n,x); /* x still has the value 4 */

    Pointers as Function ArgumentsPointers as Function Arguments

  • 8/8/2019 13878_C-Language (All Concepts)

    87/129

    Pointers as Function ArgumentsPointers as Function Arguments

    C offers two different ways to pass arguments to aC offers two different ways to pass arguments to a

    functionfunction by value : void f(int x);by value : void f(int x);

    by reference : void f(int* x);by reference : void f(int* x);

    In passIn pass--byby--value the function obtains only a localvalue the function obtains only a local

    copy of the variable, so that changes to the localcopy of the variable, so that changes to the localvariable have no impact on the argument with whichvariable have no impact on the argument with whichthe function was invokedthe function was invoked

    In passIn pass--byby--reference the function manipulates thereference the function manipulates theoriginal variable rather than merely its copyoriginal variable rather than merely its copy

    PassPass--byby--ReferenceReference

  • 8/8/2019 13878_C-Language (All Concepts)

    88/129

    yy

    void swap( double* ptr1, double* ptr2)void swap( double* ptr1, double* ptr2){{double tmp=*ptr1;double tmp=*ptr1;*ptr1=*ptr2; /* de*ptr1=*ptr2; /* de--referencing pointer */referencing pointer */*ptr2=tmp;*ptr2=tmp;

    }}

    int main()int main(){{double a=3.0;double a=3.0;double b=5.0double b=5.0swap(&a, &b); /* call by reference using the addresses of a and b */swap(&a, &b); /* call by reference using the addresses of a and b */printf(a=%lf, b=%lfprintf(a=%lf, b=%lf\\n,a,b);n,a,b);

    }}

    */Factorial of a given number using pointers*/*/Factorial of a given number using pointers*/

  • 8/8/2019 13878_C-Language (All Concepts)

    89/129

    g g pg g p

    main()main()

    {{ int n,factorial;int n,factorial;printf(enter a number);printf(enter a number);scanf(%d,&n);scanf(%d,&n);factcompute(n,&factorial);factcompute(n,&factorial);printf(the factorial of %d,n,factorial);printf(the factorial of %d,n,factorial);

    }}factcompute(a,b)factcompute(a,b)int a,*b;int a,*b;{{

    int m; *b=1;int m; *b=1;for(m=1;m

  • 8/8/2019 13878_C-Language (All Concepts)

    90/129

    ArraysArrays

    The idea of an array is to group similarThe idea of an array is to group similarobjects into units.objects into units.

    Arrays are structures that group itemsArrays are structures that group items

    of the same data type.of the same data type.

    The elements of an array are accessedThe elements of an array are accessedby an index number that allows randomby an index number that allows random

    access.access.

  • 8/8/2019 13878_C-Language (All Concepts)

    91/129

    ArraysArrays

    int poweroftwo[10]; /*array definition */int poweroftwo[10]; /*array definition */

    int poweroftwo[0]=1; /* first element hasint poweroftwo[0]=1; /* first element has

    index number 0 */index number 0 */

    int i;int i;

    for (i=1;i

  • 8/8/2019 13878_C-Language (All Concepts)

    92/129

    ArraysArrays

    double avg(int sz, double array[]); /* function definition*/double avg(int sz, double array[]); /* function definition*/

    double x[5]={1.2, 2.5, 1.7, 4.2, 3.9} /* initialize array */double x[5]={1.2, 2.5, 1.7, 4.2, 3.9} /* initialize array */

    printf(average is %lfprintf(average is %lf\\n,avg(5,x));n,avg(5,x));

    double avg(int sz, double array[])double avg(int sz, double array[]){{

    int i;int i;

    double sum;double sum;

    for (i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    93/129

    MultiMulti--Dimensional ArraysDimensional Arrays

    #define ROWS 5#define ROWS 5#define COLS 6#define COLS 6

    double matrix[ROWS][COLS];double matrix[ROWS][COLS];

    double a[COLS];double a[COLS];

    double b[ROWS];double b[ROWS];

    int i,j;int i,j;

    for(i=0;i

  • 8/8/2019 13878_C-Language (All Concepts)

    94/129

    an array */an array */ #include#include

    #define MAXSIZE 100#define MAXSIZE 100main()main(){{

    int n,I,max=0,elements[MAXSIZE];int n,I,max=0,elements[MAXSIZE];printf(enter the no of elements);printf(enter the no of elements);scanf(%d,&n);scanf(%d,&n);

    for(i=0, i

  • 8/8/2019 13878_C-Language (All Concepts)

    95/129

    Arrays in PointersArrays in Pointers Array indexing is syntactic sugar for pointersArray indexing is syntactic sugar for pointers

    a[i]a[i] is treated asis treated as *(a+i)*(a+i) To zero out an array:To zero out an array:

    for (i = 0; i < size; i++)a[i] = 0;for (i = 0; i < size; i++)a[i] = 0;

    for (i = 0; i < size; i++)*(a+i) = 0;for (i = 0; i < size; i++)*(a+i) = 0;

    for (p = a; P < a+size; p++)*p = 0;for (p = a; P < a+size; p++)*p = 0;

    BecauseBecause a[i]a[i] meansmeans *(a+i),i[a]*(a+i),i[a]is equally legal!is equally legal!

    Pointers and ArraysPointers and Arrays

  • 8/8/2019 13878_C-Language (All Concepts)

    96/129

    Pointers and ArraysPointers and Arrays There is a close association between pointers and arraysThere is a close association between pointers and arrays

    Arrays can be accessed using pointersArrays can be accessed using pointers The name of an array is also a constant pointer to the dataThe name of an array is also a constant pointer to the data

    type of the elements stored in the arraytype of the elements stored in the array

    int array[5] = { 23, 5, 12, 34, 17 }; /* array of 5 ints */int array[5] = { 23, 5, 12, 34, 17 }; /* array of 5 ints */

    for (int i=0; i

  • 8/8/2019 13878_C-Language (All Concepts)

    97/129

    Arrays and StringsArrays and Strings In C there is no particular type for strings.In C there is no particular type for strings.

    Instead strings are stored in arrays of typeInstead strings are stored in arrays of typecharacter.character.

    #include #include

    char lastname[256]=Hansen;char lastname[256]=Hansen;char firstname[256]=Ole;char firstname[256]=Ole;

    char fullname[512];char fullname[512];

    strcpy(fullname,firstname);strcpy(fullname,firstname);

    strcat(fullname, );strcat(fullname, );strcat(fullname,lastname);strcat(fullname,lastname);

    printf(full name is %sprintf(full name is %s\\n,fullname);n,fullname);

    StructuresStructures

  • 8/8/2019 13878_C-Language (All Concepts)

    98/129

    StructuresStructures A structure is a collection of simple variables, that can be ofA structure is a collection of simple variables, that can be of

    different type.different type.

    The data items in a structure are called members of the structure.The data items in a structure are called members of the structure.

    struct complex /* structure declaration */struct complex /* structure declaration */

    {{

    double re; /* members of the structure */double re; /* members of the structure */

    double im;double im;

    };};

    complex mult(struct complex a, struct complex b);complex mult(struct complex a, struct complex b);

    struct complex a,b,c; /* variable declaration of type complex */struct complex a,b,c; /* variable declaration of type complex */

    a.re=2.0; /* accessing members of struct complex */a.re=2.0; /* accessing members of struct complex */

    a.im=1.5;a.im=1.5;

    b.re=2.3;b.re=2.3;

    b.im=b.im=--1.8;1.8;

    c=mult(a,b);c=mult(a,b);

    C StructuresC Structures

  • 8/8/2019 13878_C-Language (All Concepts)

    99/129

    C StructuresC Structures Collection of related variables under one nameCollection of related variables under one name

    Derived data typesDerived data types Variables declared within the braces of the structureVariables declared within the braces of the structure

    definition are the members of the structuredefinition are the members of the structure Members of the same structure type must haveMembers of the same structure type must have

    unique namesunique names

    Two different structure types can contain members ofTwo different structure types can contain members ofthe same name without conflictthe same name without conflict

    struct card {struct card {int face;int face;

    char suit[20];char suit[20];};};

    struct card aCard, deck[52], *cardPtr;struct card aCard, deck[52], *cardPtr;

    StructuresStructures

  • 8/8/2019 13878_C-Language (All Concepts)

    100/129

    StructuresStructures Structures are collections of variables ofStructures are collections of variables of

    different types, as in the followingdifferent types, as in the followingexample.example.

    struct abc

    {

    int a;

    long b;

    char c;}

    MyStruct;

    Structure

    Definition

    variable

    declaration

    StructureType

    Name

    d id i

  • 8/8/2019 13878_C-Language (All Concepts)

    101/129

    C Structures and FunctionsC Structures and Functions

    struct point makepoint(struct point pt, int x, int y) {struct point makepoint(struct point pt, int x, int y) {

    pt.x = x;pt.x = x;

    pt.y = y;pt.y = y;

    return pt;return pt;

    }}

    int main() {int main() {

    struct point pt;struct point pt;

    pt = makepoint (pt, 5, 6);pt = makepoint (pt, 5, 6);printf(pt.x = %d pt.y = %dprintf(pt.x = %d pt.y = %d\\n, pt.x, pt.y);n, pt.x, pt.y);

    }}

    C S d iC S d i

  • 8/8/2019 13878_C-Language (All Concepts)

    102/129

    C Structures and FunctionsC Structures and Functions

    void makepoint(struct point *pt, int x, int y) {void makepoint(struct point *pt, int x, int y) {

    ptpt-->x = x;>x = x;

    ptpt-->y = y;>y = y;

    }}

    int main() {int main() {

    struct point pt;struct point pt;

    makepoint (&pt, 5, 6);makepoint (&pt, 5, 6);

    printf(pt.x = %d pt.y = %dprintf(pt.x = %d pt.y = %d\\n, pt.x, pt.y);n, pt.x, pt.y);

    }}

    For very large structures, pass the pointer to it!For very large structures, pass the pointer to it!

  • 8/8/2019 13878_C-Language (All Concepts)

    103/129

    /*Program to display the month names of both dates*//*Program to display the month names of both dates*/ Struct mydateStruct mydate

    {{ int yyyy;int yyyy;int mmdd;int mmdd;};};main()main(){{ struct mydate date1,date2;struct mydate date1,date2;

    int month1,month2;int month1,month2;

    char *months[]={ ,jan,feb,mar,.dec};char *months[]={ ,jan,feb,mar,.dec};pf(enter first date(mmdd)); sf(%d,&date1.mmdd);pf(enter first date(mmdd)); sf(%d,&date1.mmdd);

    pf(enter second date(mmdd)); sf(%d,&date2.mmdd);pf(enter second date(mmdd)); sf(%d,&date2.mmdd);month1month1--date1.mmdd/100;month2=date2.mmdd/100;//take month alonedate1.mmdd/100;month2=date2.mmdd/100;//take month alonepf(firstt month is %s,months[month1];pf(firstt month is %s,months[month1];

    pf(second month is %s,months[month2]);pf(second month is %s,months[month2]);}}

  • 8/8/2019 13878_C-Language (All Concepts)

    104/129

    /*Program to illustrate the use of structure pointer/*Program to illustrate the use of structure pointer

    Struct currencyStruct currency{{ int rupees;int rupees;

    int paise;int paise;};};main()main(){{ struct currency mycurr={123,25};struct currency mycurr={123,25};

    showit(&mycurr);showit(&mycurr);}}showit(struct currency *myptr)showit(struct currency *myptr)

    {{ pf(rupees %d,%d,myptrpf(rupees %d,%d,myptrrupees,myptrrupees,myptrpaise);paise);}}

    U iU i

  • 8/8/2019 13878_C-Language (All Concepts)

    105/129

    UnionsUnions

    Unions look similar to structures. They have identicalUnions look similar to structures. They have identicaldeclaration syntax and member access, but they serve adeclaration syntax and member access, but they serve avery different purpose.very different purpose.

    union Utype {union Utype {

    int ival;int ival;float fval;float fval;

    char *sval;char *sval;

    };};

    u

    nion Utype x, y, z;u

    nion Utype x, y, z;

    Accessing members of a union is via Accessing members of a union is via .. member operator member operatoror, for pointers to unions, theor, for pointers to unions, the -->> operator.operator.

    U iU i

  • 8/8/2019 13878_C-Language (All Concepts)

    106/129

    UnionsUnions

    A union holds the value of oneA union holds the value of one--variable at a time.variable at a time.

    The compiler allocates storage for theThe compiler allocates storage for the biggestbiggestmember of the union.member of the union.

    The type retrieved from the union must be the typeThe type retrieved from the union must be the typemost recently stored. Otherwise, the result ismost recently stored. Otherwise, the result isimplementation dependent.implementation dependent.

    union Utype x;union Utype x;

    x.fval = 56.4;x.fval = 56.4; /* x holds type float. *//* x holds type float. */printf("%fprintf("%f\\n", x.fval); /* OK. */n", x.fval); /* OK. */

    printf("%dprintf("%d\\n", x.ival); /* Implementationn", x.ival); /* Implementation

    dependent. */dependent. */

    U iU i

  • 8/8/2019 13878_C-Language (All Concepts)

    107/129

    UnionsUnions

    Unions are used to store one of a set of different types.Unions are used to store one of a set of different types.

    Commonly used to implement a variant array. (This isCommonly used to implement a variant array. (This isa form of generic programming.)a form of generic programming.)

    There are other uses also, but they are quite advancedThere are other uses also, but they are quite advanced(e.g., concern the alignment properties of unions).(e.g., concern the alignment properties of unions).

    /* Write a c/* Write a c--program for student marksprogram for student marks

  • 8/8/2019 13878_C-Language (All Concepts)

    108/129

    p gp gusing an array of structures */using an array of structures */

    struct marksstruct marks{{ int sub1; int sub2;int sub1; int sub2;

    int sub3; int total;int sub3; int total; };};

    main()main()

    {{ int i;int i;

    static struct marks student[3]={static struct marks student[3]={{56,45,65},{56,45,65},

    {59,55,75},45,65,75}};{59,55,75},45,65,75}};

    static struct marks total;static struct marks total;

    for(i=0;i

  • 8/8/2019 13878_C-Language (All Concepts)

    109/129

    printf(STUDENTprintf(STUDENT TOTAL);TOTAL);for(i=0;i

  • 8/8/2019 13878_C-Language (All Concepts)

    110/129

    File Input In CFile Input In C

    C program

    FILE

    The C type, FILE allows for a consistent approach to input

    regardless of the actual physical device

    Default: stdin

    Fil O t t I CFil O t t I C

  • 8/8/2019 13878_C-Language (All Concepts)

    111/129

    File Output In CFile Output In C

    C program

    FILE

    Similar to file input, the C type FILE allows for a consistent

    approach to output regardless of the actual physical device

    stream

    Default: stdout

    D l i g FILE V i blD l i g FILE V i bl

  • 8/8/2019 13878_C-Language (All Concepts)

    112/129

    Declaring a FILE VariableDeclaring a FILE Variable

    Format:Format: FILE *;

    Example:Example: FILE *fp;FILE *fp;

    Be sure to include the followingBe sure to include the following

    preprocessors:preprocessors: #include #include #include #include

    Opening FilesOpening Files

  • 8/8/2019 13878_C-Language (All Concepts)

    113/129

    Opening FilesOpening Files

    Format:Format:

    FILE * fopen (const char * filename, const char *FILE * fopen (const char * filename, const char *mode);mode);

    Example:Example:

    fp = fopen (data, r);fp = fopen (data, r);

    fp = fopen (/home/profs/tamj/data, r);fp = fopen (/home/profs/tamj/data, r);

    ErrorconditionsErrorconditions File does not exist.File does not exist.

    Insufficient permissions to open the file.Insufficient permissions to open the file.

    Opening Files (2)Opening Files (2)

  • 8/8/2019 13878_C-Language (All Concepts)

    114/129

    p g ( )p g ( ) FilenameFilename

    Must reside in the same directory as C programMust reside in the same directory as C programbeing runbeing run

    Alternatively you can include the path to the fileAlternatively you can include the path to the file

    Some File open modesSome File open modes

    ModeMode Effect Effect

    rr Open text file for readingOpen text file for reading

    ww Open text file for writingOpen text file for writing

    aa Open text file for writing, start writing atOpen text file for writing, start writing atthe endthe end

    r+r+ Open file for reading and writingOpen file for reading and writing

    w+w+ Open file for writing and readingOpen file for writing and reading

    Closing FilesClosing Files

  • 8/8/2019 13878_C-Language (All Concepts)

    115/129

    Closing FilesClosing Files Disassociates the file with the physical deviceDisassociates the file with the physical device

    Remaining contents of the stream a flushedRemaining contents of the stream a flushed

    Format:Format:

    int fclose (FILE * fp);int fclose (FILE * fp);

    Example:Example:

    fclose(fp);fclose(fp);

    Writing ToA File fprintfWriting ToA File fprintf

  • 8/8/2019 13878_C-Language (All Concepts)

    116/129

    Format:Format:

    fprintf (FILE *fp, const char *control_string,fprintf (FILE *fp, const char *control_string,arguments);arguments);

    Example:Example:

    char arr[8] = hiya;char arr[8] = hiya;

    fprintf(fp, %s, arr);fprintf(fp, %s, arr);

    Similar to printf except you can also write to a file otherSimilar to printf except you can also write to a file other

    than the screen (standard out).than the screen (standard out).

    Reading From A File fscanfReading From A File fscanf

  • 8/8/2019 13878_C-Language (All Concepts)

    117/129

    Format:Format:

    fscanf (FILE *fp, ,fscanf (FILE *fp, ,addresses);addresses);

    Example:Example: char arr[8];char arr[8];

    fscanf (fp, %s, chunk);fscanf (fp, %s, chunk);

    Similar to scanf except you can also read from aSimilar to scanf except you can also read from afile other than the keyboard (standard in)file other than the keyboard (standard in)

    Reading From A File fgetsReading From A File fgets

  • 8/8/2019 13878_C-Language (All Concepts)

    118/129

    Reading From A File fgetsReading From A File fgets

    Format:Format:

    fgets(char *line, int n, FILE *fp);fgets(char *line, int n, FILE *fp);

    Example:Example:

    fgets(chunk, 80, fp);fgets(chunk, 80, fp);

    File I/O: First ExampleFile I/O: First Example

  • 8/8/2019 13878_C-Language (All Concepts)

    119/129

    The full example can be found in CThe full example can be found in C::

    #include #include #include #include int const LENGTH = 80;int const LENGTH = 80;main ()main (){{

    FILE *fp_in, *fp_out ;FILE *fp_in, *fp_out ; char arr[LENGTH];char arr[LENGTH]; char fn_in [LENGTH];char fn_in [LENGTH]; char fn_out [LENGTH];char fn_out [LENGTH];

    printf("Enter name of input file: ");printf("Enter name of input file: "); scanf("%s", fn_in);scanf("%s", fn_in); printf("Enter name of output file: ");printf("Enter name of output file: "); scanf("%s", fn_out);scanf("%s", fn_out);

    File I/O: First Example (2)File I/O: First Example (2)

  • 8/8/2019 13878_C-Language (All Concepts)

    120/129

    fp_in = fopen(fn_in, "r");fp_in = fopen(fn_in, "r"); fp_out = fopen(fn_out, "w");fp_out = fopen(fn_out, "w");

    if (!fp_in)if (!fp_in) {{ printf("Can't open input fileprintf("Can't open input file\\n");n"); return(return(--1);1); }}

    if (!fp_out)if (!fp_out) {{ printf("Can't open output fileprintf("Can't open output file\\n");n"); return(return(--1);1); }}

    File I/O: First Example (3)File I/O: First Example (3)

  • 8/8/2019 13878_C-Language (All Concepts)

    121/129

    File I/O: First Example (3)File I/O: First Example (3)

    while (feof(fp_in) == 0)while (feof(fp_in) == 0)

    {{

    // Using fscanf it stops scanning at whitespace// Using fscanf it stops scanning at whitespace

    fscanf(fp_in, "%s", arr);fscanf(fp_in, "%s", arr);

    fprintf(fp_out, "%sfprintf(fp_out, "%s--", arr);", arr);

    }}

    return(0);return(0);

    }}

    File I/O: Second ExampleFile I/O: Second Example

  • 8/8/2019 13878_C-Language (All Concepts)

    122/129

    This example is identical to the first example except for theThis example is identical to the first example except for theloop:loop:

    while (feof(fp_in) == 0)while (feof(fp_in) == 0)

    {{

    // Grabs whole line up 79 characters or the end// Grabs whole line up 79 characters or the end--ofof--filefile(whichever comes first)(whichever comes first)

    fgets (arr, 80, fp_in);fgets (arr, 80, fp_in);

    // Writes out to output file as// Writes out to output file as--is.is.

    fprintf (fp_out, "%s", arr);fprintf (fp_out, "%s", arr);

    }}

    File I/O: Third ExampleFile I/O: Third Example

  • 8/8/2019 13878_C-Language (All Concepts)

    123/129

    #include #include

    #include #include

    int const LENGTH = 80;int const LENGTH = 80;

    main ()main ()

    {{ FILE *fp_in;FILE *fp_in;

    char arr[LENGTH];char arr[LENGTH];

    char fn_in [LENGTH];char fn_in [LENGTH];

    printf("Enter name of input file: ");printf("Enter name of input file: ");

    scanf("%s", fn_in);scanf("%s", fn_in);

    File I/O: Third Example (2)File I/O: Third Example (2)

  • 8/8/2019 13878_C-Language (All Concepts)

    124/129

    fp_in = fopen(fn_in, "r");fp_in = fopen(fn_in, "r"); if (!fp_in)if (!fp_in) {{ printf("Can't open input fileprintf("Can't open input file\\n");n"); return(return(--1);1); }}

    while (feof(fp_in) == 0)while (feof(fp_in) == 0) {{ // Grabs whole line up 79 characters or the end// Grabs whole line up 79 characters or the end--ofof--filefile fgets(arr, 80, fp_in);fgets(arr, 80, fp_in);

    // Writes out to output file as// Writes out to output file as--is. Output file is the screenis. Output file is the screen fprintf(fprintf(stdoutstdout, "%s", arr);, "%s", arr); }} return(0);return(0); }}

    /* Write a program to detect error while opening a file that/* Write a program to detect error while opening a file thatdoes not exist.*/does not exist.*/

  • 8/8/2019 13878_C-Language (All Concepts)

    125/129

    #include#includemain()main()

    {{ char *filename;char *filename;FILE *fp1,*fp2;FILE *fp1,*fp2;int i, number;int i, number;fp1=fopen(TEST,w);fp1=fopen(TEST,w);for(i=10;i

  • 8/8/2019 13878_C-Language (All Concepts)

    126/129

    elseelse

    for(i=1;i

  • 8/8/2019 13878_C-Language (All Concepts)

    127/129

    It is the process of calling of a function by itself. The functionwhich calls itself is known as recursive function.

    EXAMPLE: TO CALCUALTE FACTORIAL OF A NUMBER

    int factorial(int);void main(){

    int num,f;printf(enter number whose factorial is to be

    calculated);scanf(%d,&num);f=factorial(num);

    printf(%d,f);}

    Contd

    int factorial(int x)

  • 8/8/2019 13878_C-Language (All Concepts)

    128/129

    int factorial(int x){

    if(x==1)return 1;elsereturn x*factorial(x-1);}

  • 8/8/2019 13878_C-Language (All Concepts)

    129/129

    THANX