490 likes | 679 Views
CMP 131 Introduction to Computer Programming. Violetta Cavalli-Sforza Week 8, Lecture (Monday). MONDAY. Midterm results Statistics (next slide) Go over midterm. Midterm Statistics. WEDNESDAY. Multiple choice conditionals Review extended IF statement CASE statement Standard Functions.
E N D
CMP 131Introduction to Computer Programming Violetta Cavalli-Sforza Week 8, Lecture (Monday)
MONDAY • Midterm results • Statistics (next slide) • Go over midterm
WEDNESDAY • Multiple choice conditionals • Review extended IF statement • CASE statement • Standard Functions
Multiple Choice Alternatives • Do something different if Grade = A, B, C, D, F, … • Compute frequencies (histogram): • If Input is < 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 > ValN increment IntervalN
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’
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; END.
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?
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; END.
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; END.
Complex Condition • Why:IF (Grade = 'A') OR (Grade = 'a') THEN …and notIF Grade = 'A' OR Grade = 'a' THEN …? • Try compilingIF Grade = 'A' OR Grade = 'a' THEN … • Result • Error 41: Operand types do not match operator
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.
Operator Precedence: Arithmetic, Relational and Logical OperatorPrecedence ( ) parentheses Highest (evaluated first) - + NOT (unary operators) * / DIV MOD AND + - OR < <= = <> >= > Lowest (evaluated last)
Example: Exam Score Intervals Exam score Grade Assigned 90 & above A 80-89 B 70-79 C 60-69 D Below 60 F
Example: Exam Scores Intervals (2) Correct grade assignmentIncorrect grade assignment if score >= 90 then if Score >= 60 then Write ('A') Write ('D') else if Score >= 80 then else if Score >= 70 then Write ('B') Write ('C') else if Score >= 70 then else if Score >= 80 then Write ('C') Write ('B') else if Score >= 60 then else if Score >= 90 then Write ('D') Write ('A') else else Write ('F') Write ('F')
Multiple Choice Conditionals: The CASE Statement Syntax: CASE <selector> OF <label list 1> : <statement 1> ; <label list 2> : <statement 2> ; … <label list N> : <statement N> END
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?
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
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 >= 1) AND (DayNumber <= 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 (DayNumber:1, ' is an invalid day number')
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 (DayNumber:1, ' is an invalid day number') end {case}
The CASE Statement with ELSE or OTHERWISE clause Syntax: CASE <selector> OF <label list 1> : <statement 1> ; <label list 2> : <statement 2> ; … <label list N> : <statement N> ELSE / OTHERWISE <statement 1> ; <statement 2> ; … <statement N> END
Example: Tax Rate read(GrossIncome); {Real type}CASE round(GrossIncome) OF0 : ; { null statement, do nothing }1..90 : Tax := GrossIncome * 0.15;91..320: Tax := GrossIncome * 0.28;ELSE { optional }Tax := GrossIncome * 0.28;Tax := Tax + (GrossIncome * 0.0725); END { case statement }
Multiple-Alternative:CASE 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
These are almost equivalent • Cascaded IF-THEN:IF <condition1> THEN IF <condition2> THEN IF <condition3> THEN IF <condition4> THEN …If <condition N> is false <condition N+1> will never be evaluated • Single IF-THEN with complex Boolean expression:IF <condition1> AND <condition2> AND <condition3> AND <condition4> … THEN If <condition N> is false <condition N+1> will never be evaluated if the compiler is using short-circuit evaluation
Short-Circuit Evaluation • Used to speed up evaluation of Boolean expressions • Boolean conditions combined with ANDmust all be true for the entire expression to be true • Boolean conditions combined with ORmust 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
Short-Circuit Evaluation • Example:Single AND (Gender = 'M' ) AND (Age >= 18) AND (Age <= 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
Short-Circuit Evaluation • Example: • Let X = 0 If ( X <> 0.0 ) and (Y / X > 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 <> 0.0 ) then If (Y / X > 5.0 ) . . .
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 doesn’t • Enable full evaluation by using {$B+} • This is a compiler directive
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
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 don’t study these in the course • You don’t need to know how to write them • You need to understand them
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. write[ln] has the side effect of printing to the screen (or a file) • E.g. read[ln] has the side effect of setting its argument to the input
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
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. Borland’s TurboPascal) may provide more
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
Using Standard Function (2) • Arguments of standard functions can themselves be constants, variables, or expressions. E.g.: • round(3.5) • round(Amount) • round(Amount*1.065) • Make sure they are of the right type: • This won’t work: trunc(Var <= 5)
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
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
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 }
Non-printable Characters • You can represent them inside the program by using the ‘#’ before the character number • You can’t enter them that way however…
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.
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
Self-Check 3 • What do these statements display? • IF 12 < 12 THEN writeln(‘Less’)ELSE writeln(‘Not less’) • Var1 := 25.12;Var2 := 15.00;IF Var1 <= Var2 THEN writeln(‘Less or equal’)ELSE writeln(‘Greater than’)
Self-Check 4 • What value is assigned to X when Y is 15.0? • X := 25.0;IF Y <> (X - 10.0) THEN X := X - 10.0ELSE X := X / 2.0 • IF (Y < 15.0) AND (Y >= 0.0) THEN X := 5 * YELSE X := 2 * Y
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. • Don’t use the abs() function in your solution
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 Dean’s list for semester 3.5-4.0 Highest honors for semester • Assumption: • GPA is within the range 0.0 through 4.0.
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 (+, -, *, =, <, >, /) • 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
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.