l2 - basic c elements

Upload: koiuy12

Post on 01-Jun-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 L2 - Basic C Elements

    1/46

  • 8/9/2019 L2 - Basic C Elements

    2/46

    Lecture Overview 

    Overview of 

    C language

    Run Cycle

    Basic C Elements

    Various Statements

    Programming Styles

    [ CS1010E AY1112S1 Le cture 2 ]2

  • 8/9/2019 L2 - Basic C Elements

    3/46

    C Language: A brief history 

    C Programming Language

    Originally designed by 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

    Used in this course

    Evolved:

    in 1999: C99

    3[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    4/46

    C Language: Characteristics

    C Programming language is a:

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

    into machine code (executable)

    Using C Compiler 

    High Level Programming Language Follow a set of rules (grammar) to express algorithm

    General purpose language

    Imperative language

    4[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    5/46

    Run Cycle for Compiled Language

    Run Cycle:

    The process of writing, compiling and

    executing a program

    Writing

    • Tool: Editor 

    • Produce:Source Code

    Compiling

    • Tool: Compiler 

    • Produce:Executable

    Executing

    • Tool: None

    • Produce:Result

    Compilation Error 

    Runtime Error 

    Logic Error 

    5[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    6/46

    Environment and Tools in this Course Environment:

    Cygwin: Emulate Linux (Unix-like) underWindows

    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 ]

  • 8/9/2019 L2 - Basic C Elements

    7/46

    Run Cycle: Writing a Program

    Use an editor to write a program following C

    syntax

    Using vim

    editor under

    cygwin7

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    8/46

    Run Cycle: Compiling the Source Code

    Use a compiler to translate C Source Code

    into Machine Code Source code with syntax errors will fail to compile

    Known as Compilation Errors

    Using gcc

    compiler

    under cygwin

    8[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    9/46

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

    May terminate unexpectedly due to errors Runtime Error 

    May terminate successfully but give the wrong result Logic Error 

     A successful

    run of the an

    executable

    9[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    10/46

    Run Cycle: A reminder

    Run Cycle happens in the “Implementation”

    step of the problem solving process

    You should have designed the before you attempt

    to write the program

     Analysis

    Design

    Implementation

    Testing

    Writing

    • Tool: Editor 

    • Produce:Source Code

    Compiling

    •Tool:Compiler 

    •Produce:Executable

    Executing

    •Tool: None

    •Produce:Result

    10[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    11/46

     Your very first C Program

    The famous “Hello World!” program

    Simple program to show a message on screen

    #include

    int main( )

    {

     printf("Hello World!\n");

    return 0;

    }

    Preprocessor

    Directive

    Main

    function functionbody

    11[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    12/46

    C Elements: Preprocessor Directive Specific instructions for the preprocesor 

    (part of the compiler)

       S   Y   N   T   A   X

    #directive_name [additional information]

       U   S   A   G   E

    #include XXXX

    Meaning:

     Add the file “ XXXX” for compilation

    Example:#include

    We will introduce other directives when we

    encounter them in future12

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    13/46

    C Elements: Preprocessor Directive  Another commonly used directive

       U

       S   A   G   E

    #define Name Value

    Meaning:

    Substitute all occurrences of Name in the source

    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 themin future

    13[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    14/46

    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)

       S   Y   N   T   A   X

    int main( ){

    [0 or more statements]

    return 0;

    }

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

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

    14[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    15/46

  • 8/9/2019 L2 - Basic C Elements

    16/46

    C Statement: Function Call Statement Function Call Statement:

    Use (invoke) a function  A Function:

    Is a well defined program unit that performs a task

    can be predefined (already written) or user defined

    more in lecture 3

       S   Y   N   T   A   X

    function_name ( [function_arguments] );

    Function arguments:

    Information needed by the function to performthe task

    16[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    17/46

     The  printf() function: Brief look 

    The printf( ) function is a:

    predefined function provided by 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)

       S   Y   N   T   A   X

     printf ( " message_to_be_shown " );

    17[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    18/46

    C Statement: Control-Flow Statement

    Control flow statement changes the default

    sequential execution of the program There are a number of control flow statements

    we have a return statement in the sampleprogram

    Return Statement:

       S   Y   N   T   A   X

    return value;

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

    18[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    19/46

  • 8/9/2019 L2 - Basic C Elements

    20/46

     Variables and Arithmetic

    Expressions

  • 8/9/2019 L2 - Basic C Elements

    21/46

    Problem: Area and Circumference of a Circle

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

    circumference of the corresponding circle

     A simple algorithm:

    However, our C knowledge is not enough toimplement it at this point……

    21

    1. Get the radius R from user 

    2.  Area PI * R * R

    3. Circumference 2 * PI * R

    4. Print the result Area and Circumference

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    22/46

  • 8/9/2019 L2 - Basic C Elements

    23/46

    C Statement: Declaration Statement Declaration Statement

    Specify the information of a variable to the compiler  Variable must be declared before usage

       S   Y   N   T

       A   X

    datatype identifier ;

    datatype identifier1, identifier2, ...;

    datatype identifier = initial_value;

    Data Type Description

    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 ]

  • 8/9/2019 L2 - Basic C Elements

    24/46

    C Statement: Declaration Statement

    Identifier :

    Can be declared only once in a function

    Must follow naming rule

    Identifier Naming rule:

    Consists of only letters, digits and underscores

    Cannot begin with a digit

    Cannot use keywords (words with specialmeaning 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

    25/46

    C Statement: Declaration Statement Examples:

    Check for validity Can you figure out the meaning?

    double area;

    double area, circumference;

    double area = 0.0;

    double area = 0.0, circumference = 1.0;

    double 1area;

    double area_of_circle;

    double printf;

    double return;

    25[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    26/46

    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 of the following styles consistently:

    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 ]

  • 8/9/2019 L2 - Basic C Elements

    27/46

    Programming Style: Declare Together!

    In a function, you should place all the

    declaration statements together before othertypes of statements

    27

       S   Y   N   T   A   X

    int main( )

    {

    [0 or more declaration statements][0 or more other statements]

    return 0;

    }

    You can easily find out all the variable used

    in a function at the top part of function in this

    way

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    28/46

    C Element: Assignment Statement

     Assignment Statement:

    The main way to change the value stored in a

    variable

       S   Y   N

       T   A   X variable = value;

    variable = expression;

    Execution:

    1. Evaluate (calculate) the Right 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

    29/46

    C Element: Assignment Statement

    Simple Examples:

     Assume variables are declared

    area = 1.23;

    result = result + 4;

    result = x + y;

    The expression can be quite complicated:

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

    Let’s look at the expression in depth:

    Operator 

    Precedence, Associative Rule and Bracket 29[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    30/46

  • 8/9/2019 L2 - Basic C Elements

    31/46

     Assignment Statement: Operators

    Operators are ordered by precedence:

    +, - Unary +, -

    % 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

    Unary Operator: Right Associative

    x- - y x – ( - y)31

    [ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    32/46

     Assignment Statement: Brackets

    Precedence and Associative rule can be

    tricky:

    It is best to avoid them

    You can either: Break a complicated expression into several

    statements

    OR, use brackets to avoid logical error 

    32[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    33/46

     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.g. 123 123.0

    Unsafe Conversion: Information is lost during conversion

    e.g. 123.45 123

    33[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    34/46

    Simple Input and Output

    (I/O)

  • 8/9/2019 L2 - Basic C Elements

    35/46

    scanf(): Predefined Function for Input

       S   Y   N   T   A   X

    scanf( "format_string" [, input_list] );

       H   E   A   D   E   R #include

    You need to include the above header file in order to

    use the function

       E  x  a  m  p   l  e

    scanf( "%d ", &integerVar );

    Placeholder to

    indicate what

    datatype to expect

    from user 

    Variable to store the

    value entered by user.

    Note the (&) symbol.

    35[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    36/46

    scanf(): Predefined Function for Input

    Placeholder:

    %d  for integer 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:

       E  x  a  m  p   l  e

    scanf( "%d%d ", &intVar1, &intVar2 );

    36[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    37/46

     printf(): Predefined Function for Output

    Note the usage of placeholder in the format

    string

       S   Y

       N   T   A   X

     printf( "format_string " [, print_list] );

       H   E   A   D   E   R #include

       E  x  a  m  p   l  e

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

    37[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    38/46

     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

       E  x  a  m  p   l  e

     printf( "%d, %lf", intVar, 3.14 * 1.23);

    Value stored inintVar will be

    printed

    Result of thisexpression will be

    printed

    38[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    39/46

     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 print out ‘”’ (the double quote character)

    Try it out:

       E  x  a  m  p   l  e

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

    39[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    40/46

  • 8/9/2019 L2 - Basic C Elements

    41/46

    From Algorithm to Code

    Convert the "Circle algorithm" to code:#include #define PI 3.14159

    int main( )

    {

    double radius, area, circumference;

     printf ( “Enter Radius = " );

    scanf ( "%lf", &radius );

    area = PI * radius * radius;

    circumference = 2 * PI * radius;

     printf ( “The area is %lf, Circumference is %lf\n",area, circumference);

    return 0;

    }

    41[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    42/46

  • 8/9/2019 L2 - Basic C Elements

    43/46

    Programming Style: Useful Comments

    We expect you to write useful comments in

    your code:

    Explain a piece of complicated logic

    Explain the purpose of a function (more on this

    later)

    Don’t overdo it:

    There is no need to comment on every line of

    code

    Excessive comment is actually bad programming

    style

    43[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    44/46

    2. Another Example Program

     preprocessor

    directives

    standard header file

    comments

    constant 

    reserved

    words

    variables

    standard identifiers

    special

    symbols

     punctuations

    44[ CS1010E AY1112S1 Le cture 2 ]

  • 8/9/2019 L2 - Basic C Elements

    45/46

    Problem 1: What time is it?

    Problem statement:

    Given a start time ST and end time ET, expressed

    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 ]

  • 8/9/2019 L2 - Basic C Elements

    46/46

    Summary 

       C

       E   l  e  m  e  n   t  s

    Declaration Statements

     Assignment Statements

    - arithmetic expressions

    Control Flow Statements

    - return statement

    Function Call statements

       P  r  o  g  r  a  m  m   i  n  g   S   t  y   l  e

    Use white space for readability 

    Place declarations before other type of

    statements

    Use meaningful identifiers

    Use comments