2.io functions

Upload: dilkhushmeena

Post on 03-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 2.IO Functions

    1/45

    Hello World

    include

    /* The simplest C Program */

    int main(int argc, char **argv)

    {

    printf

    Hello World

    \

    n);

    return 0;

    }

    The main() function is always

    where your program starts

    running.

    #include inserts another file. .h files are called header

    files. They contain stuff needed to interface to libraries and

    code in other .c files.

    This is a comment. The compiler ignores this.

    Blocks of code (lexical scopes)

    are marked by -

    Print out a message. \n means new line.Return 0 from this function

    What do the < >

    mean?

    Can your program have

    more than one .c file?

  • 8/11/2019 2.IO Functions

    2/45

    Compilerinclude

    /* The simplest C Program */

    int main(int argc, char **argv)

    {

    printfHello World\n);

    return 0;

    }

    my_program

    __extension__ typedef unsigned long long int __dev_t;

    __extension__ typedef unsigned int __uid_t;

    __extension__ typedef unsigned int __gid_t;

    __extension__ typedef unsigned long int __ino_t;

    __extension__ typedef unsigned long long int __ino64_t;

    __extension__ typedef unsigned int __nlink_t;

    __extension__ typedef long int __off_t;

    __extension__ typedef long long int __off64_t;

    extern void flockfile (FILE *__stream) ;

    extern int ftrylockfile (FILE *__stream) ;

    extern void funlockfile (FILE *__stream) ;

    int main(int argc, char **argv)

    {

    printf Hello World\n);

    return 0;

    }

    Compilation occurs in two steps:Preprocessing and Compiling

    In Preprocessing, source code is expanded into a

    larger form that is simpler for the compiler to

    understand. Any line that starts with # is a line that isinterpreted by the Preprocessor.

    Include files are pasted in (#include)

    Macros are expanded (#define)

    Comments are stripped out ( /* */ , // )

    Continued lines are joined ( \ )

    Preprocess

    Compile

    The compiler then converts the resulting text into

    binary code the CPU can run directly.

    \ ?

    Why ?

  • 8/11/2019 2.IO Functions

    3/45

    Lexical ScopingEvery Variableis Definedwithin some scope. A

    Variable cannot be referenced by name (a.k.a.Symbol) from outside of that scope.

    The scope of Function Arguments is thecomplete body of the function.

    void p(char x)

    {

    /* p,x*/

    char y;

    /* p,x,y*/

    char z;

    /* p,x,y,z*/

    }

    /* p*/

    char z;

    /* p,z*/

    void q(char a)

    {

    char b;

    /* p,z,q,a,b*/

    {

    char c;

    /* p,z,q,a,b,c*/

    }

    char d;

    /* p,z,q,a,b,d(not c)*/

    }

    /* p,z,q*/

    (Returns nothing)

    The scope of Variables defined inside a

    function starts at the definition and ends at the

    closing brace of the containing block

    Lexical scopes are defined with curly braces { }.

    The scope of Variables defined outside a

    function starts at the definition and ends at the

    end of the file. Called Global Vars.

    legal?

    char b?

  • 8/11/2019 2.IO Functions

    4/45

    User Defined Data Declarationtypedef is used to define new data type names to make a program more readable to

    the programmer.

    typedef type identifier

    Example: typedef int unites units batch1, batch2;typedef float marks marksname1[10];

    #define preprocessor

    The #define preprocessor allows us to define symbolic names and constants.

    Example: #define PI3.14159 Ittranslate every occurrence of PI to 3.14159.

  • 8/11/2019 2.IO Functions

    5/45

    Macros

    Macros are built on the #define preprocessor.

    #define SQUARE(x) x*x

    Macros define an expression.

    After preprocessing the code would become:

    enumIt allows you to define a list of aliases which represent integer numbers.

    enumis closely related to the #define. E.g., if you find yourself coding something like:

    #define MON 1

    #define TUE 2#define WED 3

    You could use enumas:

    enumweek{ Mon=1, Tue, Wed, Thu, Fri Sat, Sun} days;

  • 8/11/2019 2.IO Functions

    6/45

    An advantage of enumover #define is that it has scope. This means that the variable (just like

    any other) is only visible within the block it was declared within.

    If a variable is defined with enum , it is considered by the compiler to be an integer, and can

    have ANY integer value assigned to it, it is not restricted to the values in the enum.

  • 8/11/2019 2.IO Functions

    7/45

    The const keyword

    The constkeyword is used to create a read only variable.

    Once initialized, the value of the variable cannot be changed but can be used just like any

    other variable

    The constkeyword is used as a qualifier to the following data types

    Int , float, char , double

  • 8/11/2019 2.IO Functions

    8/45

    C Storage ClassesC has a concept of 'Storage classes' which are used to define the scope (visibility) and life

    time of variables and/or functions.

    auto- storage class

    auto is the default storage class for local variables.{

    intCount;

    autointMonth;

    }

    It defines two variables with the same storage class. auto

    can only be used within functions, i.e. local variables

    register- Storage Classregisteris used to define local variables that should be stored in a register instead of RAM.

    This means that the variable has a maximum size equal to the register size (usually one

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

    location).

    {registerint Miles;

    }

    Register should only be used for variables that require quickaccess - such as counters.

    Defining registerdoes not mean that the variable will be

    stored in a register.

    It means that it MIGHT be stored in a register - depending on

    hardware and implementation restrictions.

  • 8/11/2019 2.IO Functions

    9/45

    static - Storage Classstaticis the default storage class for global variables.

    The two variables below (count and road) both have a static storage class.

    staticintCount;

    intRoad;

    main()

    {

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

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

    }

    staticcan also be defined within a function.

    If this is done, the variable is initialized at compilation time and retains its value between calls.

    Because it is initialized at compilation time, the initialization value must be a constant.

    void Func(void){

    static Count=1;

    }

  • 8/11/2019 2.IO Functions

    10/45

    void func1(void);

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

    main()

    {

    while (count--) func1();

    }

    void func1(void)

    {

    /* 'thingy' is local to 'func1' - it is only initialized at run time. Its value is NOT reset on

    every invocation of 'func1 /

    static thingy=5;

    thingy++;

    printf(" thingy is %d and count is %d\n", thingy, count);

    }

    /**************************************************************************

    Program )/P looks like this:

    thingy is 6 and count is 9

    thingy is 7 and count is 8

    thingy is 8 and count is 7thingy is 9 and count is 6

    thingy is 10 and count is 5

    thingy is 11 and count is 4

    thingy is 12 and count is 3

    thingy is 13 and count is 2

    thingy is 14 and count is 1

    thingy is 15 and count is 0

    **************************************************************************

  • 8/11/2019 2.IO Functions

    11/45

    extern - Storage Class

    externdefines a global variable that is visible to ALL object modules.

    When you use externthe variable cannot be initialized, as all it does is point the variable

    name at a storage location that has been previously defined

    Source 1 Source 2

    externint count; int count=5;

    write() main()

    { {

    printf("count is %d\n", count); write();

    } }

    Count in 'source 1' will have a value of 5. If source 1 changes the value of count - source 2

    will see the new value.

    void write_extern(void);

    extern int count;

    void write_extern(void)

    {

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

    }

    int count=5;

    main()

    {write_extern();

    }

    The compile command will look something like.

    gcc source1.c source2.c -o program

    staticand externvariables are automatically

    initialized to zero.

    autovariables contain undefined values

    (garbage) unless initialized explicitly.

  • 8/11/2019 2.IO Functions

    12/45

    Input/Output Operations

    Input operation

    an instruction that copies data from an input

    device into memory

    Output operation

    an instruction that displays information stored in

    memory to the output devices (such as themonitor screen)

  • 8/11/2019 2.IO Functions

    13/45

    Input/Output Functions

    A C function that performs an input or output

    operation

    A few functions that are pre-defined in the

    header file stdio.h such as :

    printf()

    scanf()

    getchar() & putchar()

  • 8/11/2019 2.IO Functions

    14/45

    The printf function

    Used to send data to the standard output (usuallythe monitor) to be printed according to specificformat.

    General format: printf(string literal);

    A sequence of any number of characters surrounded bydouble quotation marks.

    printf(format string, variables); Format string is a combination of text, conversion

    specifier and escape sequence.

  • 8/11/2019 2.IO Functions

    15/45

    The printf function cont

    Example:

    printf(Thank you);

    printf (Total sum is: %d\n, sum);

    %d is a placeholder (conversion specifier)

    marks the display position for a type integer variable

    \n is an escape sequence

    moves the cursor to the new line

  • 8/11/2019 2.IO Functions

    16/45

    Escape Sequence

    Escape Sequence Effect

    \a Beep sound

    \b Backspace

    \f Formfeed (for printing)

    \n New line\r Carriage return

    \t Tab

    \v Vertical tab

    \\ Backslash

    \ sign\o Octal decimal

    \x Hexadecimal

    \O NULL

  • 8/11/2019 2.IO Functions

    17/45

    The scanf function

    Read data from the standard input device(usually keyboard) and store it in a variable.

    General format: scanf(Format string, &variable);

    Notice ampersand (&) operator :

    C address of operator

    it passes the address of the variable instead of thevariable itself tells the scanf() where to find the variable to store

    the new value

  • 8/11/2019 2.IO Functions

    18/45

    The scanf function cont

    Example :int age;

    printf(Enter your age: );

    scanf(%d, &age);

    Common Conversion Identifier used in printf andscanf functions.

    printf scanf

    int %d %d

    float %f %f

    double %f %lf

    char %c %c

    string %s %s

  • 8/11/2019 2.IO Functions

    19/45

  • 8/11/2019 2.IO Functions

    20/45

    getchar() and putchar()

    getchar() - read a character from standard

    input

    putchar() - write a character to standard

    output

    Example:

    #include

    void main(void)

    {

    char my_char;

    printf(Please type a character: );

    my_char = getchar();printf(\nYou have typed this character: );

    putchar(my_char);

    }

  • 8/11/2019 2.IO Functions

    21/45

    getchar() and putchar() cont

    Alternatively, you can write the previous code

    using normal scanf and %c placeholder.

    Example#include

    void main(void)

    {

    char my_char;

    printf(Please type a character: );

    scanf(%c,&my_char);printf(\nYou have typed this character: %c , my_char);

    }

  • 8/11/2019 2.IO Functions

    22/45

    Few notes on C program cont

    Punctuators (separators)

    Symbols used to separate different parts of the C

    program.

    These punctuators include:

    * + ( ) - , ; : #

    Usage example:void main (void)

    {

    int num = 10;

    printf (%d,num);

    }

  • 8/11/2019 2.IO Functions

    23/45

    Few notes on C program cont

    Operators

    Tokens that result in some kind of computation or

    action when applied to variables or other

    elements in an expression.

    Example of operators:

    * + = - /

    Usage example: result = total1 + total2;

  • 8/11/2019 2.IO Functions

    24/45

    Basic C Operators

    Arithmetic operators

    Unary operators

    Binary operators

    Assignment operators Equalities and relational operators

    Logical operators

    Conditional operator

  • 8/11/2019 2.IO Functions

    25/45

    Arithmetic Operators I

    In C, we have the following operators (notethat all these example are using 9as the value

    of its first operand)

  • 8/11/2019 2.IO Functions

    26/45

    Equality and Relational Operators

    Equality Operators:Operator Example Meaning

    == x == y x is equal to y

    != x != y x is not equal to y

    Relational Operators:Operator Example Meaning

    > x > y x is greater than y

    < x < y x is less than y>= x >= y x is greater than or equal to y

  • 8/11/2019 2.IO Functions

    27/45

    Selection Structure

    In selection structure, the program is executed basedupon the given condition.

    Only instructions that satisfy the given condition areexecuted.

    There are 3 types of selection structure:

    if

    One alternative

    ifelse

    Two alternatives

    nested if..else Multiple alternatives

    switch

    Multiple alternatives

  • 8/11/2019 2.IO Functions

    28/45

    Selection structure: if

    Syntax :if (condition)

    Statement;

    The statement is only executed if the condition is satisfied.

    Example:

    if (score >= 60)

    printf(Pass!!\n);

    In the example above, the word Pass!! will only be printed out ifscoreis larger than or equal to 60. If not, the word Pass!! will notbe printed out and the program will continue with the nextstatement.

    A condition is an expression thatcan return trueor false(usually

    involving the use of an operator).

    Note that there is no semicolon (;) afterthe ifstatement. If there is one, that means

    the ifstatement and the printf()statement

    are 2 different statements and they will

    both get executed sequentially.

  • 8/11/2019 2.IO Functions

    29/45

  • 8/11/2019 2.IO Functions

    30/45

    Nested if elsestatements

    A nested ifelsestatement is an ifelsestatement with anotherifelsestatements inside it.

    Example :if (score >= 90)

    printf(A\n);

    else if (score >= 80)printf(B\n);

    else if (score >= 70)

    printf(C\n);

    else if (score >= 60)

    printf(D\n)

    elseprintf(F\n);

    The else ifstatement means that if the above condition is not

    satisfied, then try checking this condition.If any one of the condition is

    already satisfied, then ignore the rest of the available conditions

  • 8/11/2019 2.IO Functions

    31/45

    Plurality of Statements In the examples that we have seen so far, there is only one statement

    to be executed after the ifstatement.

    If we want to execute more than one statement after the condition issatisfied, we have to put curly braces { }around those statements totell the compiler that they are a part of the ifstatement, making it aCompound Statement

    Example

    if (score >= 90){

    printf(You have done very well\n);printf(Ill give you a present\n);

    }else if (score >= 60){

    printf(You have passed the course\n);printf(Sorry No present from for you\n);printf(Go and celebrate on your own\n);

    }

    h l l

  • 8/11/2019 2.IO Functions

    32/45

    Repetition : whileloop

    Syntax :while (condition)

    statement;

    As long as the condition is met (the condition expression

    returns true), the statement inside the whileloop will always

    get executed.

    When the condition is no longer met (the conditionexpression returns false), the program will continue on with

    the next instruction (the one after the whileloop).

    Example:

    int total = 0;while (total < 5)

    {

    printf(Total = %d\n, total);

    total++;

    }

    Similar as in the ifstatement, the condition

    is an expression that can return trueor

    false.

  • 8/11/2019 2.IO Functions

    33/45

    Repetition : whileloop cont

    In this example :

    (total < 5)is known as loop repetition condition

    (counter-controlled)

    totalis the loop counter variable

    In this case, this loop will keep on looping until the

    counter variable is = 4. Once total = 5, the loop

    will terminate

  • 8/11/2019 2.IO Functions

    34/45

    Repetition : whileloop cont

    Theprintf()statement will get executed as long as

    the variable totalis less than 5. Since the variable

    total is incremented each time the loop is

    executed, the loop will stop after the 5th output.

    Output:

    Total = 0

    Total = 1

    Total = 2

    Total = 3

    Total = 4

  • 8/11/2019 2.IO Functions

    35/45

    Infinite loop

    If somehow the program never goes out of theloop, the program is said to be stuck in aninfinite loop.

    The infinite loop error happens because thecondition expression of the while loop alwaysreturn a true.

    If an infinite loop occurs, the program wouldnever terminate and the user would have toterminate the program by force.

  • 8/11/2019 2.IO Functions

    36/45

    Repetition : do whileloop

    Syntax

    do {

    statement;

    }while(condition);

    A dowhileloop is pretty much the same as the whileloop exceptthat the condition is checked after the first execution of thestatement has been made.

    When there is a dowhileloop, the statement(s) inside it will beexecuted once no matter what. Only after that the condition will bechecked to decide whether the loop should be executed again orjust continue with the rest of the program.

  • 8/11/2019 2.IO Functions

    37/45

    do whileloop cont

    Let us consider the following program:

    int total = 10;

    while (total < 10)

    {printf(Total = %d\n, total);total++;

    }printf(Bye..);

    What does this program do?

    The program will only print the word Bye... The statementsinside the while loop will never be executed since the conditionis already not satisfied when it is time for the whileloop to get

    executed.

  • 8/11/2019 2.IO Functions

    38/45

    do whileloop cont

    Now consider the following program:int total = 10;

    do {printf(Total = %d\n, total);total++;

    } while (total < 10)

    printf(Bye..);

    Compared to the previous one, what will the output be?

    The program will get an output:

    Total = 10

    Bye..

    because the condition is not checked at the beginning of the loop.

    Therefore the statements inside the loop get executed once.

  • 8/11/2019 2.IO Functions

    39/45

    Repetition :forloop

    Syntax :

    for (expression1; expression2; expression3)

    statement;

    Expression1: initialize the controlling variable Expression2: the loop condition

    Expression3: changes that would be done to the

    controlling variable at the end of each loop.

    Note that each expression is separated by a

    semicolon (;)

  • 8/11/2019 2.IO Functions

    40/45

    forloop - example

    Example:int total;

    for (total = 0; total < 5; total++)printf(Total = %d\n, total);

    Output:Total = 0

    Total = 1

    Total = 2Total = 3

    Total = 4

  • 8/11/2019 2.IO Functions

    41/45

    forloop cont

    Notice that the output is the same as the one for the while

    loop example. In fact, the two examples are exactly

    equivalent. Using aforloop is just another way of writing a

    whileloop that uses a controlling variable.

    It is also possibleto omitone or more of theforloop

    expressions. In such a case, we just put the semicolon without

    the expression.

    int total= 0;for (; total < 5; total++)

    printf(Total = %d\n, total);

  • 8/11/2019 2.IO Functions

    42/45

    continueand breakstatement

    Both of these statements are used to modify the program flowwhen a selection structureor a repetition structureis used.

    The breakstatement is used to break out of selection or repetitionstructure. For example:

    for (a = 0; a < 5; a++){

    if (a == 2) break;

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

    }

    The output of this example would be:a = 0a = 1

  • 8/11/2019 2.IO Functions

    43/45

    continueand breakstatement

    When a= 2, the program will break out of theforloop

    due to the breakstatement. This will effectively

    terminate the loop. It will not wait till the value of a

    reaches 5 before terminating the loop.

    The continuestatement is used to ignore the rest of the

    statements in the loop and continue with the next loop.

  • 8/11/2019 2.IO Functions

    44/45

    continueand breakstatement

    Example:

    for (a = 0; a < 5; a++)

    {

    if (a == 2) continue;

    printf(a = %d\n, a);}

    Output:

    a = 0

    a = 1

    a = 3

    a = 4

  • 8/11/2019 2.IO Functions

    45/45

    continueand breakstatement

    a = 2 is not printed out because the loop skips theprintf()

    function when the continuestatement is encountered.

    In a whileand dowhilestructure, the loop condition will

    be checked as soon as the continuestatement isencountered to determine whether the loop will be

    continued .

    In aforloop, any modification to the controlling variable

    will be done before the condition is checked.