control structures - 1 - universitas indonesia · diamond symbol (decision symbol) indicates...

36
Control Structures - 1 Adhi Harmoko S, M.Komp

Upload: tranthien

Post on 26-May-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Control Structures - 1

Adhi Harmoko S, M.Komp

IntroductionBefore writing a program:

Have a thorough understanding of problem Carefully plan your approach for solving it

While writing a program: Know what “building blocks” are availableUse good programming principles

AlgorithmsAll computing problems

can be solved by executing a series of actions in a specific order

AlgorithmA procedure determining the

Actions to be executed Order in which these actions are to be executed

Program controlSpecifies the order in which statements are to executed

PseudocodePseudocode

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

Control StructuresSequential execution

Statements executed one after the other in the order writtenTransfer of control

When the next statement executed is not the next one in sequenceBohm and Jacopini: all programs written in terms of 3 control structures

Sequence structureBuilt into C++. Programs executed sequentially by default.

Selection structuresC++ has three types - if, if/else, and switch

Repetition structuresC++ has three types - while, do/while, and for

Control StructuresC++ keywords

Cannot be used as identifiers or variable namesC++ Keywords

Keywords 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 voidvolatile while

C++ 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 StructuresFlowchart

Graphical representation of an algorithmDrawn using certain special-purpose symbols connected by arrows called flowlines. Rectangle symbol (action symbol)

Indicates any type of action.Oval symbol

indicates beginning or end of a program, or a section of code (circles).

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.

The if Selection StructureSelection structure

used 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 next statement

If the condition is falseprint statement is ignored and the program goes onto the next statement

Indenting makes programs easier to readC++ ignores whitespace characters

The if Selection StructureTranslation of pseudocode statement into C++:

if ( grade >= 60 ) cout << "Passed";

Diamond symbol (decision symbol)indicates decision is to be madeContains an expression that can be true or false.

Test the condition, follow appropriate pathif structure is a single-entry/single-exit structure

The if Selection StructureFlowchart of pseudocode statement

true

false

grade >= 60 print “Passed”

A decision can be made on any expression.

zero - false

nonzero - true

Example:

3 - 4 is true

The if/else Selection Structureif

Only performs an action if the condition is trueif/else

A different action is performed when condition is true and when condition is false

Psuedocodeif student’s grade is greater than or equal to 60print “Passed”

else

print “Failed”

C++ codeif ( grade >= 60 )

cout << "Passed";else

cout << "Failed";

The if/else Selection Structure

Ternary conditional operator (?:)Takes three arguments (condition, value if true, value if false)

Our pseudocode could be written:cout << ( grade >= 60 ? “Passed” : “Failed” );

truefalse

print “Failed” print “Passed”

grade >= 60

The if/else Selection StructureNested if/else structures

Test for multiple cases by placing if/else selection structures inside if/else selection structures.

if student’s grade is greater than or equal to 90Print “A”

else if student’s grade is greater than or equal to 80

Print “B”else

if student’s grade is greater than or equal to 70 Print “C”

else if student’s grade is greater than or equal to 60

Print “D”else

Print “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 << "Passed.\n";

else {cout << "Failed.\n";cout << "You must take this course

again.\n";}

Without the braces,cout << "You must take this course again.\n";

would be automatically executedBlock

Compound statements with declarations

The if/else Selection StructureSyntax errors

Errors caught by compilerLogic errors

Errors which have their effect at execution timeNon-fatal logic errors

program runs, but has incorrect outputFatal logic errors

program exits prematurely

The while Repetition StructureRepetition structure

Programmer specifies an action to be repeated while some condition remains truePsuedocodewhile 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;

The while Repetition StructureFlowchart of while loop

product <= 1000 product = 2 * producttrue

false

Formulating Algorithms (Counter-Controlled Repetition)

Counter-controlled repetitionLoop repeated until counter reaches a certain value.

Definite repetitionNumber of repetitions is known

ExampleA 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 quiz

Formulating Algorithms (Counter-Controlled Repetition)

Pseudocode for example:Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to ten

Input the next gradeAdd the grade into the totalAdd one to the grade counterSet the class average to the total divided by tenPrint the class average

Following is the C++ code for this example

fig02_07.cpp

1. Initialize Variables

2. Execute Loop

3. Output results

fig02_07.cpp12345678910111213141516171819

// Fig. 2.7: fig02_07.cpp// Class average program with #include

usingusingusing

// function main begiint{

counter-controlled repetition.<iostream>

std::cout;std::cin;std::endl;

ns program executionmain()

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 counter

1. Initialize Variables

2. Execute Loop

3. Output results

fig02_07.cpp2021222324252627282930313233343536

// processing phase

}

while ( gradeCounter <= 10 ) { // loop 10 timescout << "Enter grade: "; // prompt for inputcin >> grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter

}

// termination phaseaverage = total / 10; // integer division

// display resultcout << "Class average is " << average << endl;

return 0; // indicate program ended successfully

// end function main

fig02_07.cpp2021222324252627282930313233343536

// processing phase

}

while ( gradeCounter <= 10 ) { // loop 10 timescout << "Enter grade: "; // prompt for inputcin >> grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter

}

// termination phaseaverage = total / 10; // integer division

// display resultcout << "Class average is " << average << endl;

return 0; // indicate program ended successfully

// end function main

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

fig02_07.cpp2021222324252627282930313233343536

// processing phasewhile ( gradeCounter <= 10 ) { // loop 10 times

cout << "Enter grade: "; // prompt for inputcin >> grade; // read grade from usertotal = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter

}

// termination phaseaverage = total / 10; // integer division

// display resultcout << "Class average is " << average << endl;

return 0; // indicate program ended successfully

} // end function main

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

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

Formulating Algorithms with Top-Down, Stepwise Refinement (Sentinel-Controlled Repetition)

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

Sentinel valueIndicates “end of data entry”Loop ends when sentinel inputtedSentinel value chosen so it cannot be confused with a regular input (such as -1 in this case)

Formulating Algorithms with Top-Down, Stepwise Refinement (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 Refinement

Many programs can be divided into three phases: Initialization

Initializes the program variablesProcessing

Inputs data values and adjusts program variables accordinglyTermination

Calculates and prints the final results. Helps the breakup of programs for top-down refinement.

Refine the initialization phase fromInitialize variables

toInitialize total to zeroInitialize counter to zero

Formulating Algorithms with Top-Down, Stepwise Refinement

RefineInput, 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 one to the grade counterInput the next grade (possibly the sentinel)

RefineCalculate and print the class average

toIf the counter is not equal to zero

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

ElsePrint “No grades were entered”

Fig. 2.9: fig02_09.cpp

1. 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

#include

using

// function main begiint{

sentinel-controlled repetition.<iostream>

std::cout;std::cin;std::endl;std::fixed;

<iomanip> // parameterized stream manipulators

std::setprecision; // sets numeric output precision

ns program executionmain()

int total; // sum of gradesint gradeCounter; // number of grades enteredint grade; // grade value

double average; // number with decimal point for average

1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Results

// Fig. 2.9: fig02_09.cpp// Class average program with sentinel-controlled repetition.#include <iostream>

using std::cout;using std::cin;using std::endl;using std::fixed;

#include <iomanip> // parameterized stream manipulators

using std::setprecision; // sets numeric output precision

// function main begins program executionint main(){

int total; // sum of gradesint gradeCounter; // number of grades enteredint grade; // grade value

double average; // number with decimal point for average

Fig. 2.9: fig02_09.cpp123456789101112131415161718192021

1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Results

The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.

Fig. 2.9: fig02_09.cpp22232425262728293031323334353637383940

// initialization phasetotal = 0; // initialize totalgradeCounter = 0; // initialize loop counter

// processing phase// get first grade from usercout << "Enter grade, -1 to end: "; // prompt for inputcin >> grade; // read grade from user

// loop until sentinel value read from userwhile ( grade != -1 ) {

total = total + grade; // add grade to totalgradeCounter = gradeCounter + 1; // increment counter

cout << "Enter grade, -1 to end: "; // prompt for inputcin >> 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.cpp

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 << "Class average is " << setprecision( 2 )

<< fixed << average << endl;

} // end if part of if/else

else // if no grades were entered, output appropriate messagecout << "No grades were entered" << endl;

return 0; // indicate program ended successfully

} // end function main

1. Initialize Variables2. Get user input2.1 Perform Loop3. Calculate Average3.1 Print Results

Fig. 2.9: fig02_09.cpp

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 << "Class average is " << setprecision( 2 )

<< fixed << average << endl;

} // end if part of if/else

else // if no grades were entered, output appropriate messagecout << "No grades were entered" << endl;

return 0; // indicate program ended successfully

} // end function main

static_cast<double>() - treats total as a double temporarily. Required because dividing two integers truncates the remainder.gradeCounter is an int, but it gets promoted to double.

Fig. 2.9: fig02_09.cpp

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 << "Class average is " << setprecision( 2 )

<< fixed << average << endl;

} // end if part of if/else

else // if no grades were entered, output appropriate messagecout << "No grades were entered" << endl;

return 0; // indicate program ended successfully

} // end function main

setprecision(2) - prints only two digits past decimal point.

Programs that use this must include <iomanip>

Fig. 2.9: fig02_09.cpp

Enter 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