CS1010: Programming Methodology http://www.comp.nus.edu.

sg/~cs1010/

Week 4: Selection Statements
Objectives:  Using relational and logical operators  Using selection statements in a program  Formulating complex selection structures to solve decision
problems.

Reference:  Chapter 4 Lessons 4.1 – 4.6, Beginning Decision Making

CS1010 (AY2013/4 Semester 1)

Week4 - 2

Week 4: Outline (1/2)
1. Week 3 Exercises 2. Sequential vs non-sequential control flow 3. Selection Structures
3.1 3.2 3.3 3.4 3.5 3.6 if and if-else Statements Conditions Truth Values Logical Operators Evaluation of Boolean Expressions Short-Circuit Evaluation

4. Indentation Style 5. Quiz 6. Demo #1: Hi-Lo Game

CS1010 (AY2013/4 Semester 1)

Week4 - 3

Week 4: Outline (2/2)
7. 8. 9. 10. 11. 12. 13. 14. 15. Indentation Style Again Exercise #1: Leap Year Demo #2: Maximum of 3 Numbers Very Common Errors Nested if and if-else statements Exercise #2: Taxi Fare switch Statement Demo #3: Zip code reader Exercise #3: NRIC Check Code (take-home)

CS1010 (AY2013/4 Semester 1)

Week4 - 4

Week 3 Exercise #3: Speed of Sound Write a program Week3_SpeedOfSound.92 ft/sec  Bring your program to class next week  This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week4 . Decide on its parameter(s). Formula to compute the speed s in feet/sec: 5T  297 s  1086 247  Values are of type float.80 degree = 1924.1.  You should have a function speed_of_sound() to compute and return the speed.c that calculates the speed of sound (s) in air of a given temperature T (oF).8 Speed of sound in air of 95.  Sample run (values printed in 2 decimal places): Temperature in degree Fahrenheit: 95.5 .

c that reads two positive integers (with at most 5 digits) and for each. we get 16.6 . 5 and 7. Decide on its parameter(s). then adding up the digits 4. The answer is hence 6. The right-most digit of the sum is the required answer. Week 3 Exercise #4: Magic Number Write a program Week3_MagicNumber. adds up the digits (from right) in positions 1.1.  You should have a function get_magic() to compute and return the answer. 3. What is the precondition of the function?  Sample run: Enter Magic Enter Magic 1st value: 76524 number = 6 2nd value: 8946 number = 5  Bring your program to class next week  This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week4 . and 5. if input is 76524.  For example.

Pop Quiz (1/2)  What is the output of this code and what value does the function f() return?  CS1010 (AY2013/4 Semester 1) Week4 .7 .

8 .Pop Quiz (2/2)  What is the output of this code?  CS1010 (AY2013/4 Semester 1) Week4 .

a male stick figure.2. Draw Triangle rocket Draw Rocket Ship Draw Rectangle Draw Inverted V Draw Circle male Draw 3 Figures Draw Male Stick Figure Draw Rectangle Draw Inverted V Draw Circle Draw Triangle Draw Female Stick Figure Draw Inverted V female CS1010 (AY2013/4 Semester 1) Week4 . Sequential Control Flow Recall last week‟s Simple “Drawing” Problem: Write a program to draw a rocket ship. and a female stick figure.9 .

or (3) a female stick figure.10 . (2) male stick figure.2. Draw Triangle Select only one Draw 3 Figures Draw Rocket Ship Draw Rectangle Draw Inverted V Draw Circle Draw Male Stick Figure Draw Rectangle Draw Inverted V Draw Circle Draw Triangle Draw Female Stick Figure Draw Inverted V CS1010 (AY2013/4 Semester 1) Week4 . Non-sequential Control Flow New Requirement: Write a program to allow the user to select only one of the following options: Draw a (1) rocket ship.

Selection Structures  C provides two control structures that allow you to select a group of statements to be executed or skipped when certain conditions are met. CS1010 (AY2013/4 Semester 1) Week4 .11 .3.

1 if and if-else Statements  true cond? if statement How are conditions specified and how are they evaluated? false if ( condition ) { /* Execute these statements if TRUE */ } Braces { } optional only if there is one statement in the block.12 .3.  true cond? false if-else statement if ( condition ) { /* Execute these statements if TRUE */ } else { /* Execute these statements if FALSE */ } CS1010 (AY2013/4 Semester 1) Week4 .

Relational operators  Examples: ( a <= 10 ). ( value != -9 ) Relational Operator < <= > >= == != Interpretation is less than is less than or equal to is greater than is greater than or equal to is equal to is not equal to Week4 . ( count > max ).2 Condition    A condition is an expression evaluated to true or false.13 CS1010 (AY2013/4 Semester 1) .3. It is composed of expressions combined with relational operators.

3 Truth Values (1/2)   Boolean values: true / false. a. Instead. printf("a = %d. b = %d\n".3. There is no boolean type in ANSI C.  CS1010 (AY2013/4 Semester 1) Week4 . b).14 . we use integers:   0 to represent false Any other value to represent true (1 is used as the representative value for true in output) Week4_TruthValues.c  Example: int a = (2 > 3). int b = (3 > 2).

// 13 assigned to a // 1 assigned to b // 6 assigned to c  You are certainly not encouraged to write such convoluted codes! CS1010 (AY2013/4 Semester 1) Week4 . Since the values 0 and 1 are the returned values for false and true respectively. int c = ( (4 > 5) < (3 > 2) ) * 6.15 .3.3 Truth Values (2/2)   Be careful of the value returned/evaluated by a relational operation. int b = (4 > 5) < (3 > 2) * 6. we can have codes like these: int a = 12 + (5 >= 2).

CS1010 (AY2013/4 Semester 1) Week4 . go to A&E immediately. Examples:   If temperature is greater than 40C or blood pressure is greater than 200.3.  Logical operators are needed: && (and). A False False True True B False True False True A && B False False False True A || B False True True True !A True True False False Note: There are bitwise operators such as & .16 . || (or).4 Logical Operators   Complex conditions: combine two or more boolean expressions. but we are not covering these in CS1010. If all the three subject scores (English. recommend taking Higher Mother Tongue. | and ^. Maths and Science) are greater than 85 and mother tongue score is at least 80. ! (not).

gcc issues warning (why?)  Example #2: What is the value of x? x = ((a > b) && !(b > c)). c = 0. See Week4_EvalBoolean.17 .c  CS1010 (AY2013/4 Semester 1) Week4 . Example #1: What is the value of x? int x. b = -2.3. x = (a > b && b > c || a == b).5 Evaluation of Boolean Expressions (1/2)   The evaluation of a boolean expression proceeds according to the precedence and associativity of the operators. a = 4.

5 Evaluation of Boolean Expressions (2/2)  Precedence Operator Type Operator Associativity L to R R to L L to R Primary expression ( ) [ ] .! ~ ++expr --expr (typecast) sizeof * / % + < > <= >= == != && || Ternary operator Assignment operators ?: = += -= *= /= %= R to L R to L CS1010 (AY2013/4 Semester 1) Week4 .3.18 . -> expr++ expr-operators Unary operators Binary operators * & + .

. . skip evaluating expr2.). as the result will always be false.  Short-circuit evaluation uses the following facts:  expr1 || expr2 : If expr1 is true.  CS1010 (AY2013/4 Semester 1) Week4 . expr1 && expr2: If expr1 is false. skip evaluating expr2.6 Short-circuit Evaluation  Does the following code give an error if a is zero? if ((a != 0) && (b/a > 3)) printf(.19 . as the result will always be true.3.

} else { statements. } else { statements. } else { statements. } if (cond) { statements. } Closing braces not aligned with if/else keyword. } else { statements. Indentation Style  Acceptable if (cond) { statements. } if (cond) { statements. } else No indentation! { statements. } if (cond) { statements.20 . CS1010 (AY2013/4 Semester 1) Week4 .4. }  Not acceptable if (cond) { statements.

Assume that a is an int variable. They are not considered convoluted. A if (a == 0) { … } if (a != 0) { … } B if (a) { … } if (!a) { … }   Codes in (B) are very frequently encountered in C programming. Quiz (1/2)  Match each condition in (A) to its equivalent condition in (B).5. Week4 .21 CS1010 (AY2013/4 Semester 1) .

5. how can you correct it?   CS1010 (AY2013/4 Semester 1) Week4 . printf("Line 3\n"). is the following condition correct? Why? if (a > b > c) If it is wrong. Quiz (2/2)  What is the output of the following code? if (x <= y) printf("Line 1\n"). b and c are int variables.22 . printf("Line 2\n").  Assuming that a.

larger than. etc. or equal to the jackpot. “too low”. Analysis     Inputs: jackpot number.6.23 . your guess Outputs: appropriate messages (“too high”.) CS1010 (AY2013/4 Semester 1) Week4 . Demo #1: Hi-Lo Game  User to guess a secret jackpot number (between 1 and 10). Program responses according to whether user‟s guess is smaller than.

&guess).) Can we change the 3 „if‟ statements into a single nested „if-else‟ statement? Week4 . Demo #1: Hi-Lo Game (version 1) // Hi-Lo Game version 1 #include <stdio. printf("Please type your guess: "). scanf("%d".6. Week4_HiLo_v1. jackpot = 8.\n").24 CS1010 (AY2013/4 Semester 1) . return 0. We need random number (you‟ll learn that in discussion session.h> int main(void) { int guess. if (guess == jackpot) printf("You hit the JACKPOT!\n"). if (guess > jackpot) printf("Sorry.c printf("Guess the jackpot number between 1 and 10!\n"). if (guess < jackpot) printf("Sorry. your guess is too high. your guess is too low.\n"). }   Jackpot is fixed to 8! No fun.

your guess is too low. printf("Please type your guess: "). else if (guess > jackpot) printf("Sorry.25 CS1010 (AY2013/4 Semester 1) .h> int main(void) { int guess. if (guess < jackpot) printf("Sorry. Week4_HiLo_v2.c printf("Guess the jackpot number between 1 and 10!\n"). your guess is too high.\n"). return 0. }  Is this single nested „if-else‟ statement better than 3 „if‟ statements? Why? Week4 .\n"). else printf("You hit the JACKPOT!\n").6. jackpot = 8. Demo #1: Hi-Lo Game (version 2) // Hi-Lo Game version 2 #include <stdio. scanf("%d". &guess).

CS1010 (AY2013/4 Semester 1) This follows the indentation guideline. else if (marks >= 50) printf("Grade D\n").26 .7. Example:   // marks is an int variable if (marks >= 90) printf("Grade A\n"). Week4 . else if (marks >= 60) printf("Grade C\n"). but for such cases the code tends to be long and skew to the right. else if (marks >= 75) printf("Grade B\n"). Indentation Style Again (1/2)  Week4_HiLo_v2.c shows a simple case of a frequently encountered selection structure: if-else-if. else printf("Grade F\n").

Week4 . Indentation Style Again (2/2)  Alternative (and preferred) indentation style for the ifelse-if structure is shown on the right // marks is an int variable if (marks >= 90) printf("Grade A\n"). else if (marks >= 75) printf("Grade B\n").27 . CS1010 (AY2013/4 Semester 1) // marks is an int variable if (marks >= 90) printf("Grade A\n").7. else printf("Grade F\n"). else if (marks >= 60) printf("Grade C\n"). else printf("Grade F\n"). else if (marks >= 75) printf("Grade B\n"). else if (marks >= 50) printf("Grade D\n"). else if (marks >= 60) printf("Grade C\n"). else if (marks >= 50) printf("Grade D\n").

or … It is divisible by 400 Week4 . or 0 (false) otherwise Input: a 4-digit positive integer Output: “xxxx is a leap year” or “xxxx is not a leap year” where xxxx is the year Year is a leap year if it is divisible by 4 but not by 100.  It should have a function int isLeapYear(int) with the year as the parameter and returns 1 (true) if it is a leap year.8.28  Analysis:    Design:   CS1010 (AY2013/4 Semester 1) . Exercise #1: Leap Year (1/2)  Problem: Write a modular program Week4_LeapYear.c to determine whether a year is a leap year.

29 .8. Exercise #1: Leap Year (2/2)  Are these leap years?      1997 2002 1996 2000 1900    2100 2400 2300  CS1010 (AY2013/4 Semester 1) Week4 .

 Version #1 Week4_FindMax_v1. Demo #2: Maximum of 3 Numbers (1/2)  Problem: Find the maximum among 3 integer values.  Spot the error.9.30 CS1010 (AY2013/4 Semester 1) . int num3) { int max = 0. can we change the 3 independent ‘if’ statement to a nested ‘if-else’ statement? Week4 . return max. }  After correcting the error. if ((num3 > num1) && (num3 > num2)) max = num3.c int getMax(int num1. if ((num2 > num1) && (num2 > num3)) max = num2. int num2. if ((num1 > num2) && (num1 > num3)) max = num1.

else if (num2 > max) max = num2.31 .  Spot the error. Demo #2: Maximum of 3 Numbers (2/2)  Another version: Week4_FindMax_v2. int num3) { int max = 0. } CS1010 (AY2013/4 Semester 1) Week4 . else if (num3 > max) max = num3. return max.9. if (num1 > max) max = num1.c int getMax(int num1. int num2.

else printf("a is not larger than 10\n").32 . int a = 3.10. if (a > 10). printf("Next line\n”). printf("Next line\n”). CS1010 (AY2013/4 Semester 1) Week4 . Spot the errors. printf("a is larger than 10\n"). printf("a is larger than 10\n"). One is caught by the compiler but the other is not (which make it very hard to detect). int a = 3. if (a > 10). Very Common Errors  The code fragments below contain some very common errors.

If it is a weekend. Nested if and if-else Statements  Nested if (if-else) structures refer to the containment of an if (if-else) structure within another if (if-else) structure. you will be in school from 8 am to 6 pm. CS1010 (AY2013/4 Semester 1) Week4 . do revision from 6 pm to 12 midnight. and sleep from 12 midnight to 8 am. then you will sleep from 12 midnight to 10 am and have fun from 10 am to 12 midnight.11.33 . For example    If it is a weekday.

 Eg: If boardHour and boardMin are 14 and 27 respectively. and computes the taxi fare:    dayType: 0 represents weekends and public holidays (PH for short). then boardTime is 867. int boardTime. It is the number of minutes since 0:00hr. int distance)  Your program should have a function  The parameter boardTime is converted from the input data boardHour and boardMin.34 . in metres float computeFare(int dayType.com/taxi-fare/ Write a program Week4_TaxiFare.c that reads the following input data (all are of int type) from the user. Exercise #2: Taxi Fare (1/4)   The taxi fare structure in Singapore must be one of the most complex in the world! See http://www.taxisingapore.12. CS1010 (AY2013/4 Semester 1) Week4 . boardMin: the hour and minute the passengers board the taxi (eg: 14 27 if the passengers board the taxi at 2:27 PM) distance: the distance of the journey. 1 represents weekdays and non-PH boardHour.

2km $3.12.22  Surcharge (applicable at the time of boarding): Midnight charge (12am – 5:59am) 50% of metered fare 50% of metered fare Peak hour charge (6am – 9:29am) None Peak hour charge (6pm – 11:59pm) 25% of metered fare dayType 0: Weekends & PH 1: Weekdays and non-PH 25% of metered fare 25% of metered fare CS1010 (AY2013/4 Semester 1) Week4 .40 $0. In this exercise.2km Every 350m thereafter or less after 10. Exercise #2: Taxi Fare (2/4)  To implement the actual taxi fare could be a PE question .22 $0. we use a (grossly) simplified fare structure:  Basic Fare: Flag-down (inclusive of 1st km or less) Every 400m thereafter or less up to 10.35 .

83 Day type: 1 Boarding hour and minute: 5 59 Distance: 9000 Total taxi fare is $11.26 Surcharge = 25%  $6. Sample runs below for your checking Day type: 0 Boarding hour and minute: 14 27 Distance: 10950 Total taxi fare is $9.40 Next 9. This exercise is mounted on CodeCrunch.22 = $5.12 Day type: 1 Boarding hour and minute: 9 20 Distance: 6123 Total taxi fare is $7.40 Next 5123m: 13  $0.22 = $0. Complete the program.2km: 23  $0.70 First 1km: $3.66 Basic fare = $9.c.90 Total fare = $11.36 CS1010 (AY2013/4 Semester 1) .40 Next 8km: 20  $0.12 No surcharge Total fare = $9.57 Total fare = $7.80 = $3.22 = $4.70 Week4 .22 = $2.83 First 1km: $3.40 Basic fare = $7.06 Next 750m: 3$0.26 = $1. Exercise #2: Taxi Fare (3/4)   You are given an incomplete program Week4_TaxiFarePartial.80 Surcharge = 50%  $7.12.86 Basic fare = $6.12 First 1km: $3.

In this case. Exercise #2: Taxi Fare (4/4)  Note that due to inaccuracy of floating-point number representation. just treat your answer as correct. Hence. the result may defer slightly from the model output CodeCrunch refers to. depending on how you code your formula to compute the taxi fare.  CS1010 (AY2013/4 Semester 1) Week4 .12.37 . if the difference is very small (probably in the second decimal place). your program may fail CodeCrunch test.

switch Statement   An alternative to if-else-if (section 7) is to use the switch statement.13.. Syntax: switch ( <variable> ) { case value1: Code to execute break. } if <variable> == value1 if <variable> == value2 if <variable> does not equal the any of the cases Restriction: variable must be of discrete type (eg: int.38 CS1010 (AY2013/4 Semester 1) .. case value2: Code to execute break. default: Code to execute value following break. char). Week4 . .

CS1010 (AY2013/4 Semester 1) Week4 . 2.14. invalid ZIP Code. Demo #3: ZIP Code Reader (1/2)  Write a program that reads in a ZIP Code and uses the first digit to print the associated geographic area: if zip code begins with 0.  Note: <zip> represents the entered ZIP Code value. the West. the Central Plains area.39 . 3 4–6 7 8–9 other print this message <zip> is <zip> is <zip> is <zip> is <zip> is on in in in an the East Coast. the South.

zip). break.14.\n". default: printf("%d is an invalid ZIP code. scanf("%d". case 8: case 9: printf("%d is in the West. &zip).h> int main(void) { int zip. } CS1010 (AY2013/4 Semester 1) Week4 . case 4: case 5: case 6: printf("%d is in the Central Plains.\n". printf("Enter a 6-digit ZIP code: ").c . zip). zip).40 Week4_ZipCode. zip).\n".\n". } // end switch return 0. break. switch (zip/100000) { case 0: case 2: case 3: printf("%06d is on the East Coast. zip). case 7: printf("%d is in the South. Demo #3: ZIP Code Reader (2/2) #include <stdio. break. break.\n".

3. Exercise #3: NRIC Check Code (1/4)  Algorithm for NRIC check code  NRIC consists of 7 digits.2 and add them up.6.  Eg: 8730215  Step 1: Multiply the digits with corresponding weights 2.  Eg: 104 % 11 = 5 CS1010 (AY2013/4 Semester 1) Week4 .41 .  Eg: 82 + 77 + 36 + 05 + 24 + 13 + 52 = 16+49+18+0+8+3+10 = 104  Step 2: Divide step 1 result by 11 to obtain the remainder.4.5.7.15.

42 . Exercise #3: NRIC Check Code (2/4)  Algorithm for NRIC check code (cont…)  Step 3: Subtract step 2 result from 11  Eg: 11 – 5 = 6  Step 4: Match step 3 result in this table for the check code 1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I 10 11 Z J  Eg: The check code corresponding to 6 is „F‟.  Sample run: CS1010 (AY2013/4 Semester 1) Enter 7-digit NRIC number: 8730215 Check code is F Week4 . the check code for 8730215 is „F‟.15.  Therefore.

Your program may be long now. This exercise is mounted on CodeCrunch.  You need to use the char type. such as array.15. This is your take-home exercise.  The format specifier for char type is %c (to be used in a printf() statement).)  A character constant is enclosed in single quotes (eg: 'A'. (Explore this on your own.c to generate the check code given  a 7-digit NRIC number. You can write an improved version later. Your program should include a function char generateCode(int) that takes in a single integer (the NRIC number) and returns a character (which is the check code). Do not use techniques that are not covered in class. 'Z'). Exercise #3: NRIC Check Code (3/4)  Write a program Week4_NRIC.43    CS1010 (AY2013/4 Semester 1) . Week4 .

we want to use an approach that is more “portable”.15. Please do not do the following (especially for students who are more experienced in programming):  use string (array of characters) and extract out the individual  digit characters and convert each of them into a numeric digit.44 . The %1d method may not be possible in some other programming languages. Exercise #3: NRIC Check Code (4/4)  The intention of this exercise is to let you handle a single integer input (assigned to an integer variable) and then extract the 7 individual digits from it. and also. CS1010 (AY2013/4 Semester 1) Week4 . or  use %1d%1d%1d%1d%1d%1d%1d in the scanf() statement to read in 7 digits separately into 7 variables.  We want to limit the technique to what we have covered in this week‟s lecture.

Summary for Today  Today‟s most important lessons   if and if-else statements switch statement CS1010 (AY2013/4 Semester 1) Week4 .45 .

7 (pg 191 – 193)   A few practical exercises (besides Exercises #2 and #3. Beginning Decision Making Read Application Programs 4.1 (pg 176 – 179) and 4.46 . Saturday.Announcements/Things-to-do  Revise Chapter 4 Lessons 4. 9am Next week is e-learning week  No lecture  Please view videos (details will be anounced later)   CS1010 (AY2013/4 Semester 1) Week4 .6.1 – 4. and simpler than these two) on Selection statements are on CodeCrunch Lab #2 has been released  Deadline: 14th September 2013.

End of File .

Sign up to vote on this title
UsefulNot useful