Giáo trình tin học chương II
1 Chapter - Control Structures Outline Control Structures if Selection Structure if/else Selection Structure while Repetition Structure Formulating Algorithms: Case Study (Counter-Controlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study (Sentinel-Controlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study (Nested Control Structures) Assignment Operators Increment and Decrement Operators Essentials of Counter-Controlled Repetition for Repetition Structure switch Multiple-Selection Structure do/while Repetition Structure break and continue Statements Logical Operators Confusing Equality (==) and Assignment (=) Operators Structured-Programming Summary 2003 Prentice Hall, Inc All rights reserved Control Structures • Sequential execution – Statements executed in order • Transfer of control – Next statement executed not next one in sequence • control structures (Bohm and Jacopini) – Sequence structure • Programs executed sequentially by default – Selection structures • if, if/else, switch – Repetition structures • while, do/while, for 2003 Prentice Hall, Inc All rights reserved Control Structures • C++ keywords – Cannot be used as identifiers or variable names C++ Keyw o rd s Keywords common to the C and C++ programming languages auto continue enum if short switch volatile C++ only keywords asm delete inline private static_cast try wchar_t break default extern int signed typedef while case float long sizeof union char double for register static unsigned const else goto return struct void bool dynamic_cast mutable protected template typeid catch explicit namespace public this typename class false new reinterpret_cast throw using const_cast friend operator 2003 Prentice Hall, Inc All rights reserved true virtual if Selection Structure • in C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout = 60 true zero - false print “Passed” nonzero - true Example: false 2003 Prentice Hall, Inc All rights reserved - is true if/else Selection Structure • if – Performs action if condition true • if/else – Different actions if conditions true or false • Pseudocode if student’s grade is greater than or equal to 60 print “Passed” else print “Failed” • C++ code if ( grade >= 60 ) cout = 90 ) cout = 80 ) cout = 70 ) cout = 60 ) cout