Lecture 7a S ClC ontrol Statements ((if, if--else,...

37
Lecture 7a C l S C l S Control Statements Control Statements (if, if if, if-else, while) else, while) Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: © Deitel Associates & Pearson)

Transcript of Lecture 7a S ClC ontrol Statements ((if, if--else,...

Page 1: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Lecture 7a

C l SC l SControl StatementsControl Statements((if, ifif, if--else, while)else, while)(( ))

Dr M Kasim A JalilFaculty of Mechanical Engineering

UTM(source: © Deitel Associates & Pearson)

Page 2: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

ObjectivesObjectivesjj

• In this chapter, you will learn:– To understand basic problem solving techniques. – To be able to develop algorithms through the process of top-

down, stepwise refinement.– To be able to use the if selection statement and if…else

selection statement to select actions.– To be able to use the while repetition statement to execute o be ab e to use t e e epet t o state e t to e ecute

statements in a program repeatedly.– To understand counter-controlled repetition and sentinel-

controlled repetition.co t o ed epet t o– To understand structured programming.

Page 3: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

IntroductionIntroduction

Before writing a program:g p gHave a thorough understanding of the problem Carefully plan an approach for solving itCarefully plan an approach for solving it

While writing a program: K h t “b ildi bl k ” il blKnow what “building blocks” are availableUse good programming principles

Page 4: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

AlgorithmsAlgorithmsgg

Computing problems p g pAll can be solved by executing a series of actions in a specific order

Algorithm: procedure in terms ofAlgorithm: procedure in terms ofActions to be executed Th d i hi h th ti t b t dThe order in which these actions are to be executed

Program control Specify order in which statements are to be executed

Page 5: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

PseudocodePseudocode

PseudocodeArtificial, informal language that helps us develop algorithmsSimilar to everyday EnglishSimilar to everyday EnglishNot actually executed on computers Helps us “think out” a program before writing it Helps us think out a program before writing it

Easy to convert into a corresponding C programConsists only of executable statementsConsists only of executable statements

Page 6: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Control StructuresControl Structures

Sequential execution qStatements executed one after the other in the order written

Transfer of controlWhen the next statement executed is not the next one in sequenceOveruse of goto statements led to many problemsy p

Structured ProgramAll programs written in terms of 3 control structuresp g

Sequence structures: Built into C. Programs executed sequentially by defaultSelection structures: C has three types: if, if…else, and switchRepetition structures: C has three types: while, do…while and for

Page 7: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Control StructuresControl Structures

Flowcharting C’s sequence structure.

Page 8: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Control StructuresControl Structures

Flowchart G h l f l hGraphical representation of an algorithmDrawn using certain special-purpose symbols connected by arrows called flowlinesflowlinesRectangle symbol (action symbol):

Indicates any type of action

Oval symbol:Indicates the beginning or end of a program or a section of code

Si l t / i l it t l t t Single-entry/single-exit control structures Connect exit point of one control structure to entry point of the next (control-structure stacking)structure stacking)Makes programs easy to build

Page 9: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif Selection StSelection Statementatement

Selection structure: Used to choose among alternative courses of actionPseudocode:

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

If condition trueIf condition truePrint statement executed and program goes on to next statement

If i i i d d h h If false, print statement is ignored and the program goes onto the next statementIndenting makes programs easier to readIndenting makes programs easier to read

C ignores whitespace characters

Page 10: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif Selection StSelection Statementatement

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 madeContains an expression that can be true or falseTest the condition, follow appropriate path

Page 11: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif Selection StSelection Statementatement

if statement is a single-entry/single-exit structureg y/ g

A decision can be made on any expression

truegrade >= 60 print “Passed”

on any expression. zero - falsenonzero - trueExample:

false

3 - 4 is true

Page 12: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection SSelection Statementtatement

if

Only performs an action if the condition is trueif…else

Specifies an action to be performed both when the condition is trueand when it is false

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

Print “Passed”Print Passedelse

Print “Failed”

Note spacing/indentation conventions

Page 13: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection StSelection Statementatement

C code:if ( grade >= 60 )

printf( "Passed\n");

else

printf( "Failed\n");

Ternary conditional operator (?:) Takes three arguments (condition, value if true, value if false)Our pseudocode could be written:pprintf( "%s\n", grade >= 60 ? "Passed" : "Failed" );

Or it could have been written:d 60 ? i f( “ d\ ” ) i f( grade >= 60 ? printf( “Passed\n” ) : printf(

“Failed\n” );

Page 14: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection StSelection Statementatement

Flow chart of the if…else selection statement

truefalsegrade >= 60

print “Failed” print “Passed”

Nested if…else statements Test for multiple cases by placing if…else selection statements inside if…else selection statementOnce condition is met rest of statements skippedOnce condition is met, rest of statements skippedDeep indentation usually not used in practice

Page 15: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection StSelection Statementatement

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 80Print “B”

else else If student’s grade is greater than or equal to 70

Print “C”else else

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

lelsePrint “F”

Page 16: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection StSelection Statementatement

Compound statement: Set of statements within a pair of bracesExample:if ( d 60 )if ( grade >= 60 )

printf( "Passed.\n" );

else {

i f( " il d \ " )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

Page 17: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The ifif……elseelse Selection StSelection Statementatement

Block:Compound statements with declarations

Syntax errorsSyntax errorsCaught by compiler

L i Logic errors: Have their effect at execution timeNon-fatal: program runs, but has incorrect outputFatal: program exits prematurely

Page 18: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The whilewhile Repetition StRepetition Statementatementpp

Repetition structurepProgrammer specifies an action to be repeated while some condition remains truePsuedocode:

While there are more items on my shopping listy pp gPurchase next item and cross it off my list

while loop repeated until condition becomes false

Page 19: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

The The whilewhile Repetition StRepetition Statementatementpp

Example: pint product = 2;

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

product <= 1000 product = 2 * producttrue

false

Page 20: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating AlgorithmsFormulating Algorithms(Counter(Counter--Controlled Repetition)Controlled Repetition)(( p )p )

Counter-controlled repetitionLoop repeated until counter reaches a certain valueDefinite repetition: number of repetitions is known Example: A class of ten students took a quiz The grades (integers in the range 0 Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quizPseudocode:

S l Set total to zeroSet grade counter to one

While grade counter is less than or equal to tenInput the next gradeInput the next gradeAdd the grade into the totalAdd one to the grade counter

Set the class average to the total divided by teng yPrint the class average

Page 21: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

1 /* Class average program with counter-controlled repetition */ 2 3 #include <stdio.h> 4

/ f i i b i i /5 /* function main begins program execution */ 6 main() 7 { 8 int counter; /* number of grade to be entered next */ 9 int grade; /* grade value */ 9 int grade; /* grade value */ 10 int total; /* sum of grades input by user */ 11 int average; /* average of grades */ 12 13 /* initialization phase */ 13 / initialization phase /

14 total = 0; /* initialize total */ 15 counter = 1; /* initialize loop counter */ 16 17 /* processing phase */ p g p

18 while ( counter <= 10 ) { /* loop 10 times */ 19 printf( "Enter grade: " ); /* prompt for input */ 20 scanf( "%d", &grade ); /* read grade from user */ 21 total = total + grade; /* add grade to total */ 22 counter = counter + 1; /* increment counter */ 23 } /* end while */ 24

 

Page 22: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

25 /* termination phase */ 26 average = total / 10; /* integer division */ 27 28 /* display result */ 29 printf( "Class average is %d\n", average ); 30 31 system(“pause”); 32

Enter grade: 98Enter grade: 76

33 } /* end function main */  

Enter grade: 76Enter grade: 71Enter grade: 87Enter grade: 83Enter grade: 90Enter grade: 57Enter grade: 79Enter grade: 82Enter grade: 94Class average is 81Class average is 81

Page 23: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating Algorithms with TopFormulating Algorithms with Top--Down, Down, Stepwise RefinementStepwise Refinementpp

Problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run.Unknown number of studentsHow will the program know to end?

U ti l l Use sentinel value Also called signal value, dummy value, or flag valueIndicates “end of data entry ”Indicates end of data entry.Loop ends when user inputs the sentinel valueSentinel value chosen so it cannot be confused with a regular input (such as -1 in g p (this case)

Page 24: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating Algorithms with TopFormulating Algorithms with Top--Down, Down, Stepwise RefinementStepwise Refinementpp

Top-down, stepwise refinement p pBegin with a pseudocode representation of the top:

Determine the class average for the quiz

Divide top into smaller tasks and list them in order: Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

Many programs have three phases:I l l h blInitialization: initializes the program variablesProcessing: inputs data values and adjusts program variables accordinglyTermination: calculates and prints the final resultsTermination: calculates and prints the final results

Page 25: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating Algorithms with TopFormulating Algorithms with Top--Down, Down, Stepwise RefinementStepwise Refinementpp

Refine the initialization phase from Initialize variablespto:

Initialize total to zeroInitialize counter to zero

Refine Input, sum and count the quiz grades to Input the first grade (possibly the sentinel)While the user has not as yet entered the sentinel

Add this grade into the running totalAdd this grade into the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)

Page 26: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating Algorithms with TopFormulating Algorithms with Top--Down, Down, Stepwise RefinementStepwise Refinementpp

Refine Calculate and print the class average top gIf the counter is not equal to zero

Set the average to the total divided by the counterPrint the average

elsePrint “No grades were entered”g

Page 27: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Formulating Algorithms with TopFormulating Algorithms with Top--Down, Down, Stepwise RefinementStepwise Refinementpp

Initialize total to zeroInitialize counter to zeroInitialize counter to zero

Input the first gradeWhil h h d h i l While the user has not as yet entered the sentinel

Add this grade into the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)

If the counter is not equal to zeroIf the counter is not equal to zeroSet the average to the total divided by the counterPrint the average

lelsePrint “No grades were entered”

Page 28: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

1 /* Class average program with sentinel-controlled repetition */ 2 3 #include <stdio.h> 4

/ f i i b i i /5 /* function main begins program execution */ 6 main() 7 { 8 int counter; /* number of grades entered */ 9 int grade; /* grade value */ 9 int grade; /* grade value */ 10 int total; /* sum of grades */ 11 12 float average; /* number with decimal point for average */ 13 13 14 /* initialization phase */ 15 total = 0; /* initialize total */ 16 counter = 0; /* initialize loop counter */ 17 18 /* processing phase */ 19 /* get first grade from user */ 20 printf( "Enter grade, -1 to end: " ); /* prompt for input */ 21 scanf( "%d", &grade ); /* read grade from user */ 22 23 /* loop while sentinel value not yet read from user */ 24 while ( grade != -1 ) { 25 total = total + grade; /* add grade to total */ 26 counter = counter + 1; /* increment counter */ 27  

Page 29: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

28 printf( "Enter grade, -1 to end: " ); /* prompt for input */ 29 scanf("%d", &grade); /* read next grade */ 30 } /* end while */ 31 31 32 /* termination phase */ 33 /* if user entered at least one grade */ 34 if ( counter != 0 ) { 35 36 /* calculate average of all grades entered */ 37 average = ( float ) total / counter; 38 39 /* display average with two digits of precision */ 40 printf( "Class average is %.2f\n", average ); 41 } /* end if */ 42 else { /* if no grades were entered, output message */ 43 printf( "No grades were entered\n" );

} / d l /44 } /* end else */ 45 46 system(“pause”); 47 48 } /* end function main */ 48 } / end function main /

 

Page 30: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Enter grade, -1 to end: 75d 1 d 9Enter grade, -1 to end: 94

Enter grade, -1 to end: 97Enter grade, -1 to end: 88Enter grade, -1 to end: 70Enter grade, 1 to end: 70Enter grade, -1 to end: 64Enter grade, -1 to end: 83Enter grade, -1 to end: 89E t d 1 t d 1Enter grade, -1 to end: -1Class average is 82.50

Enter grade, -1 to end: -1Enter grade, 1 to end: 1No grades were entered

Page 31: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Nested control structuresNested control structures

Problem A college has a list of test results (1 = pass, 2 = fail) for 10 studentsWrite a program that analyzes the results

If th 8 t d t i t "R i T iti "If more than 8 students pass, print "Raise Tuition"

Notice thatThe program must process 10 test resultsThe program must process 10 test results

Counter-controlled loop will be used

Two counters can be usedOne for number of passes, one for number of fails

Each test result is a number—either a 1 or a 2If th b i t 1 th t it i 2If the number is not a 1, we assume that it is a 2

Page 32: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Nested control structuresNested control structures

Top level outlinepAnalyze exam results and decide if tuition should be raised

First RefinementFirst RefinementInitialize variablesInput the ten quiz grades and count passes and failuresp q g pPrint a summary of the exam results and decide if tuition should be raised

Refine Initialize variables to Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

Page 33: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Nested control structuresNested control structures

Refine Input the ten quiz grades and count passes and failuresto to

While student counter is less than or equal to tenInput the next exam resultIf th t d t dIf the student passed

Add one to passeselse

Add one to failuresAdd one to failuresAdd one to student counter

Refine Print a summary of the exam results and decide if i i h ld b i dtuition should be raised to

Print the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition”

Page 34: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Nested control structuresNested control structuresInitialize passes to zeroInitialize failures to zeroInitialize student to one

While student counter is less than or equal to tenInput the next exam result

If the student passedAdd one to passes

elseelseAdd one to failures

Add one to student counterAdd one to student counter

Print the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition”

Page 35: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

1 /* Analysis of examination results */ 2 3 #include <stdio.h> 4 4 5 /* function main begins program execution */ 6 main() 7 { 8 /* initialize variables in definitions */ / /

9 int passes = 0; /* number of passes */ 10 int failures = 0; /* number of failures */ 11 int student = 1; /* student counter */ 12 int result; /* one exam result */ 13 14 /* process 10 students using counter-controlled loop */ 15 while ( student <= 10 ) { 16 17 /* prompt user for input and obtain value from user */ 18 printf( "Enter result ( 1=pass,2=fail ): " ); 19 scanf( "%d", &result ); 20 21 /* if result 1 increment passes */ 21 /* if result 1, increment passes */ 22 if ( result == 1 ) { 23 passes = passes + 1; 24 } /* end if */  

Page 36: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

25 else { /* otherwise, increment failures */ 26 failures = failures + 1; 27 } /* end else */ 28 29 d d 1 /* i d */ 29 student = student + 1; /* increment student counter */ 30 } /* end while */ 31 32 /* termination phase; display number of passes and failures */ 33 printf( "Passed %d\n" passes ); 33 printf( Passed %d\n , passes );

34 printf( "Failed %d\n", failures ); 35 36 /* if more than eight students passed, print "raise tuition" */ 37 if ( passes > 8 ) { 37 if ( passes > 8 ) { 38 printf( "Raise tuition\n" ); 39 } /* end if */ 40 41 system(“pause”); y ( p );

42 43 } /* end function main */

 

Page 37: Lecture 7a S ClC ontrol Statements ((if, if--else, while)))kasim/mech/sme1013/SME1013-ControlStatements1.pdf · Control Structures Sequential execution ~Statements executed one after

Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 2Enter Result (1=pass,2=fail): 2Enter Result (1=pass,2=fail): 1( p , )Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 2Enter Result (1=pass,2=fail): 1( p , )Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 2Passed 6Failed 4 Enter Result (1=pass,2=fail): 1Enter Result (1=pass 2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 2Enter Result (1=pass,2=fail): 1Enter Result (1=pass 2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass,2=fail): 1Enter Result (1=pass 2=fail): 1Enter Result (1=pass,2=fail): 1Passed 9Failed 1Raise tuition