Top Banner
TMC1414/TMC1413 INTRODUCTION TO PROGRAMMING Lecture 04: Control Structure
49

TMC1414/TMC1413 Introduction to Programming

Jan 04, 2016

Download

Documents

anjolie-melton

TMC1414/TMC1413 Introduction to Programming. Lecture 04: Control Structure. Objective. In this topic, you will learn about: Selection Structures if if-else Repetition control structures For while do..while statement Switch multiple selection statement - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: TMC1414/TMC1413 Introduction to Programming

TMC1414/TMC1413INTRODUCTION TO

PROGRAMMING

Lecture 04: Control Structure

Page 2: TMC1414/TMC1413 Introduction to Programming

2

OBJECTIVE In this topic, you will learn about:

Selection Structures if if-else

Repetition control structures For while do..while statement

Switch multiple selection statement Break Vs continue statement

Structured Programming

Page 3: TMC1414/TMC1413 Introduction to Programming

INPUT & OUTPUT

For example:int main(){

int age;printf(“What is your age?”);scanf(“%d”, &age);

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

return 0;}

Page 4: TMC1414/TMC1413 Introduction to Programming

What if your program have more than two ways to perform?

For example:If age 18 and above is adult, while younger than 18 is minor.

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

Page 5: TMC1414/TMC1413 Introduction to Programming

5

THE IF SELECTION STATEMENT

Selection structure: Used to choose among alternative

courses of actionPseudocode:

If student’s grade is greater than or equal to 60Print “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 next statement

Page 6: TMC1414/TMC1413 Introduction to Programming

6

THE IF SELECTION STATEMENT Pseudocode statement in C:

if ( grade >= 60 ) printf( "Passed\n" );

C code corresponds closely to the pseudocode

Diamond symbol (decision symbol) Indicates decision is to be made Contains an expression that can be true or false

Test the condition, follow appropriate path

Page 7: TMC1414/TMC1413 Introduction to Programming

7

THE IF SELECTION STATEMENT

if statement is a single-entry/single-exit structure

 

Page 8: TMC1414/TMC1413 Introduction to Programming

8

THE IF SELECTION STATEMENT if

Only performs an action if the condition is true

if…elseSpecifies an action to be performed both

when the 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

 

Page 9: TMC1414/TMC1413 Introduction to Programming

9

THE IF SELECTION STATEMENT C code:

if ( grade >= 60 ) printf( "Passed\n");else printf( "Failed\n");

Page 10: TMC1414/TMC1413 Introduction to Programming

10

THE IF SELECTION STATEMENT

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 skippedDeep indentation usually not used in practice

Page 11: TMC1414/TMC1413 Introduction to Programming

11

THE IF SELECTION STATEMENT

Pseudocode for a nested if…else statementIf student’s grade is greater than or equal to 90

Print “A”else

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

Print “B”else If student’s grade is greater than or

equal to 70 Print “C” else If student’s grade is greater than or

equal to 60 Print “D” else Print “F”

Page 12: TMC1414/TMC1413 Introduction to Programming

12

THE IF SELECTION STATEMENT 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 course again.\n" );}

Without the braces, the statementprintf( "You must take this course again.\n" );

would be executed automatically

Page 13: TMC1414/TMC1413 Introduction to Programming

13

Control StructureUsing Relational Operators in Conditional Expressions

Conditional expressions are formed using relational and logical operators.Relational operators are used to compare values. An expression that compares two expressions using relational operator is called a simple predicate. 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

Page 14: TMC1414/TMC1413 Introduction to Programming

A == 1 A = 2

Page 15: TMC1414/TMC1413 Introduction to Programming

15

CONTROL STRUCTURELogical 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

Page 16: TMC1414/TMC1413 Introduction to Programming

16

CONTROL STRUCTURE

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 ! (Logical NOT) Operator

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

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

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

Page 17: TMC1414/TMC1413 Introduction to Programming

17

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 multiple occurrence 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

Page 18: TMC1414/TMC1413 Introduction to Programming

18

THE SWITCH MULTIPLE-SELECTION STATEMENT switch

Useful when a variable or expression is tested for all the values it can assume and different actions are taken

FormatSeries of case labels and an optional default case

switch ( value ){case '1':

actionscase '2':

actionsdefault:

actions}

break; exits from statement

 

Page 19: TMC1414/TMC1413 Introduction to Programming

19

THE SWITCH MULTIPLE-SELECTION STATEMENT Flowchart of the switch statement

Page 20: TMC1414/TMC1413 Introduction to Programming

20

THE BREAK AND CONTINUE STATEMENTS

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

Page 21: TMC1414/TMC1413 Introduction to Programming

21

THE BREAK AND CONTINUE STATEMENTS

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 evaluated immediately after

the continue statement is executed

for Increment expression is executed, then the loop-

continuation test is evaluated

Page 22: TMC1414/TMC1413 Introduction to Programming

22

1 /* Fig. 4.11: fig04_11.c

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

Page 23: TMC1414/TMC1413 Introduction to Programming

23

1 /* Fig. 4.12: fig04_12.c

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

Page 24: TMC1414/TMC1413 Introduction to Programming

IF…ELSE STATEMENT

Let say your schedule is as below

Day Class

Monday TMC1413

Tuesday TMC1233

Wednesday TMX1011

Thursday No Class

Friday TMC1813

Saturday Badminton

Sunday sleep

Page 25: TMC1414/TMC1413 Introduction to Programming

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

}

Page 26: TMC1414/TMC1413 Introduction to Programming

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;

}

Page 27: TMC1414/TMC1413 Introduction to Programming

REPETITION STATEMENT(Loops)

Page 28: TMC1414/TMC1413 Introduction to Programming

REPETITION STATEMENTS

You can make decision with your program. Another problem arise when you want

repeating doing one operation. For example:

create a program to print 1 to 10.

Page 29: TMC1414/TMC1413 Introduction to Programming

29

CONTROL STRUCTURERepetition Statements

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

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

The repetition is controlled by a condition that is associated with the repetition statement.

There are two types of repetition statements:

• pretest repetition statements• posttest repetition statements

Page 30: TMC1414/TMC1413 Introduction to Programming

30

CONTROL STRUCTUREA pretest repetition statement computes a value for its associated predicate before entering the loop body and will execute the loop body as long as the predicate is true.

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

Flowchart

predicate loop body

false

true

Page 31: TMC1414/TMC1413 Introduction to Programming

31

CONTROL STRUCTURE

A posttest repetition statement first executes the loop body and then computes the predicate. If the predicate is true, the loop body is executed again; otherwise, the repetition terminates.

Flowchart

predicateloop body

false

true

Page 32: TMC1414/TMC1413 Introduction to Programming

32

CONTROL STRUCTURE

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*/

Page 33: TMC1414/TMC1413 Introduction to Programming

33

THE ESSENTIALS OF REPETITION

LoopGroup of instructions computer executes

repeatedly while some condition remains true

Counter-controlled repetitionDefinite repetition: know how many times

loop will executeControl variable used to count repetitions

Sentinel-controlled repetition Indefinite repetitionUsed when number of repetitions not

knownSentinel value indicates "end of data"

Page 34: TMC1414/TMC1413 Introduction to Programming

34

THE FOR REPETITION STATEMENT

Page 35: TMC1414/TMC1413 Introduction to Programming

35

THE FOR REPETITION STATEMENT

Format when using for loopsfor ( initialization; loopContinuationTest; increment )

statement

Example: for( int counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter );

Prints the integers from one to ten

 

No semicolon (;) after last expression

Page 36: TMC1414/TMC1413 Introduction to Programming

36

THE FOR REPETITION STATEMENT

For loops can usually be rewritten as while 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 );

Page 37: TMC1414/TMC1413 Introduction to Programming

37

THE FOR STATEMENT : NOTES AND OBSERVATIONS Arithmetic expressions

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

is equivalent tofor ( 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

statementControl variable

Often printed or used inside for body, but not necessary

Page 38: TMC1414/TMC1413 Introduction to Programming

38

THE FOR STATEMENT : NOTES AND OBSERVATIONS

Page 39: TMC1414/TMC1413 Introduction to Programming

39

1 /* Fig. 4.5: fig04_05.c 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 */ 16

17 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

Page 40: TMC1414/TMC1413 Introduction to Programming

40

THE WHILE REPETITION STATEMENT Repetition structure

Programmer specifies an action to be repeated while some condition remains true

Psuedocode:While there are more items on my shopping list

Purchase next item and cross it off my list

while loop repeated until condition becomes false

 

Page 41: TMC1414/TMC1413 Introduction to Programming

41

THE WHILE REPETITION STATEMENT Example:

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

product = 2 * product;

• 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.”

Page 42: TMC1414/TMC1413 Introduction to Programming

42

THE DO…WHILE REPETITION STATEMENT The do…while repetition statement

Similar to the while structure Condition for repetition tested after the body of

the loop is performed All actions are performed at least once

Format:do { statement;} while ( condition );

 

Page 43: TMC1414/TMC1413 Introduction to Programming

43

THE DO…WHILE REPETITION STATEMENT Example (letting counter = 1):

do { printf( "%d ", counter );} while (++counter <= 10);

Prints the integers from 1 to 10 

Page 44: TMC1414/TMC1413 Introduction to Programming

44

THE DO…WHILE REPETITION STATEMENT Flowchart of the do…while repetition

statement

Page 45: TMC1414/TMC1413 Introduction to Programming

45

1 /* Fig. 4.9: fig04_09.c 2 Using the do/while repetition statement */ 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

Page 46: TMC1414/TMC1413 Introduction to Programming

46

C’S SINGLE-ENTRY/SINGLE-EXIT SEQUENCE, SELECTION AND REPETITION STATEMENTS.

Page 47: TMC1414/TMC1413 Introduction to Programming

47

REFERENCES

Problem Solving using C, Uckan, Yuksel, Mc Graw Hill, 1999.

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

Page 48: TMC1414/TMC1413 Introduction to Programming

48

Q & A

Any Question? Can you write an infinity loop using

for/while/do-while statements?

Page 49: TMC1414/TMC1413 Introduction to Programming

49

Thank You