l4 - control flow statements i

42
CS1010E Programming Methodology Control Flow Statements Part I

Upload: koiuy12

Post on 17-Jul-2016

22 views

Category:

Documents


1 download

DESCRIPTION

l

TRANSCRIPT

Page 1: L4 - Control Flow Statements I

CS1010E Programming Methodology

Control Flow StatementsPart I

Page 2: L4 - Control Flow Statements I

Lecture Overview Making a Choice The if statement The relational operators The if-else statement

Repeating Computation The while statement

Problem Solving Examples

[ CS1010E AY1112S1 Lecture 4 ] 2

Page 3: L4 - Control Flow Statements I

Selection Statements Recall the three types of control structures to

control execution flow in a algorithm Sequence Selection Repetition

We have seen sequence in the programs so far

C Programming Language provides: Selection statements to selectively execute

portion of your code

3[ CS1010E AY1112S1 Lecture 4 ]

Page 4: L4 - Control Flow Statements I

The if statement: Syntax

if is a keyword The complete if-statement is a single statement

Behaviour: The statement_A is executed only if the condition

is true

SYN

TAX if ( condition )

statement_A

4[ CS1010E AY1112S1 Lecture 4 ]

Page 5: L4 - Control Flow Statements I

What is a Condition?

A condition is an expression evaluated to be 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

Relational Operator

Interpretation

>= is greater than or equal to== is equal to!= is not equal to

[ CS1010E AY1112S1 Lecture 4 ] 5

Page 6: L4 - Control Flow Statements I

Truth Values

The result of evaluating a relation operation is a Booleanvalue: true or false.

However, there is no boolean type in ANSI C. Instead, we use integers: 0 to represent false Anything else to represent true (1 is used as the representative

value for true in output)

Example:

Should refrain from using integer values directly

int a = (2 > 3);int b = (3 > 2);

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

[ CS1010E AY1112S1 Lecture 4 ] 6

Page 7: L4 - Control Flow Statements I

The if statement: Examplesint x;

x = 3;

if (x < 10)printf( "X is small\n" );

printf( "End of example\n" );

Output:

X is smallEnd of example

int x;

x = 12;

if (x < 10)printf( "X is small\n" );

printf( "End of example\n" );

Output:

End of example

7[ CS1010E AY1112S1 Lecture 4 ]

Page 8: L4 - Control Flow Statements I

Conditions: Examplesint x, y, result;

scanf("%d %d", &x, &y );

if (x < y)printf("X is smaller than Y\n");

if (x == y)printf("X is equal to Y\n");

if (x > y)printf("X is larger than Y\n");

result = (x != y); //result stores 0 or 1

if ( result )printf("X is not equal to Y\n");

8[ CS1010E AY1112S1 Lecture 4 ]

Page 9: L4 - Control Flow Statements I

Conditions: Updated Precedence Table The relational operators have lower

precedence than arithmetic operators+, - Unary +, -% Remainder*, / Multiplication, Division+, - Addition, Subtraction< <= >= > Relational Operators== != Equality Operators

Hig

her

Prec

eden

ce

if ( 2 + 6 > 7 )printf( "Condition is true\n" );

Output:

Condition is true

9[ CS1010E AY1112S1 Lecture 4 ]

Page 10: L4 - Control Flow Statements I

Boolean Operators

Complex conditions: combine two or more boolean expressions. For example,

if temperature is greater than 40°C 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. They are: && (and), || (or), ! (not).

A B A && B A || B !A0 0 0 0 10 1 0 1 11 0 0 1 01 1 1 1 0

[ CS1010E AY1112S1 Lecture 4 ] 10

Page 11: L4 - Control Flow Statements I

Evaluation of Boolean Expressions

The evaluation of a boolean expression proceeds according to the precedence and associativity of the operators.

Operator Description Associativity… … …! Logical negation Right-to-left

… … …<, <=, >, >= Relational operations Left-to-right

==, != Equality operations Left-to-right… … …&& Logical AND Left-to-right|| Logical OR Left-to-right… … …

[ CS1010E AY1112S1 Lecture 4 ] 11

Page 12: L4 - Control Flow Statements I

Evaluation of Boolean Expressions

Example #1: What is the value of x?

x is true (1)

Example #3: What is the value of x?

int x, a = 4, b = -2, c = 0;x = (a > b || b > c && a == b);

x = ((a > b) && !(b > c)); x is true (1)

Example #2: What is the value of x?x = ((a > b || b > c) && a == b); x is false (0)

[ CS1010E AY1112S1 Lecture 4 ] 12

Page 13: L4 - Control Flow Statements I

Programming Style: Indentation When statement X is under influence

(controlled) of statement Y: indent statement X by one more tab space

int main(){

int x;

x = 3;

if (x < 10)printf( "X is small\n" );

printf( "End of example\n" );return 0;

}

13[ CS1010E AY1112S1 Lecture 4 ]

Page 14: L4 - Control Flow Statements I

Programming Style: Use #define It is useful to define TRUE and FALSE in

your program to improve readability:

int input, isEven;

scanf("%d", &input);

//Is input an even number?isEven = 0; //initialized to false

if ( input % 2 == 0)isEven = 1; //true

if (isEven == 1)printf("%d is even\n", input);

#define TRUE 1 //place at program head#define FALSE 0

int input, isEven;

scanf("%d", &input);

//Is input an even number?isEven = FALSE;

if ( input % 2 == 0)isEven = TRUE;

if (isEven == TRUE)printf("%d is even\n", input);

14Demo:

ifboolean.c[ CS1010E AY1112S1 Lecture 4 ]

Page 15: L4 - Control Flow Statements I

The if statement block: Syntax

The "0 or more statements" in the {} is known as statement block or compound statement

Behaviour: The statements in statement block are executed

sequentially if the condition is true

SYN

TAX

if ( condition ) {[0 or more statements] //statements block

}

15[ CS1010E AY1112S1 Lecture 4 ]

Page 16: L4 - Control Flow Statements I

Programming Style: Watch the { } When we use a statement block, there are

two common ways to place the { }

if ( condition ) {statement 1statement 2......

}

if ( condition ) {

statement 1statement 2......

}

Just use one style consistently Always place the matching { } before coding in the

statement block to avoid mismatch You are encouraged to use { } even when there is

only 1 statement in statement block16

Demo: if_block.c[ CS1010E AY1112S1 Lecture 4 ]

Page 17: L4 - Control Flow Statements I

The if statement block: Exampleint x;

x = 3;

if (x < 10){printf( "X is small\n" );printf( "lesser than 10\n");

}

printf( "End of example\n" );

Output:

X is smalllesser than 10End of example

int x;

x = 12;

if (x < 10) ){printf( "X is small\n" );printf( "lesser than 10\n");

}

printf( "End of example\n" );

Output:

End of example

17[ CS1010E AY1112S1 Lecture 4 ]

Page 18: L4 - Control Flow Statements I

Nested-if: if within another if Since if-statement is a single statement, it can

be under influence of another if-statementint x;

x = 3;

if (x < 10)

printf( "End of example\n" );

You can have more levels of nested if-statement However, deeply nested statement is hard to

understand and error prone

18

printf( "X is small\n" );if ( x > 0 )

printf( "X is small but positive\n" );

Demo: if_nested.c[ CS1010E AY1112S1 Lecture 4 ]

Page 19: L4 - Control Flow Statements I

The if-else statement: Syntax

else is a keyword The complete if-else statement is a single statement

Behaviour: statement_A and statement_B are mutually

exclusive statement_A is executed only if the condition is true statement_B is executed only if the condition is false

SYN

TAX

if ( condition )statement_A

elsestatement_B

19[ CS1010E AY1112S1 Lecture 4 ]

Page 20: L4 - Control Flow Statements I

The if-else statement: Examplesint x;

x = 3;

if (x < 10)printf( "X is small\n" );

elseprintf( "X is at least 10\n" );

printf( "End of example\n" );

Output:

X is smallEnd of example

Output:

X is at least 10End of example

int x;

x = 12;

if (x < 10)printf( "X is small\n" );

elseprintf( "X is at least 10\n" );

printf( "End of example\n" );

20[ CS1010E AY1112S1 Lecture 4 ]

Page 21: L4 - Control Flow Statements I

The if-else statement: Examples

Note that else-part takes the opposite condition of the if-part automatically Think carefully whether this is what you need

This also implies that else-part cannot exist without the if-part

int x, y;

scanf("%d %d", &x, &y );

if (x < y)printf("X is smaller than Y\n");

elseprintf("X is larger than or equal to Y\n");

21Demo:

if_else.c[ CS1010E AY1112S1 Lecture 4 ]

Page 22: L4 - Control Flow Statements I

The if-else statement block: Syntax

Behaviour: The same as if-else, except whole statement

block is executed instead of a single statement

You are encouraged to use this form

SYN

TAX

if ( condition ) {[0 or more statements] //if-statements block

} else {[0 or more statements] //else-statements block

}

22[ CS1010E AY1112S1 Lecture 4 ]

Page 23: L4 - Control Flow Statements I

Example 1: Hi-Lo Game

Write an application that will play Hi-Lo games with the user.The objective of the game is for the user to guess the secret number. The secret number is an integer between 1 and 100, inclusive. When the user makes a guess, the program replies with HI or LO depending on whether the guess is higher or lower than the secret number.

[ CS1010E AY1112S1 Lecture 4 ] 23

Page 24: L4 - Control Flow Statements I

Example 1: Hi-Lo GameAnalysis: We define what are the inputs and output

- Inputs: secret number, your guess- Output: your guess is too high, too low or correct.

Choose the identifier names and data types- int secret, int guess

Design: Algorithm (view in words):

1. Read in your guess2. Check whether guess is greater than secret3. If yes, output “Guess is too High”4. Check whether guess is smaller than secret5. If yes, output “Guess is too Low”6. Check whether guess is the same as the secret7. If yes, output “You have guessed the correct number.”

[ CS1010E AY1112S1 Lecture 4 ] 24

Page 25: L4 - Control Flow Statements I

Example 1: Hi-Lo Game (version 1)

[ CS1010E AY1112S1 Lecture 4 ] 25

Page 26: L4 - Control Flow Statements I

Example 1: Hi-Lo Game (version 2)

[ CS1010E AY1112S1 Lecture 4 ] 26

Page 27: L4 - Control Flow Statements I

Example 2: Maximum of 3 Numbers

Problem: Find the maximum among 3 integer values.

Version #1int max = 0;if (num1 > num2 && num1 > num3)

max = num1;if (num2 > num1 && num2 > num3)

max = num2;if (num3 > num1 && num3 > num2)

max = num3;

Spot the errors

[ CS1010E AY1112S1 Lecture 4 ] 27

Page 28: L4 - Control Flow Statements I

Another version:int max = 0;if (num1 > max)

max = num1;else if (num2 > max)

max = num2;else if (num3 > max)

max = num3;

Spot the errors

Example 2: Maximum of 3 Numbers

[ CS1010E AY1112S1 Lecture 4 ] 28

Page 29: L4 - Control Flow Statements I

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.

Common 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”);

[ CS1010E AY1112S1 Lecture 4 ] 29

Page 30: L4 - Control Flow Statements I

Common Error: dangling else When { } is not used, it is easy to attach the else to the wrong if

int x;

x = -5;if (x > 0 )

if (x < 10)printf( "X is small\n" );

elseprintf( "X is negative or 0\n" );

printf( "End of example\n" );

Output: (why?)

End of example

Important: else is attached to the nearest if by default Indentation has no effect on the execution!

30Demo:

if_else_block.c[ CS1010E AY1112S1 Lecture 4 ]

Page 31: L4 - Control Flow Statements I

The dangling else: Use { }

int x;

x = -5;if (x > 0 ) {

if (x < 10)printf( "X is small\n" );

} elseprintf( "X is negative or 0\n" );

printf( "End of example\n" );

Output:

X is negative or 0End of example

31[ CS1010E AY1112S1 Lecture 4 ]

Page 32: L4 - Control Flow Statements I

Problem: The leap year Year Y is a leap year (366 days): If Y is divisible by 400 If Y is divisible by 4, unless it is also divisible by

100 Leap year: 1604, 2000 Not leap year: 1900, 2009

Write a function isLeapYear() to check whether a given year is a leap year

32Demo: leapYear.c[ CS1010E AY1112S1 Lecture 4 ]

Page 33: L4 - Control Flow Statements I

Repetition Statement

Page 34: L4 - Control Flow Statements I

Repetition Statement Statements are executed at most once even

with selection statement

Quite often we need to execute a set of statements several times

C Programming Language provides repetition statement to: Execute statement(s) multiple times 1 round of execution is also known as 1 iteration

34[ CS1010E AY1112S1 Lecture 4 ]

Page 35: L4 - Control Flow Statements I

The while statement: Syntax

while is a keyword statement_A or the statement block is also known as the

while loop body

Behaviour: As long as the condition is true, statement(s) controlled by while will be executed

SYN

TAX

while ( condition )statement_A //a single statement

OR

while ( condition ) {[0 or more statements] //a statement block

}

35Demo: while.c[ CS1010E AY1112S1 Lecture 4 ]

Page 36: L4 - Control Flow Statements I

The while statement: Common Elements

The condition in while usually involves a variable: serves to "count" / control the number of iterations commonly known as counter

Common statements for a counter variable: Initialization: Set the counter to a starting value Condition: Check whether the counter reaches

certain ending value Update: Modify the counter so that it reaches the

ending value eventually

36[ CS1010E AY1112S1 Lecture 4 ]

Page 37: L4 - Control Flow Statements I

The while statement: Example

Question: What if we remove the "Initialise counter" statement? What if we remove the "Update counter" statement?

int counter;

counter = 0;

while ( counter < 5 ) {

printf( "Hello World!\n" );counter = counter + 1;

}

37

counter

[ CS1010E AY1112S1 Lecture 4 ]

Page 38: L4 - Control Flow Statements I

The while statement: Example

The counter is just a normal variable After the loop, the condition must be false

counter >= 5 in this case

int counter;

counter = 0;

while ( counter < 5 ) {printf( "Counter:%d\n", counter );counter = counter + 1;

}

printf( "**Counter:%d\n", counter );

Output:

Counter:0Counter:1Counter:2Counter:3Counter:4**Counter:5

38Demo: counter.c[ CS1010E AY1112S1 Lecture 4 ]

Page 39: L4 - Control Flow Statements I

The while statement: Example Problem: Print power-of-2s starting from 1 to 1024

int powerOf2;

powerOf2 = 1;

while ( powerOf2 <= 1024 ) {

printf( "%d\n", powerOf2 );powerOf2 = powerOf2 * 2;

}

39

Note the update statement can be many forms, not always i = i +1;

[ CS1010E AY1112S1 Lecture 4 ]

Page 40: L4 - Control Flow Statements I

Problem: Hi-Lo Game revisited Modify the Hi-Lo game to allow the user a

maximum of 7 tries is your game fun to play? Why? How to make it really a secret?

[ CS1010E AY1112S1 Lecture 4 ] 40

Page 41: L4 - Control Flow Statements I

Problem: PI Algorithm …. revisited!

Let us: Write a functiondouble computePI( int nTerm );

The function uses nTerm number of terms to approximate PI

Write a full program:1. Ask the user for the number of terms to be used2. Compute PI3. Show PI

41Demo: pi.c

.........94

74

54

34

14

−+−+−=π

[ CS1010E AY1112S1 Lecture 4 ]

Page 42: L4 - Control Flow Statements I

SummaryC

Ele

men

ts

Control Flow Statement:- Selective Statement

- if- if-else

- Repetition Statement- while

Prog

ram

min

g St

yle Indentation

Curly braces { } for block statement

Use #define FALSE 0 #define TRUE 1

42[ CS1010E AY1112S1 Lecture 4 ]