CMP 131 Introduction to Computer Programming - PowerPoint PPT Presentation

About This Presentation
Title:

CMP 131 Introduction to Computer Programming

Description:

Example: Tax Rate. read(GrossIncome); {Real type} CASE round(GrossIncome) OF ... Turbo Pascal uses short-circuit by default. Standard Pascal doesn't ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 50
Provided by: violettaca
Learn more at: http://www.cs.cmu.edu
Category:

less

Transcript and Presenter's Notes

Title: CMP 131 Introduction to Computer Programming


1
CMP 131Introduction to Computer Programming
  • Violetta Cavalli-Sforza
  • Week 8, Lecture (Monday)

2
MONDAY
  • Midterm results
  • Statistics (next slide)
  • Go over midterm

3
Midterm Statistics
81.3 35
49 32.7
48.3 32.5
44.3 29.3
39.6 28.1
38.2 22
36.5 21.1
36 20

Average 37.11875
Median 35.5
4
WEDNESDAY
  • Multiple choice conditionals
  • Review extended IF statement
  • CASE statement
  • Standard Functions

5
Multiple Choice Alternatives
  • Do something different if Grade A, B, C, D, F,
  • Compute frequencies (histogram)
  • If Input is lt Val1 increment Interval0
  • If Input is in range Val1..Val2 increment
    Interval1
  • If Input is in range Val2..Val3 increment
    Interval2
  • If Input is in range ValN-1.. ValN increment
    IntervalN-1
  • If Input gt ValN increment IntervalN

6
Example
  • Input A letter grade A, B, C, D, or F
  • Output An English grade description
  • A Excellent
  • B Good
  • C Average
  • D Passing
  • F Failing

7
  • PROGRAM EnglishGrade File EXTIF1.pas
  • VAR Grade char
  • BEGIN
  • write('Enter a grade ')
  • readln(Grade)
  • write('Your grade is ')
  • IF Grade 'A' THEN
  • writeln('Excellent')
  • ELSE IF Grade 'B' THEN
  • writeln('Good')
  • ELSE IF Grade 'C' THEN
  • writeln('Average')
  • ELSE IF Grade 'D' THEN
  • writeln('Passing')
  • ELSE IF Grade 'F' THEN
  • writeln('Failing')
  • ELSE
  • writeln('NOT RECOGNIZED')
  • readln

8
Testing the Program
  • Test input should include
  • A test for each legal input A, B, C, D,
    or F
  • At least one test for an illegal input e.g. E
  • Maybe the program should be more robust and
    accept upper and lower case letter grades?

9
  • PROGRAM EnglishGrade File EXTIF2.pas
  • VAR Grade char
  • BEGIN
  • write('Enter a grade ')
  • readln(Grade)
  • write('Your grade is ')
  • IF (Grade 'A') OR (Grade 'a') THEN
  • writeln('Excellent')
  • ELSE IF (Grade 'B') OR (Grade 'b') THEN
  • writeln('Good')
  • ELSE IF (Grade 'C') OR (Grade 'c') THEN
  • writeln('Average')
  • ELSE IF (Grade 'D') OR (Grade 'd') THEN
  • writeln('Passing')
  • ELSE IF (Grade 'F') OR (Grade 'f') THEN
  • writeln('Failing')
  • ELSE
  • writeln('NOT RECOGNIZED')
  • readln

10
  • PROGRAM EnglishGrade File EXTIF2.pas
  • VAR Grade char
  • BEGIN
  • write('Enter a grade ')
  • readln(Grade)
  • write('Your grade is ')
  • IF (Grade 'A') OR (Grade 'a') THEN
  • writeln('Excellent')
  • ELSE IF (Grade 'B') OR (Grade 'b') THEN
  • writeln('Good')
  • ELSE IF (Grade 'C') OR (Grade
    'c') THEN
  • writeln('Average')
  • ELSE IF (Grade 'D') OR
    (Grade 'd') THEN

  • writeln('Passing')
  • ELSE IF (Grade
    'F') OR (Grade 'f') THEN

  • writeln('Failing')
  • ELSE

  • writeln('NOT RECOGNIZED')
  • readln

11
Complex Condition
  • Why IF (Grade 'A') OR (Grade 'a') THEN
    and not IF Grade 'A' OR Grade 'a' THEN
    ?
  • Try compiling IF Grade 'A' OR Grade 'a'
    THEN
  • Result
  • Error 41 Operand types do not match operator

12
Condition Evaluation
  • The condition IF Grade 'A' OR Grade 'a'
    THEN
  • is valuated as
  • IF Grade ( 'A' OR Grade ) 'a' THEN
  • A and Grade are operands of data type char.
  • They are unsuitable for operator OR which wants
    boolean operands.

13
Operator Precedence Arithmetic, Relational and
Logical
  • Operator Precedence
  • ( ) parentheses Highest (evaluated first)
  • - NOT (unary operators)
  • / DIV MOD AND
  • - OR
  • lt lt ltgt gt gt Lowest (evaluated last)

14
Example Exam Score Intervals
  • Exam score Grade Assigned
  • 90 above A
  • 80-89 B
  • 70-79 C
  • 60-69 D
  • Below 60 F

15
Example Exam Scores Intervals (2)
  • Correct grade assignment Incorrect grade
    assignment
  • if score gt 90 then if Score gt 60 then
  • Write ('A') Write ('D')
  • else if Score gt 80 then else if Score gt 70
    then
  • Write ('B') Write ('C')
  • else if Score gt 70 then else if Score gt 80
    then
  • Write ('C') Write ('B')
  • else if Score gt 60 then else if Score gt 90
    then
  • Write ('D') Write ('A')
  • else else
  • Write ('F') Write ('F')

16
Multiple Choice Conditionals The CASE Statement
  • Syntax
  • CASE ltselectorgt OF
  • ltlabel list 1gt ltstatement 1gt
  • ltlabel list 2gt ltstatement 2gt
  • ltlabel list Ngt ltstatement Ngt
  • END

17
Case Statement Example
  • Compute gross pay for a particular day
  • CASE DayNumber OF
  • 1, 7 BEGIN 1,7 - compound statement
  • WeekendRate 1.5 DailyRate
  • Gross Hours WeekendRate
  • END 1,7
  • 2 .. 6 Gross Hours DailyRate
  • END case
  • What should the type of DayNumber be?

18
Case Statement
  • More readable than nested if statements when the
    nesting is deep
  • About selectors and label lists
  • The selector expression is evaluated and compared
    to each of the case labels
  • The type of each constant in a case label value
    must correspond to the type of the selector
    expression
  • Each labeli is a list of one or more possible
    constants, separated by commas
  • A particular selector may appear in at most one
    of the labels
  • About statements and their execution
  • Statementi will be executed if selector value
    lies in labeli
  • Each statement may be a single or a compound
    Pascal statement
  • Only one statement will be executed
  • If the value of the selector is not listed in any
    case label, an error message is printed and
    program execution stops
  • After execution of the CASE statement, control is
    passed to the first statement following the CASE
    end

19
Guarding Case Statements
  • Use an if-statement to prevent the occurrence of
    Out of range error of case expression.
  • Compute gross pay for a particular day
  • IF (DayNumber gt 1) AND (DayNumber lt 7) THEN
  • CASE DayNumber OF
  • 1, 7 BEGIN 1,7
  • WeekendRate 1.5 DailyRate
  • Gross Hours WeekendRate Rate
  • END 1,7
  • 2 . . 6 Gross Hours DailyRate
  • END case
  • ELSE
  • WriteLn (DayNumber1, ' is an invalid day
    number')

20
Guarding Case Statements
  • Some compilers provide the else clause to avoid
    the out of range errors.
  • Compute gross pay for a particular day
  • case DayNumber of
  • 1, 7 begin 1,7
  • WeekendRate 1.5 DailyRate
  • Gross Hours DailyRate
  • end 1,7
  • 2 . . 6 Gross Hours DailyRate
  • else
  • WriteLn (DayNumber1, ' is an invalid day
    number')
  • end case

21
The CASE Statement with ELSE or OTHERWISE clause
  • Syntax
  • CASE ltselectorgt OF
  • ltlabel list 1gt ltstatement 1gt
  • ltlabel list 2gt ltstatement 2gt
  • ltlabel list Ngt ltstatement Ngt
  • ELSE / OTHERWISE
  • ltstatement 1gt
  • ltstatement 2gt
  • ltstatement Ngt
  • END

22
Example Tax Rate
  • read(GrossIncome) Real typeCASE
    round(GrossIncome) OF 0 null
    statement, do nothing 1..90 Tax
    GrossIncome 0.15 91..320 Tax
    GrossIncome 0.28ELSE optional Tax
    GrossIncome 0.28 Tax Tax
    (GrossIncome 0.0725) END case statement

23
Multiple-AlternativeCASE or extended IF?
  • Use CASE when the condition is a single
    multi-valued expression
  • If several variables are involved in the decision
    use Boolean expressions OR IF-THEN-ELSE statement
    instead
  • Example to see if various criteria are met

Using nested if statements Using Boolean expressions
AllMet FalseIF single THEN IF (Gender 'M') THEN IF Age gt 18 THEN IF Age lt 26 THEN AllMet True AllMet Single AND (Gender 'M') AND (Age gt 18) AND (Age lt 26)
IF AllMet THEN WriteLn ('Current person satisfies the criteria.') ELSE WriteLn ('All Criteria are not satisfied') IF AllMet THEN WriteLn ('Current person satisfies the criteria.') ELSE WriteLn ('All Criteria are not satisfied')
24
These are almost equivalent
  • Cascaded IF-THENIF ltcondition1gt THEN IF
    ltcondition2gt THEN IF ltcondition3gt THEN
    IF ltcondition4gt THEN If
    ltcondition Ngt is false ltcondition N1gt will never
    be evaluated
  • Single IF-THEN with complex Boolean
    expressionIF ltcondition1gt AND ltcondition2gt AND
    ltcondition3gt AND ltcondition4gt THEN
  • If ltcondition Ngt is false ltcondition N1gt will
    never be evaluated if the compiler is using
    short-circuit evaluation

25
Short-Circuit Evaluation
  • Used to speed up evaluation of Boolean
    expressions
  • Boolean conditions combined with AND must all be
    true for the entire expression to be true
  • Boolean conditions combined with OR must all be
    false for the entire expression to be false
  • The compiler can stop evaluating a Boolean
    expression as soon as its value can be determined
  • We can control the evaluation by using compiler
    directives

26
Short-Circuit Evaluation
  • ExampleSingle AND (Gender 'M' ) AND (Age gt
    18) AND (Age lt 26)
  • If Single False
  • The whole expression will be false regardless of
    the values of the rest of the expression
  • There is no need to evaluate the other conditions

27
Short-Circuit Evaluation
  • Example
  • Let X 0
  • If ( X ltgt 0.0 ) and (Y / X gt 5.0 ) then . . .
  • Short circuit evaluation here is important to
    prevent dividing by zero
  • Otherwise the condition should be split into two
    parts
  • If ( X ltgt 0.0 ) then
  • If (Y / X gt 5.0 ) . . .

28
Short-Circuit Evaluation
  • Remember
  • True or anything is always true
  • False and anything is always false
  • Turbo Pascal uses short-circuit by default
  • Standard Pascal doesnt
  • Enable full evaluation by using B
  • This is a compiler directive

29
Short-Circuit Evaluation
  • Compiler directives
  • Comments beginning with the symbol that
    provides instructions to the compiler.
  • B
  • Causes complete evaluation of Boolean expressions
  • B-
  • Causes short-circuit evaluation to take place

30
Case Studies
  • A couple of long programs in Chapter 4
  • Example 4.10, p.171 177
  • p. 190-196
  • Read through these carefully, understand them!!!
    The next quiz may draw from them!
  • Case studies use user-defined procedures and
    functions (Ch 3)
  • We dont study these in the course
  • You dont need to know how to write them
  • You need to understand them

31
User-Defined Functions Procedures
  • Used to
  • encapsulate operations performed frequently,
    possibly with different input
  • to structure programs.
  • Both can take arguments
  • Functions usually do
  • Procedures may not (occasionally)
  • Functions return results
  • They are used in the same place as you would put
    a value, variable, or expression
  • Procedures do not return results
  • They accomplish their work through side effects
  • E.g. writeln has the side effect of printing to
    the screen (or a file)
  • E.g. readln has the side effect of setting its
    argument to the input

32
User-Defined Functions Procedures
  • The argument list (or parameter list contains 2
    types of parameters)
  • Value parameters these are only used for
    inputting information into the function/procedure
  • Functions usually only have these
  • VAR parameters these can be used to transmit
    information back to the caller by storing into
    them as if they were variables
  • Procedures often use VAR parameters
  • VAR parameters used when need to transmit back
    more than one piece of information or data with a
    complex structure
  • Storing into a VAR parameter is a kind of side
    effect

33
Standard or Built-In Functions
  • Standard operations provided by the programming
    language
  • Computation performed more efficiently than if
    the user were to define them
  • Fundamentally 2 types in the language Pascal
  • Numeric Standard Functions
  • Character Standard Functions
  • The particular Pascal implementation (e.g.
    Borlands TurboPascal) may provide more

34
Numeric Standard Functions
Function Name Function Value Argument Type Result Type
sqr square real or integer same as argument
Examples sqr(5) ? 25, sqr(5.0) ? 25.0 sqr(5) ? 25, sqr(5.0) ? 25.0 sqr(5) ? 25, sqr(5.0) ? 25.0
sqrt square root real or integer (non-negative) real
Examples sqrt(25) ? 5.0 sqrt(-25) ? error sqrt(25) ? 5.0 sqrt(-25) ? error sqrt(25) ? 5.0 sqrt(-25) ? error
abs absolute value real or integer same as argument
Examples abs(5) ? 25, abs(-5.0) ? 5.0 abs(5) ? 25, abs(-5.0) ? 5.0 abs(5) ? 25, abs(-5.0) ? 5.0
round rounding real integer
Examples round(2.0) ? 2, round(2.1) ? 2, round(2.5) ? 3, round(2.8) ? 3round(-2.0) ? -2, round(-2.1) ? -2, round(2.5) ? -3, round(2.8) ? -3 round(2.0) ? 2, round(2.1) ? 2, round(2.5) ? 3, round(2.8) ? 3round(-2.0) ? -2, round(-2.1) ? -2, round(2.5) ? -3, round(2.8) ? -3 round(2.0) ? 2, round(2.1) ? 2, round(2.5) ? 3, round(2.8) ? 3round(-2.0) ? -2, round(-2.1) ? -2, round(2.5) ? -3, round(2.8) ? -3
trunc truncation real integer
Examples trunc(2.0) ? 2, trunc(2.1) ? 2, trunc(2.5) ? 2, trunc(2.8) ? 2trunc(-2.0) ? -2, trunc(-2.1) ? -2, trunc(2.5) ? -2, trunc(2.8) ? -2 trunc(2.0) ? 2, trunc(2.1) ? 2, trunc(2.5) ? 2, trunc(2.8) ? 2trunc(-2.0) ? -2, trunc(-2.1) ? -2, trunc(2.5) ? -2, trunc(2.8) ? -2 trunc(2.0) ? 2, trunc(2.1) ? 2, trunc(2.5) ? 2, trunc(2.8) ? 2trunc(-2.0) ? -2, trunc(-2.1) ? -2, trunc(2.5) ? -2, trunc(2.8) ? -2
35
Using Standard Functions
  • Very much the same way you use an (arithmetic)
    operator in an expression
  • Functions return values so
  • Function calls are used like values
  • E.g.
  • Result 5 2 x / 3 3
  • Result sqrt(10)
  • Result 2 sqrt (10)
  • Result Result (1 sqrt(10)) / N

36
Using Standard Function (2)
  • Arguments of standard functions can themselves be
    constants, variables, or expressions. E.g.
  • round(3.5)
  • round(Amount)
  • round(Amount1.065)
  • Make sure they are of the right type
  • This wont work trunc(Var lt 5)

37
Character Standard Functions
  • Ordering a character requires associating an
    integer with each character
  • The type character is an ordinal type
  • The ASCII standard is used for encoding (among
    others)
  • p. 78, Table 2.9
  • See also Appendix 4 Character Sets

38
ASCII Character Encoding
  • Codes 0 to 127 for most things on a Roman
    keyboard
  • Codes 0-31 are non-printable control characters
  • Represented in Pascal as 0 .. 31
  • Code 10 is ENTER
  • Code 32 is (space, blank)
  • Code 33-47 punctuation
  • 0 48 9 57
  • Codes 58-64 more punctuation
  • A 65 Z 90
  • Codes 91-96 more punctuation
  • a 97 z 122
  • Codes 123-126 more punctuation
  • Code 127 is non-printable

39
Character Standard Functions
Function Name Function Value Argument Type Result Type
ord Returns ASCII value char integer
Examples ord(C) ? 67 ord(C) ? 67 ord(C) ? 67
chr Returns associated character integer chr
Examples chr(67) ? C, chr(ord(C)1) ? D chr(67) ? C, chr(ord(C)1) ? D chr(67) ? C, chr(ord(C)1) ? D
pred Returns the predecessor of the number any ordinal type same as argument
Examples pred(C) ? B, pred(67) ? 66, pred(ord(C)) ? 66 pred(C) ? B, pred(67) ? 66, pred(ord(C)) ? 66 pred(C) ? B, pred(67) ? 66, pred(ord(C)) ? 66
succ Returns the successor of the number any ordinal type integer
Examples succ(C) ? D, succ(67) ? 68, succ(ord(C)) ? 68 succ(C) ? D, succ(67) ? 68, succ(ord(C)) ? 68 succ(C) ? D, succ(67) ? 68, succ(ord(C)) ? 68
40
Example Counting Characters
  • see program CHRCOUNT.PAS
  • CASE Ch OF 0..9 Digits
    Digits 1 A..Z,a..z Alpha
    Alpha 1 0..31 Control
    Control 1
  • ELSE optional Other Other 1
  • END case statement

41
Non-printable Characters
  • You can represent them inside the program by
    using the before the character number
  • You cant enter them that way however

42
Self Check 1
  • Write the Boolean expression to check if a
    character variable Ch is a digit.
  • Write a Boolean expression to check if a
    character variable Ch is an upper-case letter.
  • Write a Boolean expression to check if a
    character variable Ch is a lower-case letter.
  • Using a Boolean test, convert upper-case
    character Ch to a lower-case character.

43
Self-Check 2
  • Write Boolean assignment statements
  • Assign true to variable Between if the value of N
    is in the range -K to K, inclusive otherwise,
    assign a value of false
  • Assign a value of true to variable Uppercase if
    Ch is an uppercase letter otherwise, assign
    false
  • Assign a value of true to variable Divisor if M
    is a divisor of N otherwise, assign false

44
Self-Check 3
  • What do these statements display?
  • IF 12 lt 12 THEN writeln(Less)ELSE writeln(No
    t less)
  • Var1 25.12Var2 15.00IF Var1 lt Var2
    THEN writeln(Less or equal)ELSE writeln(Grea
    ter than)

45
Self-Check 4
  • What value is assigned to X when Y is 15.0?
  • X 25.0IF Y ltgt (X - 10.0) THEN X X -
    10.0ELSE X X / 2.0
  • IF (Y lt 15.0) AND (Y gt 0.0) THEN X 5
    YELSE X 2 Y

46
Self-Check 5
  • Write Pascal statements to perform the following
  • If Item is nonzero, then multiply Product by Item
    and save the result in Product otherwise, skip
    the multiplication. In either case, print the
    value of Product.
  • Store the absolute difference of X and Y in Y,
    where the absolute difference is (X - Y) or (Y -
    X), whichever is positive.
  • Dont use the abs() function in your solution

47
Self-Check 6
  • Evaluate the following expressions, with and
    without short-circuit evaluation
  • Assumptions
  • X 6
  • Y 7
  • (X gt 5) and (Y div X lt 10)
  • (X lt 10) or (X / (Y - 7) gt 3)

48
Self-Check 7
  • Implement the following decision table using a
    nested if statement then using a case statement.
  • 0.0-0.99 Failed - registration suspended
  • 1.0-1.99 On probation for next semester
  • 2.0-2.99 (No message)
  • 3.0-3.49 Deans list for semester
  • 3.5-4.0 Highest honors for semester
  • Assumption
  • GPA is within the range 0.0 through 4.0.

49
Self-Check 8
  • Write a case statement that prints a message
    indicating whether NextCh (of type char) is
    either one of the following
  • An operator symbol (, -, , , lt, gt, /)
  • A punctuation mark (comma, semicolon,
    parenthesis, brace, bracket, or colon)
  • A digit.
  • Your program should print the category selected
  • Guard the case statement
  • Write the same program using a nested if statement

50
Common Programming Errors
  • Use semicolons carefully inside if statements.
  • A semicolon before else will indicate the end of
    the if statement.
  • Don't forget to bracket (with begin-end) compound
    statements, otherwise only the statement
    preceding the semicolon will be considered.
Write a Comment
User Comments (0)
About PowerShow.com