版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、1,3,Structured Program Development in C C結構化程式的開發,2,OBJECTIVES,In this chapter you will learn: Basic problem-solving techniques (問題解決的技術). To develop algorithms through the process oftop-down(由上而下), stepwise refinement(逐步改良). To use the if selection statement (if選擇敘述式) and if.else selection statemen
2、t (ifelse選擇敘述式) to select actions. To use the while repetition statement (while重複敘述式) to execute statements in a program repeatedly. Counter-controlled repetition (計數器控制重複結構) and sentinel-controlled repetition (警示訊號控制重複結構). Structured programming (結構化程式設計). The increment(遞增), decrement (遞減) and assi
3、gnment operators (指定運算子).,3,3.1Introduction (簡介) 3.2Algorithms (演算法) 3.3Pseudocode (虛擬程式碼) 3.4Control Structures (控制結構) 3.5The if Selection Statement (if選擇敘述式) 3.6The if.else Selection Statement (ifelse 選擇敘述式) 3.7The while Repetition Statement (while重複敘述式),4,3.8Formulating Algorithms: Case Study 1(C
4、ounter-Controlled Repetition) 計數器控制的重複結構 3.9Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) 警示訊號控制的重複結構 3.10Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures) 巢狀的控制結構 3.11Assignment Operators 指定
5、運算子 3.12Increment and Decrement Operators 遞增與遞減運算子,5,3.1 Introduction,Before writing a program: Have a thorough understanding of the problem Carefully plan an approach for solving it While writing a program: Know what “building blocks” are available Use good programming principles,6,3.2 Algorithms (
6、演算法),Computing problems (計算問題) All can be solved by executing a series of actions (一系列的動作) in a specific order (特定順序) Algorithm: procedure (程序) in terms of Actions to be executed (將要執行的動作) The order in which these actions are to be executed (執行這些動作的順序) Program control (程式控制) Specify order in which s
7、tatements are to be executed (指定敘述式在程式中執行的順序),7,3.3 Pseudocode (虛擬碼; 虛擬程式碼),Pseudocode Artificial, informal language (非正規的語言) that helps us develop algorithms Similar to everyday English (口語化) Not actually executed on computers (不能真的在電腦上執行) Helps us “think out” a program before writing it Easy to co
8、nvert into a corresponding C or C+ program (易於轉換成C或C+的程式碼) Consists only of executable statements (由可執行的敘述式組成),8,3.4 Control Structures (控制結構),Sequential execution (循序式的執行) Statements executed one after the other in the order written (程式碼一行接著一行執行) Transfer of control (控制權的移轉) 1960 When the next stat
9、ement executed is not the next one in sequence Overuse of goto statements led to many problems (過度使用goto將造成許多問題),9,3.4 Control Structures (控制結構) (續),Bohm (波姆) and Jacopini (賈可皮尼) 1970 All programs written in terms of 3 control structures (所有程式皆可由3種控制結構寫成) Sequence structures(循序結構): Built into C. Pro
10、grams executed sequentially by default (C語言內建的特性) Selection structures(選擇結構): C has three types: if, ifelse, and switch Repetition structures(重複結構): C has three types: while, dowhile and for,10,Fig. 3.1 | Flowcharting Cs sequence structure (C循環結構的流程圖).,連接符號 (connector symbols : 表示流程開始),11,3.4 Contro
11、l Structures,Flowchart (流程圖) Graphical representation of an algorithm (圖型化表示) Drawn using certain special-purpose symbols connected by arrows called flowlines Rectangle symbol (action symbol): 方塊符號 Indicates any type of action Oval symbol: 橢圓形符號 Indicates the beginning or end of a program or a secti
12、on of code Single-entry/single-exit control structures (單一入口/單一出口的控制結構) Connect exit point of one control structure to entry point of the next (control-structure stacking 控制敘述式的堆疊) Makes programs easy to build,12,3.5 The if selection statement,Selection structure (選擇結構): Used to choose among alterna
13、tive courses of action (可以選取不同功能的動作) Pseudocode: If students 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 Indenting
14、 (縮排) makes programs easier to read C ignores whitespace characters (忽略空白字元),13,3.5 The if selection statement,Pseudocode statement in C: if ( grade = 60 ) printf( Passedn ); C code corresponds closely to the pseudocode Diamond symbol (decision symbol) 決策符號 Indicates decision is to be made Contains
15、an expression that can be true or false Test the condition, follow appropriate path (),14,Fig. 3.2 | Flowcharting the single-selection if statement.,15,3.6 The ifelse selection statement,if Only performs an action (執行某一項動作) if the condition is true (當條件為真時) ifelse Specifies an action to be performed
16、 both when the condition is true and when it is false Psuedocode: If students grade is greater than or equal to 60Print “Passed” elsePrint “Failed” Note spacing/indentation conventions (注意縮排),16,3.6 The ifelse selection statement,C code: if ( grade = 60 ) printf( Passedn); else printf( Failedn); Ter
17、nary conditional operator (?:) 三元條件運算子 Takes three arguments (condition, value if true, value if false) Our pseudocode could be written: printf( %sn, grade = 60 ? Passed : Failed ); Or it could have been written: grade = 60 ? printf( “Passedn” ) : printf( “Failedn” );,17,Fig. 3.3 | Flowcharting the
18、double-selection if.else statement.,18,3.6 The ifelse selection statement,Nested ifelse statements (巢狀ifelse敘述式) Test for multiple cases by placing ifelse selection statements inside ifelse selection statement Once condition is met, rest of statements skipped Deep indentation usually not used in pra
19、ctice (避免過深的縮排),19,3.6 The ifelse selection statement,Pseudocode for a nested ifelse statement If students grade is greater than or equal to 90Print “A”else If students grade is greater than or equal to 80 Print “B”else If students grade is greater than or equal to 70 Print “C” else If students grad
20、e is greater than or equal to 60 Print “D” else Print “F”,巢狀 ifelse 敘述式,20,3.6 The ifelse 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 t
21、his course again.n ); Without the braces, the statement printf( You must take this course again.n ); would be executed automatically,21,3.6 The ifelse selection statement,Block (區塊): Compound statements with declarations Syntax errors (語法錯誤) Caught by compiler Logic errors (邏輯錯誤) Have their effect a
22、t execution time Non-fatal: program runs, but has incorrect output 程式正常執行,但是輸出不對! Fatal: program exits prematurely 程式過早執行結束,22,3.7 The while repetition statement (while重複結構),Repetition structure (重複結構) Programmer specifies an action to be repeated while some condition remains true (當某個條件成立時) Pseudoc
23、ode: 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 Example: int product = 2; while ( product = 1000 )product = 2 * product;,23,Fig. 3.4 | Flowcharting the while repetition statement.,24,3.8 Counter-Control
24、led Repetition,Counter-controlled repetition (計數器控制的重複結構) Loop (迴圈) repeated until counter reaches a certain value Definite repetition: number of repetitions is known Example: A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determin
25、e the class average on the quiz. (算出考試的班平均成績),25,Fig. 3.5 | Pseudocode algorithm that uses counter-controlled repetition tosolve the class average problem.,26,Outline,fig03_06.c (1 of 2 ),Counter to control while loop,Initialize counter to 1,while loop iterates as long as counter = 10,Increment the
26、counter,27,Outline,fig03_06.c (2 of 2 ),Calculate the average,28,3.9 Formulating Algorithms with Top-Down, Stepwise Refinement (由上而下逐步改進的方法建構演算法: 警示訊號控制的重複結構),Problem becomes: (未知的學生數量) Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. Un
27、known number of students (關鍵點 : 不知道學生數量) How will the program know to end ?,29,3.9 Formulating Algorithms with Top-Down, Stepwise Refinement (續),Use sentinel value (警示訊號) Also called signal value (訊號值), dummy value (虛值), or flag value (旗標值) Indicates “end of data entry.” (表示資料輸入的結束) Loop ends when u
28、ser inputs the sentinel value (當使用者輸入警示訊號時 迴圈結束!) Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case),30,3.9 Formulating Algorithms with Top-Down, Stepwise Refinement,Top-down, stepwise refinement (由上而下逐步改進的技術) Begin with a pseudocode representation of the t
29、op (總敘述式): Determine the class average for the quiz Divide top into smaller tasks (較小的工作: 初步改進 first refinement) and list them in order: Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average,31,3.9 Formulating Algorithms with Top-Down, Stepwise Refinement,Many
30、 programs have three phases: Initialization (初始化階段): initializes the program variables (設定程式裡的變數初始值) Processing (處理階段): inputs data values and adjusts program variables accordingly (負責輸入資料並修該相對應的變數) Termination (結束階段): calculates and prints the final results (負責計算並列印出最後的結果),32,3.9 Formulating Algori
31、thms with Top-Down, Stepwise Refinement,Refine the initialization phase from Initialize variables to: 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
32、this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel),33,3.9 Formulating Algorithms with Top-Down, Stepwise Refinement,Refine Calculate and print the class average to If the counter is not equal to zero Set the average to the total divided by the
33、 counter Print the averageelse Print “No grades were entered”,34,Fig. 3.7 | Pseudocode algorithm that uses sentinel-controlled repetition tosolve the class average problem.,35,Outline,fig03_08.c (1 of 3 ),float type indicates variable can be a non-integer,36,Outline,fig03_08.c (2 of 3 ),while loop r
34、epeats until user enters a value of -1,Ensures the user entered at least one grade,Prints result with 2 digits after decimal point,Converts total to float type,37,Outline,fig03_08.c (3 of 3 ),38,3.10 Nested Control Structures (巢狀控制結構),Problem A college has a list of test results (1 = pass, 2 = fail)
35、 for 10 students Write a program that analyzes the results If more than 8 students pass, print Raise Tuition“ (調漲學費) Notice that The program must process 10 test results Counter-controlled loop will be used (使用計數器控制迴圈) Two counters can be used One for number of passes, one for number of fails Each t
36、est result is a numbereither a 1 or a 2 If the number is not a 1, we assume that it is a 2,39,3.10 Nested Control Structures,Top level outline Analyze exam results and decide if tuition should be raised First Refinement Initialize variables Input the ten quiz grades and count passes and failures Pri
37、nt a summary of the exam results and decide if tuition should be raised Refine Initialize variables to Initialize passes to zero Initialize failures to zero Initialize student counter to one,40,3.10 Nested Control Structures,Refine Input the ten quiz grades and count passes and failures to While stu
38、dent counter is less than or equal to tenInput the next exam result If the student passed Add one to passeselse Add one to failures Add one to student counter Refine Print a summary of the exam results and decide if tuition should be raised to Print the number of passes Print the number of failures
39、If more than eight students passed Print “Raise tuition”,41,Fig. 3.9 | Pseudocode for examination results problem.,42,Outline,fig03_10.c (1 of 3 ),if and else statements are nested inside while loop,while loop continues until 10 students have been processed,43,Outline,fig03_10.c (2 of 3 ),44,Outline,fig03_10.c (3 of 3 ),45,3.11 Assignment Operators (指定運算字),Assignment operators abbreviate assignment expressions c = c + 3; can be abbreviated as c += 3; using
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 为档案质量控制工作提供了坚实制度
- 大班硬笔书法奖惩制度
- 街道办事处工作奖惩制度
- 上下工序互检奖惩制度
- 团队考勤管理及奖惩制度
- 药店员工奖惩制度及流程
- 酒吧安全卫士奖惩制度
- 学校安全生产奖惩制度
- 门店巡检奖惩制度范本
- 公司奖惩制度三合一制度
- (正式版)SH∕T 3006-2024 石油化工控制室设计规范
- 住房按揭借款合同
- 二手车交易合伙协议
- 2024年江苏信息职业技术学院高职单招(英语/数学/语文)笔试历年参考题库含答案解析
- 板材行业销售渠道分析
- 2024地面用晶体硅光伏组件环境适应性测试要求第1部分:一般气候条件
- 合同税率变更补充协议
- 教科版四年级下册科学全册教案
- 苏教版五年级下册数学 列方程解决两步实际问题 教案(教学设计)
- 人教版《体育与健康》水平二 跳跃单元作业设计
- 《煤气安全作业》培训教材
评论
0/150
提交评论