1 / 24

Program Structure IV

Learn about the different control structures in programming, including sequence, selection, and repetition structures. Understand how to use if statements for decision-making and how to format your code. Explore examples and flowcharts to enhance your understanding.

glennowen
Download Presentation

Program Structure IV

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Program Structure IV • Transfer of control • Sequence, selection, repetition structures • Selection structure • if • if-else • if… else if … • Code formatting • Repetition structure • while-loop • for-loop • Nested control structures [Please switch off your phone]

  2. line 1. line 2. line 3. line 4. line 5. line 6. line 7. line 8. line 9. line 10. var mark; mark=prompt('What is your mark?',''); if (mark>40) document.write('Passed.'); else { document.write('Failed.'); document.write('<br/>'); document.write('You must take this course again!'); } document.write('<br/>End of report.'); Transfer of control Overview: Sometimes, next statement to execute may not be the next one in sequence. For example: • After the checking at line 3 has finished, either line 4 or line 5 will be executed. • Suppose line 4 is executed after line 3, we say "the control is transferred to line 4". • Suppose line 5 is executed after line 3, we say "the controlis transferred to line 5". • In case line 4 is executed, then after line 4 is executed, line 10 will be executed. • We say "the controlis transferred to line 10".

  3. 1 2 3 a = 3; b = 4; alert(a+b); 1 2 3 4 if (mark>40) document.write('pass'); else document.write('fail'); var count=1; while (count<=10) { document.write('hello</br>'); count++; } 1 2 3 4 5 Transfer of control Three different kinds of Control Structures (1) Sequence structure Statements execute in the order they are written. This is the default flow unless other control structures are applied. Example Firstly execute line 1 Then execute line 2 Finally execute line 3 (2) Selection structure The choice of next statement is based on a test: whether a condition is true or not. (3) Repetition structure (learn later) A statement (or a set of statements) is to be repeated again and again until the repetition condition becomes false.

  4. One whole if statement Transfer of control – The if statement The if statement if (condition) statement-to-be-executed; • If the conditionis true, then statement-to-be-executedwill be executed. • If the condition is not true (false), then statement-to-be-executedwill not be executed. • Must have a pair of outer brackets: if (..) brackets around “mark<0” and “mark>100” are optional • if (mark > 80) • if mark > 80 this is OK!! • if ( (mark < 0) || (mark > 100) ) alert('invalid mark'); this is OK too!! • if ( mark < 0 || mark > 100 ) • if (mark < 0) || (mark > 100) this is wrong!! Outer brackets should NOT be omitted.

  5. Start mark<=40 True Output ‘Failed’ Output ‘<br/>’ False Output ‘Please ..’ End Transfer of control – The if statement • To execute 2 or more statements under a condition, use braces to group them as a compound statement. Example: if (mark<=40) { document.write('Failed.'); document.write('<br/>'); document.write('Please retake.'); } if (condition) { .. some statements .. } A compound statement: a sequence of statements grouped by braces { and } One whole if statement

  6. Start (mark<0) || (mark>100) Output “wrong mark” True False Handle normal cases End Transfer of control – The if statement • (Recall 3ProgramStructureII.ppt slide #17)Sometimes we apply a checking at the beginning of a function: /*Check the mark, show the grade*/ function sayTheGrade(mark) { if ( (mark<0) || (mark>100) ) { alert("wrong mark"); return; } if (mark>80) alert('A'); … … … … } Handle abnormal cases: If it is abnormal, just say the error andquit the function immediately. Under normal cases, remaining code will continue.

  7. Transfer of control – The if statement • In normal cases (like below), the code after the whole if statement does not depend on the condition. if (mark > 40) document.write("Congratulations! You've passed!<br/>"); document.write("Good-bye!"); In the above, the code document.write("Good-bye!");does not belong to the if statement. "Good-bye!" will be shown no matter whether the mark is passed or not. Try to draw the flowchart:

  8. End of the whole if statement End of the whole if statement Transfer of control – The if statement • The whole if statement is ended when the first semi-colon is found. • Examples: if (mark > 40) document.write("Congratulations!"); document.write("You've passed!<br/>"); Wrong output if (mark > 40) document.write("Congratulations!"); document.write("You've passed!<br/>"); Wrong output In each of the above, the code document.write("You've passed!<br/>");does not belong to the if statement anymore. Therefore "You've passed!" will be shown no matter whether the mark is passed or not. To correct, use braces “{..}” to enclose all involved statements.

  9. End of the whole if statement Transfer of control – The if statement • Do NOT put a semi-colon after the condition. Wrong output if (mark > 40); document.write("Congratulations! You've passed!<br/>"); This code does not belong to the if statement anymore. This greeting will be shown no matter whether the mark is passed or not.

  10. One whole if-else statement Start Statement-I Statement-II True False condition End Transfer of control – The if..else statement The if..else statement if (condition) statement-I; else statement-II; • If the conditionis true, then statement-Iwill be executed, statement-IIwill not be executed. • If the condition is not true (false), then statement-IIwill be executed, statement-Iwill not be executed.

  11. One whole if-else statement Transfer of control – The if..else statement The if..else statement if (condition) statement-I; else statement-II; • If 2 or more statements have to be executed in place of statement-I (or statement-II), then they should be in form of a compound statement, ie. grouped by brackets { and }. if (condition) { .. some statements .. } else statement-II; if (condition) statement-I; else { .. some statements .. } if (condition) { .. some statements .. } else { .. some statements .. }

  12. Another one if-else statement Transfer of control – The if..else statement • Control structures can be nested. For example: if (condition A) if (condition B) statement-I-I else statement-I-II else statement-II; if (condition A) statement-I; else if (condition B) statement-II-I else statement-II-II if (condition A) if (condition B) statement-I-I else statement-I-II else if (condition C) statement-II-I else statement-II-II • We should add additional braces to avoid confusions of matching between else and if. • Example: if (female==true) if (married) document.write('Mrs.'); else document.write('Miss'); else document.write('Mr.'); if (female==true) {if (married) document.write('Mrs.'); else document.write('Miss'); } else document.write('Mr.'); Improved version

  13. Transfer of control – The if..else if .. statement • (Recall 3ProgramStructureII.ppt slide #21)A special form of the nested if..else statement is based on parallel conditions like: if (tutorialNumber==1) room='CSC-D'; else if (tutorialNumber==2) room='CSC-K'; else if (tutorialNumber==3) room='CSC-B'; else if (tutorialNumber==4) room='CSC-A'; else alert('Wrong number'); if (tutorialNumber==1) room='CSC-D'; else if (tutorialNumber==2) room='CSC-K'; else if (tutorialNumber==3) room='CSC-B'; else if (tutorialNumber==4) room='CSC-A'; else alert('Wrong number'); To better represent the parallel relationship among the cases, We may align them as: • No matter which style is being used, the indentations of lines should be consistent. • [indentation means the positioning of the first character in a line.]

  14. Figure 1 if (female==true) {if (married) document.write('Mrs.'); else document.write('Miss'); } else { document.write('Mr.'); } Figure 2 Figure 3 Difficult to read and find out errors. Code Formatting if (female==true) {if (married) document.write('Mrs.'); else document.write('Miss');} else document.write('Mr.'); • Code Formatting : Consistent positioning/indentation • Make your code easy to read. -- Relationship between statements is clear • Make it easier to find out errors.-- Easier to match beginning and ending braces • Usually, • (Recall 4ProgramStructureIII.ppt slide #8)'}' should align with the beginning of the control structure (if, else, function etc..). • For ‘{' , both ways in figures 2 and 3 are okay. • 2. Additional { and } can be added for better clarity. • 3. else should align with the matching if or else if. • 4. The if(..), else, and else if(..) parts should occupy whole lines. • statement-to-be-executedshould start on a separate line. or if (female==true) { if (married) document.write('Mrs.'); else document.write('Miss'); } else { document.write('Mr.'); }

  15. One whole while statement Start condition True Statement-to-be-executed False End Transfer of control – Repetition structure (while-loop) The while statement (while-loop) while (condition) statement-to-be-executed; Explanation: • If the conditionis not true (false), then statement-to-be-executedwill not be executed, and the whole while statement is ended. • Otherwise statement-to-be-executedwill be executed. • 1 and 2 are repeated until the condition becomes false.

  16. Start condition True Statement-to-be-executed False End Transfer of control – Repetition structure (while-loop) The while statement (while-loop) while (condition) statement-to-be-executed; • Note that: • If the condition is already false at the very beginning, statement-to-be-executed will not be executed and the whole while statement is ended immediately. • The while (condition)line is executed one time more than statement-to-be-executed.Reason: the last time of checking obtains a false condition that ends the while-loop. • Don't type a semi-colon after the while part like while (condition);what will happen? • while (condition); - means while the condition is true, nothing is to be done. • - just keep on checking the condition only. Can it stop?

  17. 1. 2. 3. 4. 5. 6. var count=1; while (count<=10) { document.write(count + ' hello</br>'); count++; } alert('End'); End Transfer of control – Repetition structure (while-loop) Example 1: Display 10 lines of "hello" : line 1: count is set to 1 line 2: "count<=10" is checked (it is true) line 3: document.write(..) shows "1 hello" line 4: "count++; " is done (count becomes 2) line 2: "count<=10" is checked (it is true) line 3: document.write(..) shows "2 hello" line 4: "count++; " is done (count becomes 3) line 2: "count<=10" is checked (it is true) line 3: document.write(..) shows "3 hello" line 4: "count++; " is done (count becomes 4) .. .. line 4: "count++; " is done (count becomes 10) line 2: "count<=10" is checked (it is true) line 3: document.write(..) shows "10 hello" line 4: "count++; " is done (count becomes 11) line 2: "count<=10" is checked (it is false) line 6: alert('End'); is done => the dialog shows "End". Questions: 1. How many times lines 1, 2, 3, 4, 6 are executed? 2. What is the value of count after the while-loop is finished?

  18. var i=1; var square=1; while (i<=10) { document.write(i + '*' + i + ' is ' + square + '</br>'); i++; square = i*i; } 1. 2. 3. 4. 5. 6. 7. var i=10; var square=100; while (square<200) { document.write(i + '*' + i + ' is ' + square + '</br>'); i++; square = i*i; } 1. 2. 3. 4. 5. 6. 7. Transfer of control – Repetition structure (while-loop) Example 2: Display the first 10 square numbers starting from 1*1 Example 3: Display all square numbers between 100 and 200

  19. Start pre-statement condition True loop-statement post-statement False End for-loop will not appear in test/exam of this course Transfer of control – Repetition structure (for-loop) The for statement (for-loop) for (pre-statement;condition; post-statement) loop-statement; Explanation: • Execute pre-statement • Check the condition. If it is not true (false), then the whole for statement is ended. • Otherwise loop-statement will be executed, followed by post-statement • 2 and 3 are repeated until the condition becomes false.

  20. Start pre-statement condition True loop-statement post-statement False End for-loop will not appear in test/exam of this course Transfer of control – Repetition structure (for-loop) The for statement (for-loop) for (pre-statement;condition; post-statement) loop-statement; • Note that: • The pre-statement is executed exactly once (not depend on the initial true/false value of the condition. • The condition is checked one time more than loop-statement and post-statement • Reason: the last time of checking obtains a false condition that ends the loop. • Like while-loops, don't type a semi-colon after for(...) like for (..);

  21. for (pre-statement;condition; post-statement) loop-statement; for-loop will not appear in test/exam of this course Transfer of control – Repetition structure (for-loop) • Run pre-statement • Check the condition. If false, then finish • Otherwise run loop-statement, then post-statement • Repeat 2 and 3 until the condition becomes false • for-loop is usually used if we know the number of times of looping. • The previous examples for while-loops can be rewritten as: var count=1; while (count<=10) { document.write(count + ' hello</br>'); count++; } alert('End'); var count; for (count=1;count<=10;count++) { document.write(count + ' hello</br>'); } alert('End');

  22. Nested Control Structures • A control structure (if-else, while, or for-loop etc..) can containone or more control structures, that can contain further control structures. • A simple example is: • To show the first 100 square numbers starting from 1*1, 10 numbers in a row. • Design: if i equals 10, 20, 30,.., then add a line break after displaying the square. var i=1; var square=1; while (i<=100) { document.write(square + ' '); if (i%10==0) { document.write('<br/>'); } i++; square = i*i; }

  23. Nested Control Structures To show the first 100 square numbers starting from 1*1, 10 numbers in a row, in an HTML table. var i=1; var square=1; document.write('<table border="1">'); while (i<=100) { /*if it is first cell of a row, ie. i=1,11,21,etc.. write <tr>*/ if (i%10==1) document.write('<tr>'); /*write the ith cell*/ document.write('<td>'+square + '</td>'); /*if it is last cell of a row, ie. i=10,20,30,etc.. write </tr>*/ if (i%10==0) document.write('</tr>'); /*prepare i and square for next iteration*/ i++; square = i*i; } document.write('</table>');

  24. Summary • Transfer of control • Sequence structure • Selection structure • Repetition structure • Selection structure • if • if-else • if… else if … • Code formatting • Repetition structure • while-loop • for-loop • Nested control structures

More Related