Lecture 7

staff.fisika.ui.ac.id
  • No tags were found...

Lecture 7

Control Structures - 1Adhi Harmoko S, M.Komp


IntroductionBefore writing a program:Have a thorough understanding of problemCarefully plan your approach for solving itWhile writing a program:Know what “building blocks” are availableUse good programming principles


AlgorithmsAll computing problemscan be solved by executing a series of actions in a specificorderAlgorithmA procedure determining theActions to be executedOrder in which these actions are to be executedProgram controlSpecifies the order in which statements are to executed


PseudocodePseudocodeArtificial, informal language used to develop algorithmsSimilar to everyday EnglishNot actually executed on computersAllows us to “think out” a program before writing thecode for itEasy to convert into a corresponding C++ programConsists only of executable statements


Control StructuresC++ keywordsCannot be used as identifiers or variable namesC++ KeywordsKeywords common to the C and C++ programming languagesauto break case char constcontinue default do double elseenum extern float for gotoif int long register returnshort signed sizeof static structswitch typedef union unsigned voidvolatilewhileC++ only keywordsasm bool catch class const_castdelete dynamic_cast explicit false friendinline mutable namespace new operatorprivate protected public reinterpret_caststatic_cast template this throw truetry typeid typename using virtualwchar_t


Control StructuresFlowchartGraphical representation of an algorithmDrawn using certain special-purpose symbols connectedby arrows called flowlines.Rectangle symbol (action symbol)Indicates any type of action.Oval symbolindicates beginning or end of a program, or a sectionof code (circles).single-entry/single-exit control structuresConnect exit point of one control structure to entrypoint of the next (control-structure stacking).Makes programs easy to build.


The if Selection StructureSelection structureused to choose among alternative courses of actionPseudocode example:If student’s grade is greater than or equal to 60Print “Passed”If the condition is trueprint statement executed and program goes on to nextstatementIf the condition is falseprint statement is ignored and the program goes onto the nextstatementIndenting makes programs easier to readC++ ignores whitespace characters


The if Selection StructureTranslation of pseudocode statement into C++:if ( grade >= 60 )cout


The if Selection StructureFlowchart of pseudocode statementgrade >= 60trueprint “Passed”A decision can bemade on anyexpression.zero - falsenonzero - truefalseExample:3 - 4 is true


The if/else Selection StructureifOnly performs an action if the condition is trueif/elseA different action is performed when condition is true and whencondition is falsePsuedocodeif student’s grade is greater than or equal to 60print “Passed”elseprint “Failed”C++ codeif ( grade >= 60 )cout


The if/else Selection Structurefalsegrade >= 60trueprint “Failed”print “Passed”Ternary conditional operator (?:)Takes three arguments (condition, value if true, value iffalse)Our pseudocode could be written:cout = 60 ? “Passed” :“Failed” );


The if/else Selection StructureNested if/else structuresTest for multiple cases by placing if/else selection structuresinside if/else selection structures.if student’s grade is greater than or equal to 90Print “A”elseif student’s grade is greater than or equal to 80Print “B”elseif student’s grade is greater than or equal to 70Print “C”elseif student’s grade is greater than or equal to 60Print “D”elsePrint “F”Once a condition is met, the rest of the statements are skipped


The if/else Selection StructureCompound statement:Set of statements within a pair of bracesExample:if ( grade >= 60 )cout


The if/else Selection StructureSyntax errorsErrors caught by compilerLogic errorsErrors which have their effect at execution timeNon-fatal logic errorsprogram runs, but has incorrect outputFatal logic errorsprogram exits prematurely


The while Repetition StructureRepetition structureProgrammer specifies an action to be repeated whilesome condition remains truePsuedocodewhile there are more items on my shopping listPurchase next item and cross it off my listwhile loop repeated until condition becomes false.Exampleint product = 2;while ( product


The while Repetition StructureFlowchart of while loopproduct


Formulating Algorithms (Counter-ControlledRepetition)Counter-controlled repetitionLoop repeated until counter reaches a certain value.Definite repetitionNumber of repetitions is knownExampleA class of ten students took a quiz. The grades(integers in the range 0 to 100) for this quizare available to you. Determine the class averageon the quiz


Formulating Algorithms (Counter-ControlledRepetition)Pseudocode for example:Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to tenInput the next gradeAdd the grade into the totalAdd one to the grade counterSet the class average to the total divided by tenPrint the class averageFollowing is the C++ code for this example


fig02_07.cpp1. Initialize Variables2. Execute Loop3. Output results


fig02_07.cpp12345678910111213141516171819// Fig. 2.7: fig02_07.cpp// Class average program with#include usingusingusingstd::cout;std::cin;std::endl;counter-controlled repetition.// function main begins program executionint main(){int total; // sum of grades input by userint gradeCounter; // number of grade to be entered nextint grade; // grade valueint average; // average of grades// initialization phasetotal = 0; // initialize totalgradeCounter = 1; // initialize loop counter1. Initialize Variables2. Execute Loop3. Output results


fig02_07.cpp2021222324252627282930313233343536// processing phasewhile ( gradeCounter grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter}}// termination phaseaverage = total / 10; // integer division// display resultcout


fig02_07.cpp2021222324252627282930313233343536// processing phasewhile ( gradeCounter grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter}}// termination phaseaverage = total / 10; // integer division// display resultcout


fig02_07.cpp20212223242526272829303132333435// processing phasewhile ( gradeCounter grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter}The counter gets incremented eachtime the loop executes. Eventually,the counter causes the loop to end.// termination phaseaverage = total / 10; // integer division// display resultEnter grade: cout


Formulating Algorithms with Top-Down, StepwiseRefinement (Sentinel-Controlled Repetition)Suppose the problem becomes:Develop a class-averaging program that will process anarbitrary number of grades each time the program is run.Unknown number of students - how will the programknow to end?Sentinel valueIndicates “end of data entry”Loop ends when sentinel inputtedSentinel value chosen so it cannot be confused with aregular input (such as -1 in this case)


Formulating Algorithms with Top-Down, StepwiseRefinement (Sentinel-Controlled Repetition)Top-down, stepwise refinementbegin with a pseudocode representation of the top:Determine the class average for the quizDivide top into smaller tasks and list them in order:Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average


Formulating Algorithms with Top-Down,Stepwise RefinementMany programs can be divided into three phases:InitializationInitializes the program variablesProcessingInputs data values and adjusts program variables accordinglyTerminationCalculates and prints the final results.Helps the breakup of programs for top-down refinement.Refine the initialization phase fromInitialize variablestoInitialize total to zeroInitialize counter to zero


Formulating Algorithms with Top-Down,Stepwise RefinementRefineInput, sum and count the quiz gradestoInput the first grade (possibly the sentinel)While the user has not as yet entered the sentinelAdd this grade into the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)RefineCalculate and print the class averagetoIf the counter is not equal to zeroSet the average to the total divided by the counterPrint the averageElsePrint “No grades were entered”


Fig. 2.9: fig02_09.cpp1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Results


Fig. 2.9: fig02_09.cpp123456789101112131415161718192021// Fig. 2.9: fig02_09.cpp// Class average program with#include usingusingusingusing#includeusingstd::cout;std::cin;std::endl;std::fixed;sentinel-controlled repetition. // parameterized stream manipulatorsstd::setprecision; // sets numeric output precision// function main begins program executionint main(){int total; // sum of gradesint gradeCounter; // number of grades enteredint grade; // grade value1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Resultsdouble average; // number with decimal point for average


Fig. 2.9: fig02_09.cpp123456789101112131415161718192021// Fig. 2.9: fig02_09.cpp// Class average program with sentinel-controlled repetition.#include using std::cout;using std::cin;using std::endl;using std::fixed;#include // parameterized stream manipulatorsusing std::setprecision; // sets numeric output precision// function main begins program executionint main(){int total; // sum of gradesint gradeCounter; // number of grades enteredint grade; // grade value1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print ResultsThe counter gets incremented eachtime the loop executes. Eventually,the counter causes the loop to end.double average; // number with decimal point for average


Fig. 2.9: fig02_09.cpp22232425262728293031323334353637383940// initialization phasetotal = 0; // initialize totalgradeCounter = 0; // initialize loop counter// processing phase// get first grade from usercout > grade; // read grade from user// loop until sentinel value read from userwhile ( grade != -1 ) {total = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment countercout > grade; // read next grade} // end while 1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Results


Fig. 2.9: fig02_09.cpp41424344454647484950515253545556575859// termination phase// if user entered at least one grade ...if ( gradeCounter != 0 ) {// calculate average of all grades enteredaverage = static_cast< double >( total ) / gradeCounter;// display average with two digits of precisioncout


Fig. 2.9: fig02_09.cpp41424344454647484950515253545556575859// termination phase// if user entered at least one grade ...if ( gradeCounter != 0 ) {// calculate average of all grades enteredaverage = static_cast< double >( total ) / gradeCounter;// display average with two digits of precisioncout


Fig. 2.9: fig02_09.cppsetprecision(2) - prints only two digitspast decimal point.41424344454647484950515253545556575859// termination phase// if user entered at least one grade ...if ( gradeCounter != 0 ) {// calculate average of all grades enteredaverage = static_cast< double >( total ) / gradeCounter;// display average with two digits of precisioncout


Fig. 2.9: fig02_09.cppEnter grade, -1 to end: 75Enter grade, -1 to end: 94Enter grade, -1 to end: 97Enter grade, -1 to end: 88Enter grade, -1 to end: 70Enter grade, -1 to end: 64Enter grade, -1 to end: 83Enter grade, -1 to end: 89Enter grade, -1 to end: -1Class average is 82.50

More magazines by this user
Similar magazines