46

Lecture 04 Control Structure

Embed Size (px)

Citation preview

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 1/46

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 2/46

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 3/46

For example:int main()

{

int age;

printf(“What is your age?”); 

scanf(“%d”, &age); 

printf(“your age is %d”, age); 

return 0;

}

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 4/46

What if your program have more thantwo ways to perform?

For example:

If age 18 and above is adult, whileyounger than 18 is minor.

From the program in previous slide, howcan you code your program to performin a way to determine you as adult or minor based on your input?

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 5/46

Selection structure:› Used to choose among alternative

courses of action

› Pseudocode:

If student’s grade is greater than or equal to 60 Print “Passed” 

If condition true › Print statement executed and program

goes on to next statement› If false, print statement is ignored and

the program goes onto the nextstatement

5

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 6/46

Pseudocode statement in C:if ( grade >= 60 )

printf( "Passed\n" );

› C code corresponds closely to thepseudocode

Diamond symbol (decision symbol)› Indicates decision is to be made

› Contains an expression that can be true or false

› Test the condition, follow appropriate path6

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 7/46

if statement is a single-entry/single-

exit structure

7

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 8/46

if

› Only performs an action if the condition is true

if…else

› Specifies an action to be performed both whenthe condition is true and when it is false

Psuedocode:If student’s grade is greater than or equal to 60 

Print “Passed” else

Print “Failed”

› Note spacing/indentation conventions

8

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 9/46

C code:if ( grade >= 60 )

printf( "Passed\n");

else

printf( "Failed\n"); 

9

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 10/46

Flow chart of the if…else selection statement

Nested if…else statements› Test for multiple cases by placing if…else selection

statements inside if…else selection statement› Once condition is met, rest of statements skipped

› Deep indentation usually not used in practice

10

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 11/46

› Pseudocode for a nested if…else statementIf student’s grade is greater than or equal to 90 Print “A” 

elseIf student’s grade is greater than or equal to 80 

Print “B” elseIf student’s grade is greater than or equal to

70Print “C” 

elseIf student’s grade is greater than or equal

to 60Print “D” 

elsePrint “F” 

11

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 12/46

Compound statement:› Set of statements within a pair of braces

› Example:if ( grade >= 60 )

printf( "Passed.\n" );

else {printf( "Failed.\n" );

printf( "You must take this courseagain.\n" );

}

› Without the braces, the statementprintf( "You must take this course

again.\n" );

would be executed automatically

12

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 13/4613

Control Structure

Using Relational Operators in Conditional Expressions

Conditional expressions are formed using relational and logicaloperators.Relational operators are used to compare values. An expression thatcompares two expressions using relational operator is called a simplepredicate. A simple predicate computes to either 1 (for true) or 0 (for false).

C has six relational operators.

Equal to

Not equal to

Less than

Less than or equal to

Greater than

Greater than or equal to

==

>

<

!=

>=

<=

Symbol Operator Name

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 14/46

14

Logical expression is one that computes to either 1 (for true) or 0 (for false). A simple predicate is a logical expression because it produces

either a true or false result.

Logical AND (conjunction)

Logical OR (disjunction)

Logical NOT (negation)

&&

!

||

Symbol Logical Name

Logical AND-Returns true if both conditions are true.

Logical OR-Returns true if either of its conditions are true.

Logical NOT-Reverses the truth/false of its condition-unary operator, has one operand

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 15/46

15

true

false

true

true

false

true

operand_1 operand_2

false false

operand_1 && operand_2

true

false

false

false

Truth Table for the && (Logical AND) Operator

true

false

true

true

false

true

operand_1 operand_2

false false

operand_1 || operand_2

true

true

false

true

Truth Table for the || (Logical OR) Operator

false

true

true

false

operand_1 ! (operand_1)

Truth Table for the ! (LogicalNOT) Operator

Example:((X < 1) && (Y > =1))

Example:

((X < 1) || (Y > =1))

Example:!(X < 1) == (X> =1)

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 16/46

16

Multiple Operators: Precedence of Logical Operators 

A precedence rule states the order in which different operators are

applied. An associativity rule specifies the order in which multipleoccurrence of the same operator are applied.

Operators Associativity Type

++ (postfix)  --  (postfix)  right to left postfix

+ - ! ++  (prefix) --  (prefix)  (type) right to left unary

* / % left to right multiplicative

+ -  left to right additive

< <= > >= left to right relational

== != left to right equality

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %=  right to left assignment

, left to right comma

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 17/46

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 18/46

Flowchart of the switch statement

18

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 19/46

break

› Causes immediate exit from a while, for,do

…while

or switch

statement› Program execution continues with the first

statement after the structure

› Common uses of the break statement

Escape early from a loop Skip the remainder of a switch statement

19

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 20/46

continue› Skips the remaining statements in the body

of a while, for or do…while statement

Proceeds with the next iteration of the loop

› while and do…while

Loop-continuation test is evaluatedimmediately after the continue statement is

executed› for

Increment expression is executed, then theloop-continuation test is evaluated

20

1 /* Fig. 4.11: fig04_11.c

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 21/46

21

2 Using the break statement in a for statement */

3 #include <stdio.h>

4

5 /* function main begins program execution */

6 int main( void )

7 {

8 int x; /* counter */

9

10 /* loop 10 times */

11 for ( x = 1; x <= 10; x++ ) {

12

13 /* if x is 5, terminate loop */

14 if ( x == 5 ) {

15 break; /* break loop only if x is 5 */

16 } /* end if */17

18 printf( "%d ", x ); /* display value of x */

19 } /* end for */

20

21 printf( "\nBroke out of loop at x == %d\n", x );

22

23 return 0; /* indicate program ended successfully */

24

25 } /* end function main */

1 2 3 4

Broke out of loop at x == 5

 break immediately ends for 

loop

1 /* Fig. 4.12: fig04_12.c

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 22/46

22

2 Using the continue statement in a for statement */

3 #include <stdio.h>

4

5 /* function main begins program execution */

6 int main( void )

7 {

8 int x; /* counter */

9

10 /* loop 10 times */

11 for ( x = 1; x <= 10; x++ ) {

12

13 /* if x is 5, continue with next iteration of loop */

14 if ( x == 5 ) {

15 continue; /* skip remaining code in loop body */

16 } /* end if */17

18 printf( "%d ", x ); /* display value of x */

19 } /* end for */

20

21 printf( "\nUsed continue to skip printing the value 5\n" );

22

23 return 0; /* indicate program ended successfully */

24

25 } /* end function main */

1 2 3 4 6 7 8 9 10

Used continue to skip printing the value 5

continue skips to end of for 

loop and performs next

iteration

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 23/46

Let say your schedule is as below

Day Class

Monday TMC1413Tuesday TMC1233

Wednesday TMX1011

Thursday No Class

Friday TMC1813

Saturday Badminton

Sunday sleep

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 24/46

int main(){

string day;printf(“What is today?\n”); 

scanf(“%s”, &day); 

if (day == “Monday”) {

printf(“TMC1413”); }

else if (day == “Tuesday”) {

printf(“TMC1233); }else if (day == “Wednesday”) {

printf(“TMX1011”) }return 0

}

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 25/46

int main()

{

string day;

printf(“What is today?\n”); scanf(“%s”, &day); 

switch (day){

case “Monday”: 

{

printf(“TMC1413”); 

break;

}

case “Tuesday”: 

{

printf(“TMC1233”); break;

}…. 

case “Saturday”: 

{

printf(“Badminton”); break 

}

default:

{

printf (“sleep”); 

break;

}

}

return 0;

}

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 26/46

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 27/46

You can make decision with your program.

Another problem arise when you wantrepeating doing one operation.

For example:

create a program to print 1 to 10.

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 28/46

28

Repetition Statements

Every programming language has some constructs that can beused to define controlled repetitions (or loops) on a program block.

A program block that is executed repeatedly by a repetitionstatement is called its loop body.

The repetition is controlled by a condition that is associated withthe repetition statement.

There are two types of repetition statements:

•pretest repetition statements

•posttest repetition statements

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 29/46

29

A pretest repetition statement computes a value for its associated

predicate before entering the loop body and will execute the loopbody as long as the predicate is true.

Once the predicate computes to false, repetition stops and theprogram control passes to the next statement that follows therepetition statement.

Flowchart

predicate loop body

false

true

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 30/46

30

A posttest repetition statement first executes the loop body and then

computes the predicate. If the predicate is true, the loop body isexecuted again; otherwise, the repetition terminates.

Flowchart

predicateloop body

false

true

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 31/46

31

There are three statements for repetitions:

while statement;for statement;do-while statement;

a pretest repetition statement

a posttest repetition statement

Using while Statements

while (Expression)

Statement;/*end while*/

loop body

enclosed in parenthesis

comment: to show termination

Example

while (++counter <= 10) {

printf (“%d\n”, counter); /*end while*/

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 32/46

Loop› Group of instructions computer executes

repeatedly while some condition remains true

Counter-controlled repetition› Definite repetition: know how many times loop

will execute

› Control variable used to count repetitions

Sentinel-controlled repetition› Indefinite repetition

› Used when number of repetitions not known

› Sentinel value indicates "end of data"

32

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 33/46

33

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 34/46

Format when using for loops

for ( initialization; loopContinuationTest; increment ) statement 

Example:for( int counter = 1; counter <= 10; counter++ )

printf( "%d\n", counter );

› Prints the integers from one to ten

34

No

semicolon

(;) after

lastexpression

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 35/46

For loops can usually be rewritten aswhile loops:initialization; while ( loopContinuationTest ) {

 statement;

increment;}

Initialization and increment› Can be comma-separated lists

› Example:for (int i = 0, j = 0; j + i <= 10;j++, i++)

 printf( "%d\n", j + i );

35

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 36/46

Arithmetic expressions

› Initialization, loop-continuation, and increment cancontain arithmetic expressions. If x equals 2 and y equals 10 for ( j = x; j <= 4 * x * y; j += y / x ) 

is equivalent to

for ( j = 2; j <= 80; j += 5 )

Notes about the for statement:› "Increment" may be negative (decrement)

› If the loop continuation condition is initially false

The body of the for statement is not performed

Control proceeds with the next statement after the for statement

› Control variable Often printed or used inside for body, but not necessary

36

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 37/46

37

1 /* Fig. 4.5: fig04_05.c

2

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 38/46

38

2 Summation with for */

3 #include <stdio.h>

4

5 /* function main begins program execution */

6 int main( void )

7 {

8 int sum = 0; /* initialize sum */

9 int number; /* number to be added to sum */

10

11 for ( number = 2; number <= 100; number += 2 ) {

12 sum += number; /* add number to sum */ 

13 } /* end for */

14

15 printf( "Sum is %d\n", sum ); /* output sum */

1617 return 0; /* indicate program ended successfully */

18

19 } /* end function main */

Sum is 2550

Note that number has a different

value each time this statement is

executed

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 39/46

Repetition structure

› Programmer specifies an action to berepeated while some condition remains true

› Psuedocode:

While there are more items on my shopping listPurchase next item and cross it off my list

› while loop repeated until conditionbecomes false

39

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 40/46

Example:int product = 2;

while ( product <= 1000 )product = 2 * product;

40

• Not providing the body of a while statement with an action that

eventually causes the condition in the while to become false.

Normally, such a repetition structure will never terminate—an error

called an “infinite loop.” 

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 41/46

The do…while repetition statement

› Similar to the while structure

Condition for repetition tested after the bodyof the loop is performed

All actions are performed at least once

› Format:

do { statement;

} while ( condition );

41

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 42/46

Example (letting counter = 1):do {

printf( "%d ", counter );

} while (++counter <= 10);

› Prints the integers from 1 to 10

42

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 43/46

Flowchart of the do…while repetition

statement

43

1 /* Fig. 4.9: fig04_09.c

2 Using the do/while repetition statement */

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 44/46

44

3 #include <stdio.h>

4

5 /* function main begins program execution */

6 int main( void )

7 {

8 int counter = 1; /* initialize counter */

9

10 do {

11 printf( "%d ", counter ); /* display counter */

12 } while ( ++counter <= 10 ); /* end do...while */ 

13

14 return 0; /* indicate program ended successfully */

15

16 } /* end function main */

1 2 3 4 5 6 7 8 9 10

increments counter then checks if it

is less than or equal to 10

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 45/46

 

45

8/4/2019 Lecture 04 Control Structure

http://slidepdf.com/reader/full/lecture-04-control-structure 46/46

Problem Solving using C, Uckan, Yuksel, Mc GrawHill, 1999.

C How to Program, Deitel&Deitel, Prentice-Hall, 6th Edition, 2010.