Learning by Example Example Program - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Learning by Example Example Program

Description:

Further Digression: Basic C/C ... Further Digression: Naming Rules ... Digression: Declarations and Definitions. Subtle distinction as applied to variables ... – PowerPoint PPT presentation

Number of Views:101
Avg rating:3.0/5.0
Slides: 39
Provided by: myn91
Category:

less

Transcript and Presenter's Notes

Title: Learning by Example Example Program


1
Learning by Example Example Program
  • / Example program computes prints users age
    in days
  • Course CS 2308-xxx Author ...
    Date ...
  • ... /
  • include ltiostream.hgt
  • int main(void)
  • const int DAYS_PER_YEAR 365 // constant
    declaration
  • int ageInYears, ageInDays // variable
    declarations
  • cout ltlt "Enter your age in years (whole
    number) "
  • cin gtgt ageInYears
  • ageInDays ageInYears DAYS_PER_YEAR
  • cout ltlt "Your age is about " ltlt ageInDays ltlt "
    days.\n"
  • return(0)

2
Learning by Example Dissection of Example
Program
  • / Example program computes prints users age
    in days
  • Course CS 2308-xxx Author ...
    Date ...
  • ... /
  • include ltiostream.hgt
  • int main(void)
  • const int DAYS_PER_YEAR 365 // constant
    declaration
  • int ageInYears, ageInDays // variable
    declarations
  • cout ltlt "Enter your age in years (whole
    number) "
  • cin gtgt ageInYears
  • ageInDays ageInYears DAYS_PER_YEAR
  • cout ltlt "Your age is about " ltlt ageInDays ltlt "
    days.\n"
  • return(0)

3
Dissection of Example ProgramComments
  • Explanatory remarks
  • what entire program is about
  • what each line of code (or set of same) is meant
    to do or reason behind its use
  • anything useful for own future reference or for
    helping others understand your program
  • Syntax 1 (C/C) / ltcommentgt /
  • Syntax 2 (C Only) // ltcommentgt
  • delimiters (/, / //) must appear as single
    units

4
Dissection of Example ProgramMore on Comments
  • No effect on program size or execution speed
  • Can be placed anywhere in program
  • Syntax 1 best when across two or more lines
  • As in example program
  • Syntax 1 cannot nest one within another
  • Dont do / A comment / Another comment / /
  • Syntax 2 best when one line or same line as
    actual code
  • // An example one-line comment
  • int ageInYears, ageInDays // variable
    declarations

5
Dissection of Example ProgramMore on Comments
(contd)
  • Almost always a good thing to have
  • Most programmers dont use enough comments
  • Important part of any program (esp. for this
    class)
  • Remember
  • Not every one is as smart as you are or think or
    see things like you do
  • You may not remember undocumented stuff yourself
  • Details are represented by your codes, so
    comments should concentrate on big picture, not
    details
  • Should clarify any significant reason underlying
    you work (why do it why doing it the way you do)

6
Learning by Example Dissection of Example
Program (contd)
  • / Example program computes prints users age
    in days
  • Course CS 2308-xxx Author ...
    Date ...
  • ... /
  • include ltiostream.hgt
  • int main(void)
  • const int DAYS_PER_YEAR 365 // constant
    declaration
  • int ageInYears, ageInDays // variable
    declarations
  • cout ltlt "Enter your age in years (whole
    number) "
  • cin gtgt ageInYears
  • ageInDays ageInYears DAYS_PER_YEAR
  • cout ltlt "Your age is about " ltlt ageInDays ltlt "
    days.\n"
  • return(0)

7
Dissection of Example Programinclude
Preprocessor Directive
  • Tells compiler to insert contents of another file
    into your source file, at where the directive is
    located
  • In effect, include directive is replaced by the
    contents of the file indicated
  • Syntax include lt name of file to be inserted gt
  • In example program, specifically,
  • include ltiostream.hgt
  • tells compiler to add contents of file
    iostream.h to the source file before actual
    compilation starts

8
Dissection of Example ProgramDigression About
iostream.h
  • Stands for input/output stream header file
  • Comes packaged with C compiler
  • Contains declarations for iostream library -
    provides interactive I/O capabilities
  • Because example program uses objects cin and
    cout, declarations in iostream.h are needed so
    that compiler can recognize these objects

9
Dissection of Example ProgramDigression Header
Files
  • Example iostream.h weve just discussed
  • Header because they are placed at the top or
    head of C/C programs
  • Other commonly used standard header files
  • iomanip.h (output formatting capabilities)
  • math.h (math functions)
  • ctype.h (single-character processing)
  • stdlib.h (commonly used functions)

10
Dissection of Example ProgramDigression Header
Files (contd)
  • Inserting custom header files
  • Custom header files header files written by you
  • Syntax include path and name of file
  • Example include myheader.h
  • What difference does this make?
  • Need for header files
  • All programs (except trivial ones) invariably
    need one or more header files
  • Explicitly include header files for portability
  • Header files optional for some compilers

11
Dissection of Example ProgramDigression
Preprocessor Directives
  • Numerous preprocessor directives in C/C,
    notably
  • include - beaten to death already
  • define - create symbolic constants (in C,
    discussed next) and macros (will not discuss in
    this course)
  • Creating symbolic constants in C using define
  • Symbolic (names for) constants
  • Syntax define symbolic-name constant
  • Example define MARKUP 1.75
  • Customary use all uppercase for symbolic
    constants
  • ? In C, named constant const double MARKUP
    1.75

12
Dissection of Example ProgramDigression
Preprocessor Directives (contd)
  • Rules
  • All preprocessor directives begin with
  • A preprocessor directive must be written on one
    line, except in some cases where a backslash ( \
    ) can be used to indicate continuation onto next
    line
  • Only whitespace characters may appear before a
    preprocessor directive on a line
  • Other uses of preprocessor directives
  • Conditional execution of preprocessor directives
  • will use this when separating interface from
    implementation
  • Conditional compilation of program code
  • will not see this in this course

13
Learning by Example Dissection of Example
Program (contd)
/ Example program computes prints users age
in days Course CS 2308-xxx Author
... Date ... ... / include
ltiostream.hgt int main(void) const int
DAYS_PER_YEAR 365 // constant declaration
int ageInYears, ageInDays // variable
declarations cout ltlt "Enter your age in years
(whole number) " cin gtgt ageInYears
ageInDays ageInYears DAYS_PER_YEAR cout
ltlt "Your age is about " ltlt ageInDays ltlt "
days.\n" return(0)
14
Dissection of Example ProgramDigression
Functions
  • One of the fundamental building blocks of C/C
  • A C/C program consists of one or more functions
  • Example program consists almost entirely (save
    comments preprocessor directive) of a single
    main function
  • Self-contained units of program code designed to
    perform specific tasks
  • Subprograms (small programs) that can be called
    by other programs (calling programs) to
    accomplish particular tasks
  • Essentially programs (though small), thus
    characteristics design are similar to those for
    programs (discussed earlier)
  • Need some means for receiving data returning
    results

15
Dissection of Example ProgramDigression
Functions (contd)
  • C/C Function Format (informally somewhat
    simplified)
  • ReturningSpec CallingSpec ( ReceivingSpec )
  • Function Body
  • Parentheses are distinguishing feature of a
    function
  • Every function must have pair of braces -
    delimit body of function
  • More formal terms
  • ReturningSpec ??Return Data Type
  • CallingSpec ??Function Name
  • ReceivingSpec ??Function Parameters (Arguments)
  • To discuss basic data types in C/C naming
    rules for now

16
Dissection of Example ProgramFurther Digression
Basic C/C Data Types
  • (Operating system/compiler dependent examples
    below typical for PC )
  • Data Type Size (bytes) Lower Bound Upper Bound
  • char 1 - -
  • int 2 ?????? ??????
  • unsigned int 2 ? ?????
  • long int 4 ??3?? ??3???
  • float 4 ??????????? ??????????
  • double 8 ??????????? ????????????
  • char - alphabet letters (lower upper case),
    digits, special symbols
  • int, unsigned int, long int - integer (short
    int also in C)
  • float - single-precision floating-point
  • double - double-precision floating-point (long
    double also in C)
  • ? bool - booleans (included in ANSI C
    standard)

17
Dissection of Example ProgramFurther Digression
Naming Rules
  • Same rules for all C/C identifiers (functions,
    variables, etc.)
  • May use only upper lower case letters, digits
    (0 to 9), and underscore ( _ ) no other
    characters (spaces included) allowed
  • First character must be a letter or underscore
  • Only 31 characters is recognized by most
    compilers
  • Cannot be the same as a C/C keyword (reserved
    word)
  • C Keywords (as listed in page 638 of textbook)
  • asm class double friend new return switch union
  • auto const else goto operator short template uns
    igned
  • break continue enum if private signed this virtu
    al
  • case default extern inline protected sizeof thro
    w void
  • catch delete float int public static try volatile
  • char do for long register struct typedef while
  • ? There are additional keywords in ANSI C
    standard

18
Dissection of Example ProgramFurther Digression
Common Sense Naming Rules
  • All names should be mnemonic - memory aid by
    design
  • Should be carefully chosen to be as meaningful
    as self-documenting as possible
  • Names that are not adequately self-documenting
    should be supplemented with comments
  • All program code, including names, should in
    general be in lowercase letters - leave names
    that begin with uppercase letters or use all
    uppercase letters for special cases (all
    uppercase letters for symbolic constants, for
    example)
  • Proper use of multiple-word names can improve
    readability
  • Not good totalcommissionstodate
  • Better total_commissions_todate or
    totalCommissionsTodate

19
Dissection of Example Program (contd)Function
Header
  • Structure
  • int main(void)
  • Function Body
  • ReturningSpec - int specifies that data type of
    result to be returned is of type int
  • Defaults to int if not specified (common
    practice for main function)
  • Use void if function returns nothing
  • ReceivingSpec - void specifies that nothing
    will be received
  • Use of void is optional (for functions that
    receive nothing)
  • CallingSpec - main is name with which function
    is called

20
Dissection of Example Program (contd)Digression
main Function Specials
  • All C/C programs must have a function called
    main
  • For a C/C program w/ only 1 function, that
    function must be called main - this is the case
    with example program
  • If there is no function called main - linker
    will signal error
  • Execution of all C/C programs starts with main
  • In most programs, the main function plays a
    driver role - calls other functions to carry
    out programs real work
  • For this reason, it is sometimes referred to as
    the driver function or simply the driver

21
Learning by Example Dissection of Example
Program (contd)
/ Example program computes prints users age
in days Course CS 2308-xxx Author
... Date ... ... / include
ltiostream.hgt int main(void) const int
DAYS_PER_YEAR 365 // constant declaration
int ageInYears, ageInDays // variable
declarations cout ltlt "Enter your age in years
(whole number) " cin gtgt ageInYears
ageInDays ageInYears DAYS_PER_YEAR cout
ltlt "Your age is about " ltlt ageInDays ltlt "
days.\n" return(0)
22
Dissection of Example Program (contd)Function
Body
  • Structure
  • C/C Statements
  • Purpose performs all necessary operations to
    accomplish the specific task for which function
    is designed
  • Includes processing of data received (if any)
  • Can directly return at most one value back to
    calling program (multiple values can be returned,
    but indirectly, more on this to come)
  • May call other functions


Compound Statement (Block)
23
Dissection of Example Program (contd)Function
Body (contd)
  • Statements
  • Fundamental unit of C/C programming
  • Many C/C statements must be ended with
    (crucial part of syntax but very easy to forget
    - syntax error)
  • Preprocessor directives - not statements (dont
    end with )
  • Declaration Statements
  • Naming and defining variables (more on this to
    come)
  • Must appear before executable statements in C
    (not in C)
  • Executable Statements
  • Cause computer to perform some operations
  • Constitute majority of statements
  • Much of what you have to learn in this class

24
Learning by Example Dissection of Example
Program (contd)
/ Example program computes prints users age
in days Course CS 2308-xxx Author
... Date ... ... / include
ltiostream.hgt int main(void) const int
DAYS_PER_YEAR 365 // constant declaration
int ageInYears, ageInDays // variable
declarations cout ltlt "Enter your age in years
(whole number) " cin gtgt ageInYears
ageInDays ageInYears DAYS_PER_YEAR cout
ltlt "Your age is about " ltlt ageInDays ltlt "
days.\n" return(0)
25
Dissection of Example Program (contd)Declaration
of Named Constants
  • Declaration statement
  • const int DAYS_PER_YEAR 365
  • declares DAYS_PER_YEAR to be an integer
    constant whose value is 365
  • Constants
  • Cannot be assigned another value (even if its
    the same value)

26
Dissection of Example Program (contd)Declaration
of Variables
  • Declaration statement
  • int ageInYears, ageInDays
  • declares that variables ageInYears
    ageInDays are intended to hold data of type int
  • Variables
  • Most fundamental part of any language
  • Symbolic names - refer to locations in computer
    memory
  • When value is assigned to a variable, value is
    stored in memory location referred to by the
    variable
  • Must be defined before they can be used
  • C only must be defined before first executable
    statement

27
Dissection of Example Program (contd)Digression
Declarations and Definitions
  • Subtle distinction as applied to variables
  • Declaration introduces a variable into program
    and specifies its data type
  • If declaration also sets aside memory for
    variable (up to compiler to decide), it is called
    definition
  • Most declarations are also definitions
  • Cases where declarations are not definitions most
    commonly occur when multiple programs are
    involved (may encounter later in this class)

28
Learning by Example Dissection of Example
Program (contd)
  • / Example program computes prints users age
    in days
  • Course CS 2308-xxx Author ...
    Date ...
  • ... /
  • include ltiostream.hgt
  • int main(void)
  • const int DAYS_PER_YEAR 365 // constant
    declaration
  • int ageInYears, ageInDays // variable
    declarations
  • cout ltlt "Enter your age in years (whole
    number) "
  • cin gtgt ageInYears
  • ageInDays ageInYears DAYS_PER_YEAR
  • cout ltlt "Your age is about " ltlt ageInDays ltlt "
    days.\n"
  • return(0)

29
Dissection of Example Program (contd)Digression
Operators in C/C
  • Arithmetic Operators in C/C
  • Operation C/C Operator Algebraic E.g. E.g. in
    C/C
  • Addition x 7 x 7
  • Subtraction - x - y x - y
  • Multiplication xy or x ??y or x ??y x
    y
  • Division / x / y
  • Modulus x mod y x y
  • Operands must represent numeric values
    (characters okay, why?)
  • Modulus - integer operands, non-zero second
    operand
  • Division - non-zero second operand
  • No exponentiation operator in C/C (use math
    function pow)

30
Dissection of Example Program (contd)Digression
Operators in C/C (contd)
  • Relational Operators in C/C
  • Standard
  • Algebraic C/C
  • Relational Relational C/C Meaning of
  • Operator Operator Example C/C Example
  • ? gt x gt y x greater than y
  • ?? lt x lt y x less than y
  • ?? gt x gt y x greater or equal to y
  • ? lt x lt y x less than or equal to y
  • No spaces between the two symbols in gt and lt
  • The two symbols in gt and lt cannot be reversed

31
Dissection of Example Program (contd)Digression
Operators in C/C (contd)
  • Equality Logical Operators in C/C
  • Standard
  • Algebraic C/C
  • Equality/Logical Equality/Logical
    C/C Meaning of
  • Operator Operator Example C/C E.g.
  • ? x y x equal y
  • ?? ! x ! y x not equal y
  • AND? x y x AND y
  • OR x y x OR y
  • NOT ! !x NOT x
  • No spaces between the two symbols in , !,
    and

32
Dissection of Example Program (contd)Digression
Operators in C/C (contd)
  • More Operators in C/C
  • Name Operator Example Effect
  • unary minus - -x reverse sign of x
  • preincrement x increment x by 1 then use
    new
  • value of x in expression
  • postincrement x use current value of x in
  • expression then increment x by 1
  • predecrement -- --x decrement x by 1 then use
    new
  • value of x in expression
  • postdecrement -- x-- use current value of x
    in
  • expression then decrement x by 1
  • cast (type) (int) x create temporary integer
    copy of x
  • No spaces between the two symbols in and --

33
Dissection of Example Program (contd)Digression
Operators in C/C (contd)
  • Still More Operators in C/C (Still Many More
    Not Listed)
  • Name Operator Example Effect
  • assignment x y assign (store) value of y
    in x
  • x y x x y
  • - x - y x x - y
  • x y x x y
  • / x / y x x / y
  • x y x x y
  • address of x address of variable x
  • indirection x variable whose address is
    stored in x
  • conditional ? (x lt y) ? x y if x is less
    than y then x else y
  • (see Appendix D of text, pages 641-642, for
    complete list of C/C operators)


arithmetic assignment
34
Dissection of Example Program (contd)
Digression Operators in C/C (contd)
  • Operator Precedence Associativity
  • Precedence order-of-evaluation hierarchy
    according to which C/C operators are grouped
  • Operations with higher precedence carried out
    first
  • Example , / and belong to one group, and
    and - belong to another
  • Former group has higher precedence than latter
    group
  • Mult., div. mod. operations carried out
    before add. sub.
  • Natural order of evaluation can be altered
    through use of parentheses
  • Associativity order in which consecutive
    operations of the same precedence are carried
    out
  • left-to-right or right-to-left
  • See Appendix D of text (pages 641-642) for
    complete listing

35
Dissection of Example Program (contd)Digression
Expressions in C/C
  • Expression combination of 1 or more operands
    0 or more operators that usually evaluates to
    a value
  • single entity - constant, variable, function
    reference, etc.
  • combination of such entities - connected by
    operators
  • Almost all of C/C executable statements use
    expressions
  • Examples 12.3 A
  • years 10 a b c
  • x y c a b
  • x y counter
  • To repeat, a C/C expression usually evaluates
    to a value
  • In expression x 5, both variable x and
    expression x 5 have value 5
  • Since is an operator, this makes expressions
    like x y z 0 valid

36
Dissection of Example Program (contd)Digression
Expressions in C/C (contd)
  • Some Notes on Arithmetic Expressions
  • Integer expression (expression containing only
    integer operands) results in integer value
  • Floating-point expression (expression containing
    only floating-point operands) results in
    double-precision value
  • Mixed-mode expression (expression containing both
    integer and floating-point variables) results in
    double-precision value
  • Division of two integers always produces integer
    result - any fractional part is dropped
    (truncated)
  • Example value of 17 / 5 is 3
  • Terminating expression with results in
    statement

37
Dissection of Example Program (contd)Assignment
Statements
  • Tell computer to assign (store) values into
    variables
  • Syntax variable any valid C/C expression
  • Always have (assignment operator) a variable
    name immediately to the left of the operator
  • Value of expression on the right of first
    evaluated then stored in variable whose name
    appears on the left of
  • Expression on the right of can involve the
    same variable that appears on the left of
    (e.g., x x 5)
  • x 10 y z is not a valid statement, why?
  • Since expressions like x y z 0 are valid
    in C/C, statements like x y z 0 are
    valid in C/C

38
Learning by Example Dissection of Example
Program (Next Time)
  • / Example program computes prints users age
    in days
  • Course CS 2308-xxx Author ...
    Date ...
  • ... /
  • include ltiostream.hgt
  • int main(void)
  • const int DAYS_PER_YEAR 365 // constant
    declaration
  • int ageInYears, ageInDays // variable
    declarations
  • cout ltlt "Enter your age in years (whole
    number) "
  • cin gtgt ageInYears
  • ageInDays ageInYears DAYS_PER_YEAR
  • cout ltlt "Your age is about " ltlt ageInDays ltlt "
    days.\n"
  • return(0)
Write a Comment
User Comments (0)
About PowerShow.com