0% found this document useful (0 votes)
2 views

Chapter4Control Statements Nva

Uploaded by

adrian.mohanta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter4Control Statements Nva

Uploaded by

adrian.mohanta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

PROGRAMMING METHODOLOGY

CS1010 (AY2012/3 Semester 1)

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

Week4 - 2
CS1010 (AY2012/3 Semester 1)

Week 4: Outline (1/2)


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

Week4 - 3
CS1010 (AY2012/3 Semester 1)

3. 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.

if … else…
switch
Week4 - 4
CS1010 (AY2012/3 Semester 1)

3.1 if and if-else Statements true


cond?

How are conditions specified false


• if statement and how are they evaluated?

if ( condition ) {
/* Execute these statements if TRUE */
}

Example

Week4 - 5
CS1010 (AY2012/3 Semester 1)

3.1 if and if-else Statements


Braces { } optional only if there is one true false
cond?
statement in the block.
 if-else statement
if ( condition ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}

Example

Week4 - 6
CS1010 (AY2012/3 Semester 1)

3.1 if and if-else Statements

Week4 - 7
CS1010 (AY2012/2013 Semester 1)

3.2 Condition
• A condition is an expression evaluated to true or false.
• It is composed of expressions combined with relational
operators.
• Relational operators
• Examples: ( a <= 10 ), ( count > max ), ( 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 - 8
CS1010 (AY2012/3 Semester 1)

3.3 Truth Values (1/2)


• Boolean values: true / false.
• There is no boolean type in ANSI C. Instead, we use
integers:
• 0 to represent false
• Any other value to represent true (1 is used as the representative
value for true in output)
• Example:
Week4_TruthValues.c
int a = (2 > 3);
int b = (3 > 2);

printf("a = %d; b = %d\n", a, b);

 Week4 - 9
CS1010 (AY2012/3 Semester 1)

3.3 Truth Values (1/2)


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

Week4 - 10
CS1010 (AY2012/3 Semester 1)

3.4 Logical Operators


• Complex conditions: combine two or more boolean expressions.
• Examples:
• If temperature is greater than 40C or blood pressure is greater than 200, go
to A&E immediately.
• If all the three subject scores (English, Maths and Science) are greater than
85 and mother tongue score is at least 80, recommend taking Higher
Mother Tongue.
• Logical operators are needed: && (and), || (or), ! (not).

A B A && B A || B !A
False False False False True
Note: There are bitwise
False True False True True
operators such as & , | and
True False False True False ^, but we are not covering
True True True True False these in CS1010.

Week4 - 11
CS1010 (AY2012/3 Semester 1)

3.5 Evaluation of Boolean


Expressions (1/2)
• The evaluation of a boolean expression proceeds
according to the precedence and associativity of the
operators.
• Example #1: What is the value of x?

int x, a = 4, b = -2, c = 0; gcc issues warning (why?)


x = (a > b && b > c || a == b);

 Example #2: What is the value of x?


x = ((a > b) && !(b > c));

See Week4_EvalBoolean.c
 Week4 - 12
CS1010 (AY2012/3 Semester 1)

3.5 Evaluation of Boolean


Expressions (2/2)
• Lesson 4.5 Precedence of Logical Operators (pg 142-143)
Operators Name Associativity Precedence
() Parentheses L to R 1 (highest)
++, -- Post-increment L to R 2
++, -- Pre-increment R to L 2
! Logical NOT L to R 3
+, - Positive, negative sign L to R 3
*, /, % Multiplication, division, mod L to R 4
+, - Addition, subtraction L to R 5
==, >=, <=, >, <, != Relational operator L to R 6
&& Logical AND L to R 7
|| Logical OR L to R 8
=, +=, -=, *=, /=, %= Assignment R to L 9 (lowest)

Note error in reference book.


Week4 - 13
3.6 Short-circuit Evaluation
• Does the following code give an error if a is zero?
if ((a != 0) && (b/a > 3))
printf(. . .);

 Short-circuit evaluation uses the following facts:


 expr1 || expr2 : If expr1 is true, skip evaluating expr2, as the
result will always be true.

 expr1 && expr2: If expr1 is false, skip evaluating expr2, as the


result will always be false.

CS1010 (AY2011/2 Semester 1) Week4 - 14


CS1010 (AY2012/3 Semester 1)

4. Indentation Style
• Acceptable  Not acceptable
if (cond) { if (cond) if (cond)
statements; { {
} statements; statements;
else { } }
statements; else else No indentation!
} { {
statements; statements;
if (cond) { } }
statements;
} else { if (cond) {
statements; statements; }
} else {
statements; }
Closing braces not
aligned with if/else
keyword.
Week4 - 15
CS1010 (AY2012/3 Semester 1)

5. Quiz (1/2)
• Match each condition in (A) to its equivalent condition in
(B). Assume that a is an int variable.
A B

if (a == 0) { if (a) {
… …
} }

if (a != 0) { if (!a) {
… …
} }

 Codes in (B) are very frequently encountered in C


programming. They are not considered convoluted.
 Week4 - 16
CS1010 (AY2012/3 Semester 1)

5. Quiz (2/2)
• What is the output of the following code?

if (x <= y)
printf("Line 1\n");
printf("Line 2\n");
printf("Line 3\n");

 Assuming that a, b and c are int variables, is the


following condition correct? Why?
if (a > b > c)
 If it is wrong, how can you correct it?

 Week4 - 17
CS1010 (AY2012/3 Semester 1)

6. 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, larger than, or equal to the jackpot.
• Analysis
• Inputs: jackpot number, your guess
• Outputs: appropriate messages (“too high”, “too low”, etc.)

Week4 - 18
CS1010 (AY2012/3 Semester 1)

6. Demo #1: Hi-Lo Game


(version 1)
Week4_HiLo_v1.c
// Hi-Lo Game version 1
#include <stdio.h>
int main(void) {
int guess, jackpot = 8;

printf("Guess the jackpot number between 1 and 10!\n");


printf("Please type your guess: ");
scanf("%d", &guess);

if (guess < jackpot)


printf("Sorry, your guess is too low.\n");

if (guess > jackpot)


printf("Sorry, your guess is too high.\n");

if (guess == jackpot)
printf("You hit the JACKPOT!\n");
 Jackpot is fixed to 8! No fun. We need random
return 0;
} number (you’ll learn that in discussion session.)
 Can we change the 3 ‘if’ statements into a single
nested ‘if-else’ statement?
Week4 - 19
CS1010 (AY2012/3 Semester 1)

6. Demo #1: Hi-Lo Game


(version 2)
// Hi-Lo Game version 2
Week4_HiLo_v2.c
#include <stdio.h>

int main(void) {
int guess, jackpot = 8;

printf("Guess the jackpot number between 1 and 10!\n");


printf("Please type your guess: ");
scanf("%d", &guess);

if (guess < jackpot)


printf("Sorry, your guess is too low.\n");

else if (guess > jackpot)


printf("Sorry, your guess is too high.\n");

else
printf("You hit the JACKPOT!\n");

return 0;
}
 Is this single nested ‘if-else’ statement better than 3 ‘if’
statements? Why?

Week4 - 20
CS1010 (AY2012/3 Semester 1)

7. Indentation Style Again (1/2)


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

Week4 - 21
CS1010 (AY2012/3 Semester 1)

7. Indentation Style Again (2/2)


 Alternative (and preferred) indentation style for the if-
else-if structure is shown on the right

// marks is an int variable // marks is an int variable


if (marks >= 90) if (marks >= 90)
printf("Grade A\n"); printf("Grade A\n");
else else if (marks >= 75)
if (marks >= 75) printf("Grade B\n");
printf("Grade B\n"); else if (marks >= 60)
else printf("Grade C\n");
if (marks >= 60) else if (marks >= 50)
printf("Grade C\n"); printf("Grade D\n");
else else
if (marks >= 50) printf("Grade F\n");
printf("Grade D\n");
else
printf("Grade F\n");

Week4 - 22
CS1010 (AY2012/3 Semester 1)

8. Exercise #1: Leap Year (1/2)


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

Week4 - 23
CS1010 (AY2012/3 Semester 1)

8. Exercise #1: Leap Year (2/2)


 Are these leap years?
 1997
 2002
 1996
 2000
 1900
 2100
 2400
 2300

 Week4 - 24
CS1010 (AY2012/3 Semester 1)

9. Demo #2: Maximum of 3


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

Week4 - 25
CS1010 (AY2012/3 Semester 1)

9. Demo #2: Maximum of 3


Numbers (2/2)
 Another version:
Week4_FindMax_v2.c
int getMax(int num1, int num2, int num3) {
int max = 0;
if (num1 > max)
max = num1;
else if (num2 > max)
max = num2;
else if (num3 > max)
max = num3;
return max;  Spot the error.
}

Week4 - 26
CS1010 (AY2012/3 Semester 1)

10. Very Common Errors


• The code fragments below contain some very common
errors. One is caught by the compiler but the other is not
(which make it very hard to detect). Spot the errors.
int a = 3;
if (a > 10);
printf("a is larger than 10\n");
printf("Next line\n”);

int a = 3;
if (a > 10);
printf("a is larger than 10\n");
else
printf("a is not larger than 10\n");
printf("Next line\n”);

Week4 - 27
CS1010 (AY2012/3 Semester 1)

11. 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.
• For example
• If it is a weekday, you will be in school from 8 am to 6 pm, do
revision from 6 pm to 12 midnight, and sleep from 12 midnight to 8
am.
• If it is a weekend, then you will sleep from 12 midnight to 10 am
and have fun from 10 am to 12 midnight.

Week4 - 28
CS1010 (AY2012/3 Semester 1)

Nested if-else example


Nested if statements

Sequence of if statements
CS1010 (AY2012/3 Semester 1)

Multiple alternatives
CS1010 (AY2012/3 Semester 1)

Nested if else
CS1010 (AY2012/3 Semester 1)

13. switch Statement


• An alternative to if-else-if (section 7) is to use the switch statement.
• Syntax:

switch ( <variable> ) {
case value1:
Code to execute if <variable> == value1
break;
case value2:
Code to execute if <variable> == value2
break;
...
default:
Code to execute if <variable> does not equal the
value following any of the cases
break;
}
Restriction: variable must be of discrete type
(eg: int, char).

Week4 - 32
CS1010 (AY2012/3 Semester 1)

Example
CS1010 (AY2012/3 Semester 1)

Summary for Today


 Today’s most important lessons
 if and if-else statements
 switch statement

Week4 - 34
CS1010 (AY2012/3 Semester 1)

Problems
End of File

You might also like