Lecture 0405

download Lecture 0405

of 61

Transcript of Lecture 0405

  • 8/19/2019 Lecture 0405

    1/61

    Lecture 04Chapter 2: Overview of C programming(cont..)

  • 8/19/2019 Lecture 0405

    2/61

    Basic Data Types int used to declare numeric program variables of integer type

    whole numbers, positive and negative

    keyword: intint number;

     number = 12; Type of int format

  • 8/19/2019 Lecture 0405

    3/61

    Basic Data Types cont… float

    fractional parts, positive and negative

    keyword: floatfloat height;

    height = 1.72;

  • 8/19/2019 Lecture 0405

    4/61

    Basic Data Types

    sign exponent mantissa

  • 8/19/2019 Lecture 0405

    5/61

    Basic Data Types cont…

    Type Range in Typical Microprocessor

    Implementation

     s ort − , .. ,

    unsigned short 0 .. 65,535

    int −2,147,483,648 .. 2,147,483,647

    unsigned 0 .. 4,294,967,295

    long −2,147,483,648 .. 2,147,483,647unsigned long 0 .. 4,294,967,295

  • 8/19/2019 Lecture 0405

    6/61

    Basic Data Types cont… char equivalent to ‘letters’ in English language

    Example of characters: Numeric digits: 0 - 9

    Lowercase/uppercase letters: a - z and A - Z

    S ace blank

    Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc single character keyword: char

    char my_letter;

    my_letter = 'U'; The declared character must beenclosed within a single quote!

  • 8/19/2019 Lecture 0405

    7/61

    ASCII Code

    American Standard Code for Information Interchange

    particular code that specifies the integer representing each charvalue.

    The digit characters '0' through '9' have code values of 48 through

    57 (decimal). uppercase letters have the decimal code values 65 through 90

    Lowercase letters have the decimal code values 97 through 122

    the printable characters have codes from 32 (code for a blank orspace) to 126 (code for the symbol ~ ).

  • 8/19/2019 Lecture 0405

    8/61

    ASCII Code Table

  • 8/19/2019 Lecture 0405

    9/61

    Extended ASCII Code Table

  • 8/19/2019 Lecture 0405

    10/61

    Constant example – volume of a cone#include

    int main(void)

    {double height, radius, base, volume;

    double pi = 3.14;

    printf(“Enter the height and radius of the cone:”);

     scanf(“%lf %lf”,&height, &radius);

    base = pi * radius * radius;

    volume = (1.0/3.0) * base * height;

    printf(“\nThe volume of a cone is %lf ”, volume);

    return 0;

    }

  • 8/19/2019 Lecture 0405

    11/61

    #define You may also associate constant using #define preprocessor directive

    #include

    #define PI 3.14int main(void){

    double height, radius, base, volume;

    printf(“Enter the height and radius of the cone:”);scanf(“%lf %lf ”,&height,&radius);

    base = PI * radius * radius;volume = (1.0/3.0) * base * height;printf(“\nThe volume of a cone is %lf ”, volume);return 0;

    }

  • 8/19/2019 Lecture 0405

    12/61

    Input/Output Operations Input operation

    an instruction that copies data from an input device intomemory

    Output operation

     

    the output devices (such as the monitor screen)

  • 8/19/2019 Lecture 0405

    13/61

    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.hsuch as :

    printf()

    getchar() & putchar()

  • 8/19/2019 Lecture 0405

    14/61

    The printf function Used to send data to the standard output (usually the

    monitor) to be printed according to specific format. General format:

    printf(“string literal”);

    A sequence of any number of characters surrounded by double quotationmarks.

    printf(“format string”, variables); Format string is a combination of text, conversion specifier and escape

    sequence.

  • 8/19/2019 Lecture 0405

    15/61

    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/19/2019 Lecture 0405

    16/61

    Program Structure: Executablee.g. sum = sum + item;

    Note: Left side of an assignmentstatement is called lvalue – it mustbe assignable

    Examples of invalid assignment (result in compilation error “lvaluerequired as left operand of assignment”):

    32 = a;

    a + b = c;

    Assignment can be cascaded, with associativity from right to left: a = b = c = 3 + 6; // 9 assigned to variables c, b and a

    The above is equivalent to: a = (b = (c = 3 + 6));

    which is also equivalent to:

    c = 3 + 6;

    b = c;

    a = b;

  • 8/19/2019 Lecture 0405

    17/61

    Program Structure: Executable Side Effect:

    An assignment statement does not just assigns, it also has the

    side effect of returning the value of its right-hand sideexpression

    Hence a = 12; has the side effect of returning the value of

    Usually we don’t make use of its side effect, but sometimes wedo, eg:

    z = a = 12;  // or z = (a = 12);

    The above makes use of the side effect of the assignment

    statement a = 12; (which gives 12) and assigns it to z Side effects have their use, but avoid convoluted codes:

    a = 5 + (b = 10);  // assign 10 to b, and 15 to a

    Side effects also apply to expressions involving other operators

    (eg: logical operators).

  • 8/19/2019 Lecture 0405

    18/61

    Escape SequenceEscape 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/19/2019 Lecture 0405

    19/61

    Placeholder / Conversion Specifier

    No Conversion

    Specifier

    Output Type Output Example

    1 %d Signed decimal integer 762 %i Signed decimal integer 76

    3 %o Unsigned octal integer 134

    4 %u Unsigned decimal integer 76

     

    6 %X Unsigned hexadecimal (capital letter) 9C7 %f Integer including decimal point 76.0000

    8 %e Signed floating point (using e

    notation)

    7.6000e+01

    9 %E Signed floating point (using E

    notation)

    7.6000E+01

    10 %g The shorter between %f and %e 76

    11 %G The shorter between %f and %E 76

    12 %c Character ‘7’

    13 %s String ‘76'

  • 8/19/2019 Lecture 0405

    20/61

    The scanf function Read data from the standard input device (usually keyboard)

    and store it in a variable.

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

     

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

    value

  • 8/19/2019 Lecture 0405

    21/61

    The scanf function cont… Example :

    int age;

    printf(“Enter your age: “);scanf(“%d”, &age);

     ommon onvers on en er use n pr n an scanfunctions.

    printf scanf  

    int %d %d

    float %f %f  double %lf %lf  

    char %c %c

    string %s %s

  • 8/19/2019 Lecture 0405

    22/61

    The scanf function cont… If you want the user to enter more than one value, you

    serialise the inputs.

    Example:

    float height, weight;

    printf(“Please enter your height and weight:”);scanf(“%f%f ”, &height, &weight);

  • 8/19/2019 Lecture 0405

    23/61

    Few notes on C program cont… Reserved Words

    Keywords that identify language entities such as statements,

    data types, language attributes, etc.

    Have special meaning to the compiler, cannot be used asidentifiers (variable, function name) in our pro ram. 

    Should be typed in lowercase. Example: const, double, int, main, void,printf, while, for, else

    (etc..)

  • 8/19/2019 Lecture 0405

    24/61

    Few notes on C program cont… Punctuators (separators)

    Symbols used to separate different parts of the C program. These punctuators include:

    [ ] ( ) { } , ; “: * #

     

    int main void()

    {

    int num = 10;

    printf(“%d”, num);

    return 0;

    }

  • 8/19/2019 Lecture 0405

    25/61

    Few notes on C program cont…Operators

    Tokens that result in some kind of computation or action whenapplied to variables or other elements in an expression.

    Example of operators:

      -

    Usage example:

    result = total1 + total2;

  • 8/19/2019 Lecture 0405

    26/61

    Input/Output %d and %lf are examples of format specifiers; they are placeholders for values to be

    displayed or read

    Placeholder Variable Type Function Use%c char printf / scanf  

    %d int printf / scanf  

     oa or ou e pr n

    %f float scanf  

    %lf double scanf  

    %e float or double printf (for scientific notation)

    Examples of format specifiers used in printf(): %5d: to display an integer in a width of 5, right justified

    %8.3f : to display a real number (float or double) in a width of 8,

    with 3 decimal places, right justified

    Note: For scanf(), just use the format specifier without indicating width,

    decimal places, etc.

  • 8/19/2019 Lecture 0405

    27/61

    Input/Output \n is an example of escape sequence

    Escape sequences are used in printf() function for certain special effects or to display

    certain characters properly

    These are the more commonly used escape sequences:

     

    sequence\n New line Subsequent output will appear on the next line

    \t Horizontal tab Move to the next tab position on the current line

    \" Double quote Display a double quote "

    %% Percent Display a percent character %

  • 8/19/2019 Lecture 0405

    28/61

    Operators Arithmetic operations Binary Operators: +, – , *, /, % (modulo or remainder)

    Left Associative (from left to right) 46 / 15 / 2 3 / 2 1

    19 % 7 % 3 5 % 3 2

       – , Right Associative x = – 23 p = +4 * 10

    Execution from left to right, respecting parentheses rule, and then precedencerule, and then associative rule (next page)

    addition, subtraction are lower in precedence than multiplication, division, andremainder

    Truncated result if result can’t be stored (the page after next)

    int n; n = 9 * 0.5; results in 4 being stored in n.

  • 8/19/2019 Lecture 0405

    29/61

    Operators Arithmetic operators: Associativity & Precedence

    Operator Name Number of

    operands

    Position Associativity Precedence

    ( Parentheses Unary Prefix Left to right 1

    ) Parentheses Unary Postfix Left to right 1

    + Positive sign Unary Prefix Right to left 2

    - Negative sign Unary Prefix Right to left 2++ Post-increment Unary Postfix Left to right 2

    -- Post-decrement Unary Postfix Left to right 2

    ++ Pre-increment Unary Prefix Right to left 2

    -- Pre-decrement Unary Prefix Right to left 2

    *, /, % Multiplication,division,remainder

    Binary Infix Left to right 3

    +, - Addition, subtraction Binary Infix Left to right 4

    =, +=, -=,*=, /=, %=

    Assignment Binary Infix Right to left 5

  • 8/19/2019 Lecture 0405

    30/61

    Operators Mixed-Type Arithmetic Operations

    int m = 10/4; means

    float p = 10/4; means

    int n = 10/4.0; means

    float q = 10/4.0; means

    int r = -10/4.0; means Type Casting

    Use a cast operator to change the type of an expression

    syntax: (type) expression

    int aa = 6; float ff = 15.8;

    float pp = (float) aa / 4; means

    int nn = (int) ff / aa; means

    float qq = (float) (aa / 4);means

  • 8/19/2019 Lecture 0405

    31/61

    Common Programming Errors Debugging Process removing errors from a

    program

    Three (3) kinds of errors :

     

    Syntax Error a violation of the C grammar rules, detected during

    program translation (compilation).

    statement cannot be translated and program cannot beexecuted

  • 8/19/2019 Lecture 0405

    32/61

    Common Programming Errors cont…Run-time errors

    An attempt to perform an invalid operation, detectedduring program execution.

    Occurs when the program directs the computer to,

    by zero. The computer will stop executing the program, and

    displays a diagnostic message indicates the line where the

    error was detected

  • 8/19/2019 Lecture 0405

    33/61

    Common Programming Errors cont… Logic Error/Design Error An error caused by following an incorrect algorithm

    Very difficult to detect - it does not cause run-timeerror and does not display message errors.

    The only sign of logic error – incorrect program

    Can be detected by testing the program thoroughly,comparing its output to calculated results

    To prevent – carefully desk checking the algorithmand written program before you actually type it

  • 8/19/2019 Lecture 0405

    34/61

    Lecture 05:Chapter 3: Top-Down Design with Functions

    CSE 115: Computing Concepts

  • 8/19/2019 Lecture 0405

    35/61

    Top-Down Design and Structure Charts

    Top down design

    A problem solving method

    break a problem up into its major subproblems

    Solve the subproblems

      Derive the solution

    Structure Charts

    documentation tool shows the relationships among the subproblems of a

  • 8/19/2019 Lecture 0405

    36/61

    Drawing Simple Diagrams PROBLEM: Draw some simple diagrams on your printer

    or screen.

    ANALYSIS: Both figures can be drawn with these fourbasic components:

    ■ a circle ■ parallel lines

    a base line■

    intersecting lines

  • 8/19/2019 Lecture 0405

    37/61

    Draw a figure DESIGN : Divide the problem in three sub problems

    INITIAL ALGORITHM

    Draw a circle.

    Draw a triangle.

      Draw intersecting.

    ALGORITHM REFINEMENTS

    Step 2 Refinement

    2.1 Draw intersecting lines.

    2.2 Draw a base.

  • 8/19/2019 Lecture 0405

    38/61

    Structure Chart

  • 8/19/2019 Lecture 0405

    39/61

    Top down design using function/* Draws a stick figure*/

    #include /* printf definition */

    /* function prototypes */

    void draw_circle(void); /* Draws a circle */

    void draw_intersect(void); /* Draws intersecting lines */

    void draw_base(void); /* Draws a base line */

    void draw_triangle(void); /* Draws a triangle */

    int main(void)

    {

    /* Draw a circle. */draw_circle();

    /* Draw a triangle. */

    draw_triangle();

    /* Draw intersecting lines. */

    draw_intersect();return (0);

    }

  • 8/19/2019 Lecture 0405

    40/61

    A simple drawing program

    Problem:- Write a program DrawFigures.c to draw a rocket ship (which is

    a triangle over a rectangle, over an inverted V), a male stick

    figure (a circle over a rectangle over an inverted V), and afemale stick figure (a circle over a triangle over an inverted V)

    Analysis:

    - No particular input needed, just draw the needed 3 figures- There are common shapes shared by the 3 figures

    Design:

    - Algorithm (view in words):1. Draw Rocket ship2. Draw Male stick figure (below Rocket ship)

    3. Draw Female stick figure (below Male stick figure)

    rocket male female

  • 8/19/2019 Lecture 0405

    41/61

    A simple drawing program

    Design (Structure Chart):

    Draw 3Figures

    Draw RocketShip

    Draw TriangleDraw

    Rectangle

    Draw

    Inverted V

    Draw MaleStick Figure

    Draw CircleDraw

    Rectangle

    Draw

    Inverted V

    Draw FemaleStick Figure

    Draw Circle Draw TriangleDraw

    Inverted V

    rocket male female

  • 8/19/2019 Lecture 0405

    42/61

    Modular Programming  Break a large problem into smaller pieces

    Smaller pieces sometimes called ‘modules’ or ‘subroutines’ or‘procedures’ or functions

    Why? Hel s mana e com lexit 

    Smaller blocks of code Easier to read

    Encourages re-use of code

    Within a particular program or across different programs

    Allows independent development of code Provides a layer of ‘abstraction’

    a = sqrt(9.0);

  • 8/19/2019 Lecture 0405

    43/61

    Functions The ‘building blocks’ of a C program

    You’ve used predefined functions already:

    main()

    printf(), scanf(), pow()

    User-defined functions

    Your own code In combination with predefined functions

  • 8/19/2019 Lecture 0405

    44/61

    Functions - Mathematical View

    32)(

    2++=

     x x x f 

    f(2)?isWhat

    11is)2(

    113443)2(2)2()2( 2

     f 

     f 

    ⇒++⇒++⇒

    )( x f 2 11

    X Function

    Returned

    value

  • 8/19/2019 Lecture 0405

    45/61

    Functions in CresultType functionName(type1 param1, type2 param2, …)

    {

    body 

    } // functionName

    If no result, resultType should be void 

    Warning if not!

    If no parameters, use void between ()

  • 8/19/2019 Lecture 0405

    46/61

    Library Function Goal to write error-free code

    Code reuse

    C’s standard math library defines a function named sqrt -performs the square root computation

      e unct on ca n t e ass gnment statement

  • 8/19/2019 Lecture 0405

    47/61

    C Library FunctionFunction Header Purpose: Example Argument(s) Result

    abs(x) Returns the absolute value of its integer

    argument: if x is −5 , abs(x) is 5

    int int

    ceil(x) Returns the smallest integral value that is notless than x : if x is 45.23 , ceil(x) is 46.0

    double double

     .   . ,

    cos(x) is 1.0 (radians)pow(x,y) double,

    doubledouble

    sqrt(x) Returns the nonnegative square root of x (1x)for x ≥ 0.0 : if x is 2.25 , sqrt(x) is 1.5

    double double

    log(x) Returns the natural logarithm of x for x > 0.0 :if x is 2.71828 , log(x) is 1.0

    double double

    log10(x) Returns the base-10 logarithm of x for x > 0.0: if x is 100.0 , log10(x) is 2.0

    double double

  • 8/19/2019 Lecture 0405

    48/61

    Using Functions Let int f(double x, int a) be (the beginning

    of) a declaration of a function.

    Then f(expr1, expr2) can be used in any expression

     –   . .,

     N = + d;

    f(pi*pow(r,2), b+c)

  • 8/19/2019 Lecture 0405

    49/61

    Using Functions Let int f(double x, int a) be (the beginning

    of) a declaration of a function.

    Then f(expr1, expr2) can be used in any expression

     –   . .,

     N = + d;

    f(pi*pow(r,2), b+c)

  • 8/19/2019 Lecture 0405

    50/61

    Using Functions (continued) Let int f(double x, int a) be (the beginning

    of) a declaration of a function.

    Then f(expr1, expr2) can be used in any

     expression where a value of type int can beused – e.g., N = f(pi*pow(r,2), b+c) + d;

    Function f is executed and returns a

    value of type intResult of f is added to d Sum is assigned to N

  • 8/19/2019 Lecture 0405

    51/61

    Function definition Every function definition has the form

    return-type function-name ( parameter declarations) {

    definitions and statements

    }

    For practical purposes, code between {} (inclusive) is acompound statement

  • 8/19/2019 Lecture 0405

    52/61

    Function Prototype There are many, many situations in which a

    function must be used separate from where it is

    defined – 

    before its definition in the same C program

      In one or more completely separate C programs

    This is actually the normal case!

    Therefore, we need some way to declare a

    function separate from defining its body. Called a Function Prototype

  • 8/19/2019 Lecture 0405

    53/61

    Function Prototype (continued) Definition:– a Function Prototype in C is a language

    construct of the form:– 

    return-type function-name (parameter declarations) ;

    I.e., exactly like a function definition, except with a

    ';' instead of a body in curly brackets

  • 8/19/2019 Lecture 0405

    54/61

    Purposes of Function Prototype So compiler knows how to compile calls to that

    function, i.e.,

    number and types of arguments type of result

      “ ”

    programmer who uses the function

    As part of hiding details of how it works andexposing what it does.

    A function serves as a “black box.”

  • 8/19/2019 Lecture 0405

    55/61

    Header files In applications with multiple C programs, function

    prototypes are typically provided in header files

    I.e., the ‘.h’ files that programmers include in their code

    Grouped by related functions and features

    To make it easier for developers to understand

    To make it easier for team development

    To make a package that can be used by someone else

  • 8/19/2019 Lecture 0405

    56/61

    Include #include

    Search the system’s directories in order for a file of the

    name foo.h

     " ".

    Search the directory where the source program is foundfirst, before system directories

  • 8/19/2019 Lecture 0405

    57/61

    Functions - Definition Structure Function 'header'

    Return data type

    (if any) Name Descriptive

    Arguments (or parameter list) 

    type function_name (type arg1, type arg2 )

    {

    statements;}

    otice: ata type an name

    Statements Variable declaration Operations Return value (if any)

    double product(double x, double y)

    {

    double result;

    result = x * y;return result;

    }

    A function that calculates the product of two numbers

  • 8/19/2019 Lecture 0405

    58/61

    Functions - Example Function prototype

    Like a variable declaration Tells compiler that the function will be defined

    later

    Helps detect program errors Note semicolon!!

    Function definition See previous slide

    Note NO semicolon

    #include

    /* function prototype */

    double product(double x, double y);

    int main()

    {

    double var1 = 3.0, var2 = 5.0; 

    Function return

    return statement terminates execution of thecurrent function

    Control returns to the calling function

    if return   expression; then value of expression is returned as the

    value of the function call

    Only one value can be returned this way

    Function call   main() is the 'calling function'

     product() is the 'called function'

    Control transferred to the function code

    Code in function definition is executed

    ans = product(var1, var2); printf("var1 = %.2f\n"

    "var2 = %.2f\n",var1,var2);

     printf("var1*var2 = %g\n", ans);

    }

    /* function definition */

    double product(double x, double y)

    {

    double result;

    result = x * y;

    return result;

    }

    Creating Function

  • 8/19/2019 Lecture 0405

    59/61

    Creating Function

    #include

    #include

    #define PI 3.14159

    double circle_area(double diameter)

    {

     

    Functiondefinition

    ,

    }

    int main(void ) {

    // identical portion omitted for brevity

    // compute weight of a single washer

    rim_area = circle_area(d2) - circle_area(d1);

    unit_weight = rim_area * thickness * density;

    // identical portion omitted for brevity

    }

    Calling circle_area()

    twice.

    Creating Function

  • 8/19/2019 Lecture 0405

    60/61

    Creating Function

    Components of a function definition

    Header (or signature): consists of return type, function name, and a list of

    parameters (with their types) separated by commas Function names follow identifier rules (just like variable names) May consist of letters, digit characters, or underscore, but cannot begin with a digit

    Return type is void if function does not need to return any value Function body: code to perform the task; contains a return statement if return

    type is not void

    double circle_area(double diameter) {

    return pow(diameter/2, 2) * PI;

    }

    Return type Function name Parameter

    Function body

    Programming style

  • 8/19/2019 Lecture 0405

    61/61

    Programming style

    Preferred practice: add function prototype Before main() function Parameter names may be omitted, but not their type

    #include

    #include

    #define PI 3.14159

     Function prototype

    double circle_area(double);

    int main(void ) {

    // identical portion omitted for brevity

    // compute weight of a single washer

    rim_area = circle_area(d2) - circle_area(d1);unit_weight = rim_area * thickness * density;

    // identical portion omitted for brevity

    }

    double circle_area(double diameter)

    {

    return pow(diameter/2, 2) * PI;}

    Functiondefinition