l2 - basic c elements_4

Upload: koiuy12

Post on 01-Jun-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 L2 - Basic C Elements_4

    1/12

     

    Basic C Elements

    The building blocks of C….

    Lecture Overview 

    Overview of 

    C lan ua e

    Run Cycle

    Basic C Elements

     

    [ CS1010E AY1112S1 Le cture 2 ]2

    C Language: A brief history 

    C Programming Language

    Ori inall desi ned b  Dennis Ritchie in 1972 

    The 1978 book “The C Programming Language”

    by Brian Kernighan and Dennis Ritchie

    Gave the first specification of the language

    Standardized:

    in 1990: ANSI C ( ISO C, C89/C90 )

    The most widespread version

     

    Evolved:

    in 1999: C99

    3[ CS1010E AY1112S1 Le cture 2 ]

    C Language: Characteristics

    C Programming language is a:

    Compiled language Program written in C (source code) must be compiled

    into machine code (executable) 

      Hi h Level Pro rammin Lan ua e Follow a set of rules (grammar) to express algorithm

     General purpose language

      mpera ve anguage

    4[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    2/12

    Run Cycle for Compiled Language

    Run Cycle:

    The rocess of   wri tin com i lin and 

    executing a program

    Writing

    Writing

    • Tool: Editor 

    Compiling

    Compiling

    • Tool: Compiler 

    Executing

    Executing

    • Tool: None

    • Produce:Source Code

    • Produce:Executable

    • Produce:Result

    Compilation Error 

    Runtime Error 

     

    5[ CS1010E AY1112S1 Le cture 2 ]

    Environment and Tools in this Course Environment:

     Cygwin: Emulate Linux (Unix-like) under

    Windows

    Tools:

    Editor: vim, nano, etc (You only need one)

    Compiler: gcc (GNU C Compiler)

    Comments and Rationale: Tools look primitive but very flexible and powerful

    Explicitly show the run cycle step by step

    6[ CS1010E AY1112S1 Le cture 2 ]

    Run Cycle: Writing a Program

    Use an editor to write a program following C

    syntax

     

    editor under

    cygwin7

    [ CS1010E AY1112S1 Le cture 2 ]

    Run Cycle: Compiling the Source Code

    Use a compiler to translate C Source Codeinto Machine Code Source code with syntax errors will fail to compile

    Known as Compilation Errors

    s ng gcc

    compiler

    under cygwin

    8[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    3/12

    Run Cycle: Executing the Executable The executable can be directly executed

    May terminate unexpectedly due to errors  

    May terminate successfully but give the wrong result Logic Error 

     A successful

    run o e an

    executable

    9[ CS1010E AY1112S1 Le cture 2 ]

    Run Cycle: A reminder

    Run Cycle happens in the “ Implementation”

    step of the problem solving process

    You should have designed the before you attemptto write the program

     Analysis

    DesignWriting

    Writing

    • Tool: Editor 

    Compiling

    Compiling

    • Tool: Com i ler  

    Executing

    Executing

    • Tool: Nonemp emen a on

    Testing

    • Produce:Source Code

    • Produce:Executable

    • Produce:Result

    10[ CS1010E AY1112S1 Le cture 2 ]

     Your very first C Program

    The famous “Hello World!” program

    Simple program to show a message on screen

    #include Preprocessor

    int main( )

    rec ve

     printf("Hello World!\n");Mainfunction function

    return 0;

    }

    body

    11[ CS1010E AY1112S1 Le cture 2 ]

    C Elements: Preprocessor Directive Specific instructions for the preprocesor 

    (part of the compiler)

       Y   N

       T   A   X

    #directive_name [additional information]

    #include XXXX

       U   S   A   G   E Meaning:

     Add the f ile “ XXXX” fo r compi lat ion

    #include

    We will introduce other directives when we

    encounter them in future12

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    4/12

    C Elements: Preprocessor Directive  Another commonly used directive

    #define Name Value

       G   E

     

    Meaning:

    Substitute all occurrences of Name in the source

       U   S code with Value

    Example:

    #define MAXIMUM 5000

    This directive is useful when:

    There is a constant value used multiple time in the code  Allow easy modification in future

    We will introduce other directives when we encounter them in future

    13[ CS1010E AY1112S1 Le cture 2 ]

    C Elements: The main Function The main function is the starting point of

    your program

    Execution starts from here a special case of function (lecture 3)

       A   X

    int main( )

    {

    0 or more statements

       S   Y   N

     

    return 0;

    }

    Caution: C is case sensitive, e.g. “Main” is not the same as “main”

    Pay attention to the braces: “( )” and “{ }”

    14[ CS1010E AY1112S1 Le cture 2 ]

    C Elements: Statements

    Statements form the major element of a C

    program:

    Basically represent a “step” in algorithm

    In this course, we categorise the C

    statements as:

    1. Declaration Statements

    2.  Assignment Statements

    3. Function Call Statements

    4. Control Structure (Control Flow) Statements

    15[ CS1010E AY1112S1 Le cture 2 ]

    C Statement: Function Call Statement Function Call Statement:

    Use (invoke) a function

    Is a well defined program unit that performs a task

    can be predefined (already written) or user defined more in lecture 3

       X

       S   Y   N   T function_name ( [function_arguments] );

    Function arguments:

    Information needed by the function to perform

    16[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    5/12

     The  printf() function: Brief look 

    The printf( ) function is a:

    redefined function rovided b C standard 

    library defined in the header file

    This is why we have the “#include ” directive

    Purpose:

    prepare and show a message on the output device

    (usually your screen)

       Y   N   T   A   X

     printf ( " message_to_be_shown " );

    17[ CS1010E AY1112S1 Le cture 2 ]

    C Statement: Control-Flow Statement

    Control flow statement changes the defaultsequential execution of the program

    There are a number of control flow statements we have a return statement in the sample

       T   A   X

    return value

       S   Y

     

    Terminates the current function  Give (return) the value to the caller (user) of this function

    18[ CS1010E AY1112S1 Le cture 2 ]

    Programming Style: The role of Spaces White spaces:

    space, empty line, tab

    Generally ignored by compiler, as long as: You place them between elements in the program They are not part of a message (i.e. in between “ ” )

    We use them to im rove ro ram readabilit

    include

    int main( ){

     printf(“Hello World!\n”);return 0;}

      ,

    but a lot harder to read.

    19[ CS1010E AY1112S1 Le cture 2 ]

     

    Ex ressions

  • 8/9/2019 L2 - Basic C Elements_4

    6/12

    Problem: Area and Circumference of a Circle

    Problem Description: Given the radius R, calculate the area and

    c rcum erence o e correspon ng c rc e

     

    1. Get the radius R from user 

    2.   Area PI * R * R

    3.   Circumference 2 * PI * R

    . r n e resu rea an rcum erence

    ,implement it at this point……

    21[ CS1010E AY1112S1 Le cture 2 ]

    C Statement: Declaration Statement Variable:

    Storage for temporary result (data) during execution

     A C variable is specified by: Identifier: Name of the variable

    Data Type: Type of value stored in the variable

    variable is like a “box” to store data

    12345result

    Identifier 

     Actual Value

     

    what kind of value you

    can find in the box22

    [ CS1010E AY1112S1 Le cture 2 ]

    C Statement: Declaration Statement Declaration Statement

    Specify the information of a variable to the compiler 

    Variable must be declared before usage

    datatype identifier ;

       S   Y   N   T   A datatype identifier1, identifier2, ...;

    datatype identifier = initial_value;

    Data Type Desc ri pti on

    int Integer (whole number) with no fractional part

    double Real number with fractional part

    Other To be covered later in the course

    23[ CS1010E AY1112S1 Le cture 2 ]

    C Statement: Declaration Statement

    Identifier :

    Can be declared onl once in a function 

    Must follow naming rule

    Identifier Naming rule:

      ,

    Cannot begin with a digit

     

    meaning in C)

    E.g. return, int, double, … …

    Should not redefine identifiers defined in C library

    24[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    7/12

    C Statement: Declaration Statement Examples:

    Check for validity

    Can ou fi ure out the meanin ? 

    double area;

    ,

    double area = 0.0;

    double area = 0.0, circumference = 1.0;

    double 1area;

    double area_of_circle;

    double return;

    double printf;

    25[ CS1010E AY1112S1 Le cture 2 ]

    Programming Style: Meaningful Identifiers

     Additional requirement when naming

    identifier for readability:

    The name should be short and meaningful Identifier with multiple words should be avoided

    If you must use identifier with multiple words, use

    one o e o ow ng s y es cons s en y:

    Separate word with “_” (underscore)

    E.g. radius of circle _ _ 

    Capitalise the first letter of each word beyond the first:

    E.g. radiusOfCircle

    26[ CS1010E AY1112S1 Le cture 2 ]

    Programming Style: Declare Together!

    In a function, you should place all thedeclaration statements together before otherypes o s a emen s

    int main( )

       Y   N   T   A   X

    {

    [0 or more declaration statements]

    [0 or more other statements]

       Sreturn 0;

    }

    ou can eas y n ou a e var a e use

    in a function at the top part of function in this

    27[ CS1010E AY1112S1 Le cture 2 ]

    C Element: Assignment Statement

     Assignment Statement:

    The main way to change the value stored in a

    variable

       X variable = value;

       S   Y   N   T

    variable = expression;

    Execution:

    1. Evaluate calculate the Ri ht Hand Side

    (R.H.S) to a single value V

    2. Place V in the variable on L.H.S.

    28[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    8/12

    C Element: Assignment Statement

    Simple Examples:

     Assume variables are declared 

    area = 1.23;

    result = result + 4;

     

    The expression can be quite complicated:

    answer = (x + y) * 5 / 1.23;

    Let’s look at the expression in depth:

    pera or 

    Precedence, Associative Rule and Bracket29

    [ CS1010E AY1112S1 Le cture 2 ]

     Assignment Statement: Operators

    Binary Operators:

    Works on two ar uments: ar 1 o ar 2 

    Example: +, -

    * (multiplication)

    / (dividision)

      mo u o, rema n er, on y or w o e num ers

    Unary Operators:

    or s on one argumen : op arg Example:

     

    - (negative): -7.14

    30[ CS1010E AY1112S1 Le cture 2 ]

     Assignment Statement: Operators

    Operators are ordered by precedence:

    - -, - , -

    % Remainder  

    *, / Multiplication, Division+, - Addition, Subtraction

    Operators with the same precedence are

    ordered by associative rule

    Binary Operator: Left Associative

    a + b + c ( a + b ) + c

    Unar O erator: Ri ht Associative

    x- - y x – ( - y)31

    [ CS1010E AY1112S1 Le cture 2 ]

     Assignment Statement: Brackets

    Precedence and Associative rule can be

    trick :

    It is best to avoid them

    You can either:

    Break a com licated ex ression into several 

    statements

    OR, use brackets to avoid logical error 

    32[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    9/12

     Assignment Statement: Conversion Datatype conversion will happen automatically

    during evaluation and assignment

    Example: intVar = 1 / 2;

    doubleVar = 1 / 2;

    doubleVar = 1 / 2.0;

    Safe Conversion: No information is lost during conversion

    e. . 123 123.0

    Unsafe Conversion: 

    e.g. 123.45 123

    33[ CS1010E AY1112S1 Le cture 2 ]

     I O

    scanf(): Predefined Function for Input

       D   E   R #include

       A   X

       H   E

     

    use the function

       S   Y   N   T scanf( "format_string" [, input_list] );

       E  x  a  m  p   l

    scanf( "%d ", &integerVar );

    Placeholder to

    indicate whatdatatype to expect

    Variable to store the

    value entered by user.

    from user   .

    35[ CS1010E AY1112S1 Le cture 2 ]

    scanf(): Predefined Function for Input

    Placeholder:

    %d  for inte er value

    %lf for double floating point value

    Variable: Must match the datatype specified by the placeholder 

    Need a “&” symbol in front

    Will be explained in lecture 6

     A single scanf() can read in multiple values:

      p   l  e

    " "

       E  x  a

      , ,

    36[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    10/12

     printf(): Predefined Function for Output

       D   E   R #include

       A   X

       H

       E

       S   Y   N   T  printf( "format_string " [, print_list] );

      e

       E  x  a  m  p   l

     printf( "Answer is %d ", intVar );

    Note the usage of placeholder in the format

    s r n g

    37[ CS1010E AY1112S1 Le cture 2 ]

     printf(): Predefined Function for Output

    By using placeholder, we can show

    computed values to the user:

    Value stored in a variable Value evaluated by an expression

      p   l  e

    " " *

       E  x  a

      , , , . .

    Value stored inintVar will be

    printed

    esu o s

    expression will be

    printed

    38[ CS1010E AY1112S1 Le cture 2 ]

     printf(): Predefined Function for Output

    Special Control Characters:

    also known as escape sequence

    mainly used to control the movement of cursor 

    \n go to newline\t jump to next tab

    \\ to print out ‘\’

    \” to rint out ‘”’ the double uote character  

    Try it out:

      x  a  m

      p   l  e

     printf( "To print \" you need to \\\"\n");

       E

    39[ CS1010E AY1112S1 Le cture 2 ]

     

    1. Get the radius R from user 

    2.   Area PI * R * R

    3.   Circumference

    2 * PI * R.

  • 8/9/2019 L2 - Basic C Elements_4

    11/12

    From Algorithm to Code

    Convert the "Circle algorithm" to code:#include

      .

    int main( )

    {

    , ,

     printf ( “Enter Radius = " );

    scanf ( "%lf", &radius );

    area = PI * radius * radius;

    circumference = 2 * PI * radius;

    rintf  “The area is %lf Circumference is %lf n"  , ,

    area, circumference);

    return 0;

    }

    41[ CS1010E AY1112S1 Le cture 2 ]

    C Elements: Comments

    You can add descriptive messages in the

    code for ex lanation and extra information

       A   X

    // a single line comment

       S   Y   N * a multiple

    lines comment

    */

    Comments are for humans only ignored by compiler 

    You can also comment off a chunk of actual codeto hide them from compilation

     program

    42[ CS1010E AY1112S1 Le cture 2 ]

    Programming Style: Useful Comments

    We expect you to write useful comments in

    our code:

    Explain a piece of complicated logic

    Ex lain the ur ose of a function more on thislater)

    Don’t overdo it:

    There is no need to comment on every line of

    code

    Excessive comment is actually bad programmings y e

    43[ CS1010E AY1112S1 Le cture 2 ]

    2. Another Exam le Pro ram

    standard  header   ile preprocessor  

    directives

    constant 

    comments

    reserved  

    words

    var a es

    standard  identifiers

    special  

    symbols

     punctuations

    44[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements_4

    12/12

    Problem 1: What time is it?

    Problem statement:

    Given a start time ST and end time ET ex ressed 

    by the hour (0 to 23) and minute (0 to 59) Show the total elapsed time (hour and minute)

    between start time and end time

    For simplicity:

    You can assume that ST and ET are in the same

    day, so ST is always smaller than ET

    45[ CS1010E AY1112S1 Le cture 2 ]

    Summary 

      s

    Declaration Statements

     Assignment Statements

        E   l  e  m  e  n   t

    - arithmetic expressions

    Control Flow Statements

    - return statement

    Function Call statements

      g   S   t  y   l  e

    Use white space for readability 

    Place declarations before other type of

      g  r  a  m  m   i  n

    statements

    Use meaningful identifiers

       P  r  o

    Use comments

    46[ CS1010E AY1112S1 Le cture 2 ]