C Language Preliminaries - PowerPoint PPT Presentation

About This Presentation
Title:

C Language Preliminaries

Description:

Report length in centimetres. Chapter 7. Homework. 9. From Problem to Algorithm ... 'Enter a length in inches: ' is an argument to the printf() function. ... – PowerPoint PPT presentation

Number of Views:145
Avg rating:3.0/5.0
Slides: 48
Provided by: cen7150
Category:

less

Transcript and Presenter's Notes

Title: C Language Preliminaries


1
Chapter 7
  • C Language Preliminaries

2
CS1101C Textbook
C How To Program by H.M. Deitel and P.J.
Deitel Prentice Hall, 2nd Edition ISBN
0-13-288333-3
3
Introduction
  • 1972 by Dennis Ritchie at Bell Lab.
  • ALGOL60 ? CPL ? BCPL ? B ? C
  • ANSI C standardised.
  • C is a high-level language.
  • C is a procedural language.
  • C is baffling to look at, easy to mess up, and
    tricky to learn.

4
Introduction
  • Some articles (more in CS1101C web site, under
    CA Activities/Readings Preparation)
  • The Ten Commandments for C Programmers
  • The Top 10 Ways to get screwed by the C
    programming language

5
Algorithmic Problem Solving
6
From Problem to Algorithm
  • Conversion from inches to centimetres.
  • Step 1 Understanding the problem.
  • What is the the data (input)?
  • Length in inches. Lets call it inches.
  • What is the unknown (output)?
  • Length in centimetres. Lets call it cm.

7
From Problem to Algorithm
  • Step 2 Devising a plan.
  • First draft of plan (algorithm)
  • Get length in inches
  • Compute length in centimetres
  • Report length in centimetres
  • What is the relationship between the data and
    the unknown?
  • 1 inch 2.54 centimetres

8
From Problem to Algorithm
  • Step 2 Devising a plan. (continue)
  • Do I know how to compute the length in cm?
  • Yes.
  • Length in cm is 2.54 times length in inches
  • Complete plan (algorithm)
  • Get length in inches
  • Compute length in centimetres, using
  • 2.54 length in inches
  • Report length in centimetres

9
From Problem to Algorithm
  • Step 2 Devising a plan. (continue)
  • Is the plan correct?
  • Walk through the plan.
  • Work out on some examples 1 inch, 2 inches,
  • 3.5 inches, 0 inch, etc.

10
From Problem to Algorithm
  • Step 3 Carrying out the plan.
  • Convert algorithm to program.
  • Compile and run.
  • Step 4 Looking back.
  • Check the output. Is the output correct?
  • In general, an algorithm may need to go through a
    few rounds of refinements.

11
From Algorithm to Program
  • inch2cm.c

12
Sample Runs
13
Preprocessor Directives
  • C system C language preprocessor libraries
  • Preprocessor modifies program before it is
    compiled.
  • Common directives include and define
  • must be first non-blank character on the line.

14
Preprocessor Directives
  • include ltstdio.hgt
  • Includes header file stdio.h from /usr/include
    directory into program.
  • stdio.h contains functions prototypes of scanf(),
    printf() and others, so that inch2cm.c can use
    these functions.
  • include "file" assumes file in current directory.

15
Preprocessor Directives
  • define CM_PER_INCH 2.54
  • Defines constant macro (or symbolic constant)
    CM_PER_INCH as 2.54
  • Preprocessor replaces each occurrence of
    CM_PER_INCH in the rest of program to 2.54.
  • cm CM_PER_INCH inches
  • ? cm 2.54 inches
  • Purpose?

16
Comments
  • / this is a line of comments /
  • Comments are text enclosed in / and /. Some
    compilers accept //.
  • Comments provide documentation for program
    readability.
  • Every program should have its author and date
    written documented.
  • Every program and function should have a
    statement to describe its purpose.

17
Comments
  • Right dosage is important.
  • Too much
  • i / increment i by 1 /
  • sum num / add num to sum /
  • / multiply CM_PER_INCH by inches /
  • / and store result in cm
    /
  • cm CM_PER_INCH inches

18
Comments
  • Comments add values to readers.
  • Should describe what the steps do and explain
    difficult logic, instead of translating C
    statements into English.
  • Comments explain the purpose program statements
    show the logic.
  • Self-explanatory codes do not need much comments.
    Name variables appropriately. Examples width
    instead of w.

19
Comments
  • Do not fill in comments as an after-thought.
    Documentation should begin at design, and follows
    through every phase.
  • Spot the error
  • float inches, / length in inches
  • cm length in
    centimetres /

20
The main() Function
  • C program consists of functions.
  • At least one function must be present main().
    Execution of the program starts at this function.
  • Example
  • int main (void)
  • / body of function /

21
The main() Function
  • Function consists of header and body.
  • Function header
  • The type of the function -- eg int.
  • The name of the function -- eg main
  • The parameter list enclosed in parentheses --
    eg void

22
The main() Function
  • Function type the type of value this function
    produces.
  • If function type is not void, then there should
    be a return statement to return the result of the
    function. Example return 0
  • Execution of the function ends when the return
    statement is executed, or when the last statement
    is executed.
  • Where is the result returned to?

23
The main() Function
  • A function returns its result (and control) to
    its caller. The caller for the main() function
    is the operating system.
  • Zero is usually returned to UNIX to signal the
    successful completion of the program.

24
The main() Function
  • A function parameter lists the arguments which
    the function takes from its caller.
  • For example
  • printf ("Enter a length in inches ")
  • scanf ("f", inches)
  • "Enter a length in inches " is an argument to
    the printf() function. "f" and inches are
    arguments to the scanf() function.
  • A void parameter indicates no argument.

25
The main() Function
  • Function body
  • Declarations
  • Executable statements
  • Example
  • int main (void)
  • int a, b, c
  • b 5 c 3
  • a b c
  • return 0

26
The main() Function
  • Declarations are statements that declare local
    variables used in the function.
  • Compiler allocate memory space for all variables.

27
Keywords
  • Keywords are reserved words in C language with
    special meanings, and cannot be redefined.

28
Identifiers
  • Identifiers are names given to objects (variables
    and functions).
  • Two types of identifiers standard and
    user-defined.
  • Standard identifiers are predefined names, like
    printf and scanf. They may be redefined, but
    preferably not.
  • User-defined identifiers are created by
    programmers to name variables and functions.

29
Identifiers
  • Syntax for an identifier consists of letters,
    digits and underscore (_), but may not begin with
    digit.
  • Avoid naming an identifier starting with
    underscore (_).
  • Choose appropriate identifiers for variable names
    and function names. Compare these identifiers
    for a particular variable
  • sum_of_list_of_numbers
  • s
  • sum

30
Identifiers
  • Identifiers are case sensitive.
  • By convention, identifiers for constant macros
    (symbolic constants) are usually in upper-case
    letters. Example CM_PER_INCH

31
Constants
  • Constants are often used in programs for values
    that do not change. Examples
  • perimeter 2 (length breadth)
  • rem count 7
  • printf ("Hello\n")
  • Types of constants numeric constants, character
    constants, and string constants.

32
Constants
  • Numeric contants integers (decimal, octal, and
    hexadecimal) and floating-point numbers.
    Examples
  • 123, -345, 12
  • 0123, 05
  • 0x2A, 0x88
  • 1.234, -0.00987, 1.2e-4, -3.5E3

33
Constants
  • Character contants a single character enclosed
    in single quotes. Examples
  • 'A', 'b', '', '9', ''
  • String contants a sequence of characters
    enclosed in double quotes. Examples
  • "Hello\n", "ABC", "34.56"
  • A null character, \0, is appended at the end of
    the string.
  • 'K' and "K" are different.

34
Variable Declarations
  • Variables must be declared before they can be
    used.
  • Variables are declared in the declaration
    statements in a function. The declaration of a
    variable consists of its name and its type of
    value.
  • float inches
  • float cm
  • or
  • float inches, cm

35
Data Types
  • A data type defines a set of values and a set of
    operations permissible on those values.
  • Basic data types int, float, double, char.
  • int integer data type. Example of values of
    this type 123, -900, 987654321, 31. An integer
    occupies a fixed number of bytes, so there is a
    range of values that can be represented.

36
Data Types
  • float floating-point data type. Example of
    values of this type 4.3, -123.00, 0.02, 1.2e4,
    -86e3, 3.9e-12.
  • A floating-point representation consists of
    mantissa (fraction part) and exponent, with an
    assumed base.
  • double double-precision floating-point data
    type. It uses twice the number of bits in the
    mantissa, hence it may represent more precise
    values.

37
Data Types
  • char character data type. Example of values of
    this type 'a', 'P', '3', '', ' '.

38
Programming Style
  • Indentation to show the hierarchy of logic.
  • if (x lt y)
  • printf ("x is smaller than y\n")
  • if (y lt z)
  • printf ("y is smaller than z\n")
  • else
  • printf ("y is larger than or equal to z\n")
  • else
  • printf ("x is larger than or equal to y\n")

39
Programming Style
  • Blank lines to separate functions, or logical
    blocks.
  • Naming of identifiers.

40
Data Validation
  • Examine this run
  • Should -2 be accepted?
  • Data validation to validate input data and take
    necessary actions.
  • A rugged program should not terminate abruptly
    under all circumstances -- ultimate aim.

41
Data Validation
  • But this is too ambitious. An easy way out is to
    make assumptions, and document them in the
    program as pre-conditions.
  • Compromise include simple data validation
    checks, whenever possible.

42
Variables and Memory
  • A variable has name, type and value.
  • Each variable is allocated some memory
    location(s) to hold its value. Such allocation
    occurs at the variable declaration statements.
  • Every memory location has an address. However,
    programmer only needs to refer to the variable by
    its name, and leaves it to the system to work out
    the address.

43
Variables and Memory
  • Example float inches, cm

44
Variables and Memory
  • Initially, the value of a variable is undefined.
    A variable must be initilialised before its value
    is used.
  • 3 ways to assign a value into a variable
  • Initialising the variable at declaration
  • Use the assignment statement
  • Use the input function

45
Variables and Memory
  • Initialisation at declaration
  • float inches 3.2
  • Using assignment statement
  • inches 3.2
  • Using an input function
  • scanf ("f", inches)

46
Variables and Memory
  • Destructive write, non-destructive read.
  • int a, b
  • a 40
  • b 50
  • b a b

47
Homework
  • Try exercises behind chapter 7.
Write a Comment
User Comments (0)
About PowerShow.com