control structures – 2 · nested control structures problem: a college has a list of test results...

37
Control Structures – 2 Adhi Harmoko S, M.Komp

Upload: others

Post on 19-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Control Structures – 2

Adhi Harmoko S, M.Komp

Page 2: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Nested control structuresProblem:

A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition".

We can see thatThe program must process 10 test results. A counter-controlled loop will be used. Two counters can be used—one to count the number of students who passed the exam and one to count the number of students who failed the exam. Each test result is a number—either a 1 or a 2. If the number is not a 1, we assume that it is a 2.

Top level outline:Analyze exam results and decide if tuition should be raised

Page 3: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Nested control structuresFirst Refinement:

Initialize variablesInput the ten quiz grades and count passes and failuresPrint a summary of the exam results and decide if tuition should be raised

RefineInitialize variables

to Initialize passes to zeroInitialize failures to zeroInitialize student counter to one

Page 4: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Nested control structuresRefine

Input the ten quiz grades and count passes and failuresto

While student counter is less than or equal to tenInput the next exam resultIf the student passed

Add one to passesElse

Add one to failuresAdd one to student counter

RefinePrint a summary of the exam results and decide if tuition should be raised

toPrint the number of passesPrint the number of failuresIf more than eight students passed

Print “Raise tuition”

Page 5: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.11: fig02_11.cpp

1. Initialize variables2. Input data and count

passes/failures3. Print results

Page 6: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.11: fig02_11.cpp1234567891011121314151617181920212223

// Fig. 2.11: fig02_11.cpp// Analysis of exam#include

usingusingusing

// function main begiint{

ination results.<iostream>

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

ns program executionmain()

// initialize variables in declarationsint passes = 0; // number of passesint failures = 0; // number of failuresint studentCounter = 1; // student counterint result; // one exam result

// process 10 students using counter-controlled loopwhile ( studentCounter <= 10 ) {

// prompt user for input and obtain value from usercout << "Enter result (1 = pass, 2 = fail): ";cin >> result;

1. Initialize variables2. Input data and count

passes/failures3. Print results

Page 7: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.11: fig02_11.cpp2425262728293031323334353637383940414243444546

// if result 1, increment passes; if/else nested in whileif ( result == 1 ) // if/else nested in while

passes = passes + 1;

else // if result not 1, increment failuresfailures = failures + 1;

// increment studentCounter so loop eventually terminatesstudentCounter = studentCounter + 1;

} // end while

// termination phase; display number of passes and failurescout << "Passed " << passes << endl; cout << "Failed " << failures << endl;

// if more than eight students passed, print "raise tuition"if ( passes > 8 )

cout << "Raise tuition " << endl;

return 0; // successful termination

// end function main}

Page 8: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.11: fig02_11.cpp

Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 2Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Enter result (1=pass,2=fail): 1Passed 9Failed 1Raise tuition

Page 9: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Assignment OperatorsAssignment expression abbreviations

c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Statements of the formvariable = variable operator expression;

can be rewritten asvariable operator= expression;

Examples of other assignment operators include:d -= 4 (d = d - 4)e *= 5 (e = e * 5)f /= 3 (f = f / 3)g %= 9 (g = g % 9)

Page 10: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Increment and Decrement OperatorsIncrement operator (++) - can be used instead of c += 1Decrement operator (--) - can be used instead of c -= 1

PreincrementWhen the operator is used before the variable (++c or –c)Variable is changed, then the expression it is in is evaluated.

PosincrementWhen the operator is used after the variable (c++ or c--)Expression the variable is in executes, then the variable is changed.

If c = 5, then cout << ++c; prints out 6 (c is changed before cout is executed)cout << c++; prints out 5 (cout is executed before the increment. c now has the value of 6)

Page 11: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Increment and Decrement OperatorsWhen Variable is not in an expression

Preincrementing and postincrementing have the same effect.++c;cout << c;

and c++; cout << c;

have the same effect.

Page 12: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Essentials of Counter-Controlled Repetition

Counter-controlled repetition requires:The name of a control variable (or loop counter).The initial value of the control variable.The condition that tests for the final value of the control variable (i.e., whether looping should continue).The increment (or decrement) by which the control variable is modified each time through the loop.

Example: int counter =1; //initializationwhile (counter <= 10){ //repetition condition

cout << counter << endl;++counter; //increment

}

Page 13: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Essentials of Counter-Controlled Repetition

The declarationint counter = 1;

Names counterDeclares counter to be an integerReserves space for counter in memorySets counter to an initial value of 1

Page 14: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The for Repetition StructureThe general format when using for loops isfor ( initialization; LoopContinuationTest;

increment )

statement

Example: for( int counter = 1; counter <= 10; counter++ )

cout << counter << endl;

Prints the integers from one to tenNo semicolon after last statement

Page 15: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The for Repetition StructureFor loops can usually be rewritten as while loops:

initialization;while ( loopContinuationTest){

statementincrement;

}

Initialization and increment as comma-separated listsfor (int i = 0, j = 0; j + i <= 10; j++, i++)

cout << j + i << endl;

Page 16: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Examples Using the for StructureProgram to sum the even numbers from 2 to 100

12345678910111213141516171819

// Fig. 2.20: fig02_20.cpp// Summation with for.#include <iostream>using std::cout;using std::endl;

// function main begins program executionint main(){

int sum = 0; // initialize sum

// sum even integers from 2 through 100for ( int number = 2; number <= 100; number += 2 )

sum += number; // add number to sum

cout << "Sum is " << sum << endl; // output sumreturn 0; // successful termination

} // end function main

Sum is 2550

Page 17: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Examples Using the for StructureProgram to sum the even numbers from 2 to 100

12345678910111213141516171819

// Fig. 2.20: fig02_20.cpp// Summation with for.#include <iostream>using std::cout;using std::endl;

// function main begiint main(){

} // end function main

ns program execution

int sum = 0; // initialize sum

// sum even integers from 2 through 100for ( int number = 2; number <= 100; number += 2 )

sum += number; // add number to sum

cout << "Sum is " << sum << endl; // output sumreturn 0; // successful termination

Page 18: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The switch Multiple-Selection Structure

switch

Useful when variable or expression is tested for multiple valuesConsists of a series of case labels and an optional default case

Page 19: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The switch Multiple-Selection Structure

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

Page 20: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp

1. Initialize variables2. Input data2.1 Use switch loop to

update count2.1 Use switch loop to

update count3. Print results

Page 21: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp1234567891011121314151617181920

// Fig. 2.22: fig02_22.cpp// Counting letter grades.#include <iostream>

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

// function main begiint main(){

ns program execution

int grade; // one gradeint aCount = 0; // number of Asint bCount = 0; // number of Bsint cCount = 0; // number of Csint dCount = 0; // number of Dsint fCount = 0; // number of Fs

cout << "Enter the letter grades." << endl<< "Enter the EOF character to end input." << endl;

1. Initialize variables2. Input data2.1 Use switch loop to

update count2.1 Use switch loop to

update count3. Print results

Page 22: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp2122232425262728293031323334353637383941

// loop until user types end-of-file key sequencewhile ( ( grade = cin.get() ) != EOF ) {

// determine which grade was inputswitch ( grade ) { // switch structure nested in while

case 'A': // grade was uppercase Acase 'a': // or lowercase a

++aCount; // increment aCountbreak; // necessary to exit switch

case 'B': // grade was uppercase Bcase 'b': // or lowercase b

++bCount; // increment bCountbreak; // exit switch

case 'C': // grade was uppercase Ccase 'c': // or lowercase c

++cCount; // increment cCountbreak; // exit switch

Page 23: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp2122232425262728293031323334353637383941

// loop until user types end-of-file key sequencewhile ( ( grade = cin.get() ) != EOF ) {

// determine which grade was inputswitch ( grade ) { // switch structure nested in while

case 'A': // grade was uppercase Acase 'a': // or lowercase a

++aCount; // increment aCountbreak; // necessary to exit switch

case 'B': // grade was uppercase Bcase 'b': // or lowercase b

++bCount; // increment bCountbreak; // exit switch

case 'C': // grade was uppercase Ccase 'c': // or lowercase c

++cCount; // increment cCountbreak; // exit switch

Notice how the case statement is used

Page 24: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp2122232425262728293031323334353637383941

// loop until user types end-of-file key sequencewhile ( ( grade = cin.get() ) != EOF ) {

// determine which grade was inputswitch ( grade ) { // switch structure nested in while

case 'A': // grade was uppercase Acase 'a': // or lowercase a

++aCount; // increment aCountbreak; // necessary to exit switch

case 'B': // grade was uppercase Bcase 'b': // or lowercase b

++bCount; // increment bCountbreak; // exit switch

case 'C': // grade was uppercase Ccase 'c': // or lowercase c

++cCount; // increment cCountbreak; // exit switch

Notice how the case statement is used

break causes switch to end and the program continues with the first statement after the switch structure.

Page 25: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp4243444546474849505152535455565758596061626364

case 'D': // grade was uppercase Dcase 'd': // or lowercase d

++dCount; // increment dCountbreak; // exit switch

case 'F': // grade was uppercase Fcase 'f': // or lowercase f

++fCount; // increment fCount break; // exit switch

case '\n': // ignore newlines,case '\t': // tabs, case ' ': // and spaces in input

break; // exit switch

default: // catch all other characterscout << "Incorrect letter grade entered."

<< " Enter a new grade." << endl;break; // optional; will exit switch anyway

} // end switch

} // end while

Page 26: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp4243444546474849505152535455565758596061626364

case 'D': // grade was uppercase Dcase 'd': // or lowercase d

++dCount; // increment dCountbreak; // exit switch

case 'F': // grade was uppercase Fcase 'f': // or lowercase f

++fCount; // increment fCount break; // exit switch

case '\n': // ignore newlines,case '\t': // tabs, case ' ': // and spaces in input

break; // exit switch

default: // catch all other characterscout << "Incorrect letter grade entered."

<< " Enter a new grade." << endl;break; // optional; will exit switch anyway

} // end switch

} // end while

Notice the default statement.

Page 27: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cpp656667686970717273747576

// output summary of resultscout << "\n\nTotals for each letter grade are:"

<< "\nA: " << aCount // display number of A grades<< "\nB: " << bCount // display number of B grades<< "\nC: " << cCount // display number of C grades<< "\nD: " << dCount // display number of D grades<< "\nF: " << fCount // display number of F grades<< endl;

return 0; // indicate successful termination

// end function main}

Page 28: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Fig. 2.22: fig02_22.cppEnter the letter grades.Enter the EOF character to end input.aBcCAdfCEIncorrect letter grade entered. Enter a new grade.DAb

Totals for each letter grade are: A: 3B: 2C: 3D: 2F: 1

Page 29: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The do/while Repetition StructureThe do/while repetition structure is similar to the whilestructure,

Condition for repetition tested after the body of the loop is executed

Format:do {

statement} while ( condition );

Example (letting counter = 1): do {cout << counter << " ";

} while (++counter <= 10);

This prints the integers from 1 to 10All actions are performed at least once.

Page 30: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The break and continue StatementsBreak

Causes immediate exit from a while, for, do/whileor switch structureProgram execution continues with the first statement after the structureCommon uses of the break statement:

Escape early from a loopSkip the remainder of a switch structure

Page 31: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

The break and continue StatementsContinue

Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loopIn while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executedIn the for structure, the increment expression is executed, then the loop-continuation test is evaluated

Page 32: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Logical Operators&& (logical AND)

Returns true if both conditions are true|| (logical OR)

Returns true if either of its conditions are true! (logical NOT, logical negation)

Reverses the truth/falsity of its conditionReturns true when its condition is falseIs a unary operator, only takes one condition

Logical operators used as conditions in loopsExpression Resulttrue && false falsetrue || false true!false true

Page 33: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Confusing Equality (==) and Assignment (=) Operators

These errors are damaging because they do not ordinarily cause syntax errors.

Recall that any expression that produces a value can be used in control structures. Nonzero values are true, and zero values are false

Example:if ( payCode == 4 )

cout << "You get a bonus!" << endl;Checks the paycode, and if it is 4 then a bonus is awarded

If == was replaced with =if ( payCode = 4 )

cout << "You get a bonus!" << endl; Sets paycode to 44 is nonzero, so the expression is true and a bonus is awarded, regardless of paycode.

Page 34: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Confusing Equality (==) and Assignment (=) Operators

LvaluesExpressions that can appear on the left side of an equationTheir values can be changedVariable names are a common example (as in x = 4;)

RvaluesExpressions that can only appear on the right side of an equationConstants, such as numbers(i.e. you cannot write 4 = x;)

Lvalues can be used as rvalues, but not vice versa

Page 35: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Structured-Programming SummaryStructured programming

Programs are easier to understand, test, debug and, modify. Rules for structured programming

Only single-entry/single-exit control structures are usedRules:

1) Begin with the “simplest flowchart”.2) Any rectangle (action) can be replaced by two rectangles

(actions) in sequence. 3) Any rectangle (action) can be replaced by any control structure

(sequence, if, if/else, switch, while, do/while or for).4) Rules 2 and 3 can be applied in any order and multiple times.

Page 36: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Structured-Programming Summary

Rule 3

Rule 3Rule 3

Representation of Rule 3 (replacing any rectangle with a control structure)

Page 37: Control Structures – 2 · Nested control structures Problem: A college has a list of test results (1 = pass, 2 = fail) for 10students. Write a program that analyzes the results

Structured-Programming SummaryAll programs can be broken down into

SequenceSelection

if, if/else, or switchAny selection can be rewritten as an if statement

Repetitionwhile, do/while or forAny repetition structure can be rewritten as a whilestatement