+ All Categories
Home > Documents > Control Structures RepetitionorIterationorLooping Part I.

Control Structures RepetitionorIterationorLooping Part I.

Date post: 17-Jan-2016
Category:
Upload: anissa-williams
View: 216 times
Download: 3 times
Share this document with a friend
23
Control Structures Control Structures Repetition Repetition or or Iteration Iteration or or Looping Looping Part I Part I
Transcript
Page 1: Control Structures RepetitionorIterationorLooping Part I.

Control StructuresControl Structures

RepetitionRepetition

oror

IterationIteration

oror

LoopingLooping

Part IPart I

Page 2: Control Structures RepetitionorIterationorLooping Part I.

SequenceSequence Print out a sales reportPrint out a sales report

Open the salesperson fileOpen the salesperson file

Print heading on formPrint heading on form

Skip 3 linesSkip 3 lines

Read the first recordRead the first record

Print salesperson’s namePrint salesperson’s name

Also called “Straight-Line” Programs

Page 3: Control Structures RepetitionorIterationorLooping Part I.

Decision (selection, branching)Decision (selection, branching)

sales > quotasales > quotayes

bonus=sales*.01bonus=sales*.01

no

bonus = 0bonus = 0

Sequential prior to if

{

sequential

inside an if }

true

Sequential after an if

falseblock

Page 4: Control Structures RepetitionorIterationorLooping Part I.

Switch (Multiple Decision)Switch (Multiple Decision)

Option=1Option=1 Option=2Option=2 Option=3Option=3 Option=4Option=4

Can always be written as nested if

Assumes no multiple cases, break for each, no default

Page 5: Control Structures RepetitionorIterationorLooping Part I.

Repetition (iteration, looping) Repetition (iteration, looping)

More?More?

Comm = Sales*.02Comm = Sales*.02

Calculate PayCalculate Pay

Print CheckPrint Check

NoNo

YesYesSequential inside of the loop

truefalse

After the loop,

continue sequentially

with next statement

Page 6: Control Structures RepetitionorIterationorLooping Part I.

The The whilewhile Statement Statement

SyntaxSyntaxwhile while (expression)(expression)

statement statement

Example:count = 1;while (count <= 10){

cout << “Yankees are #1\n”;count = count + 1;

}next statement

*

Page 7: Control Structures RepetitionorIterationorLooping Part I.

The The whilewhile Statement Statement

SyntaxSyntaxwhile while (expression)(expression)

statement statement

a loop control variable is evaluated a loop control variable is evaluated in the expressionin the expression

the loop statements contain the lines the loop statements contain the lines executed each time the loop repeatsexecuted each time the loop repeats

Page 8: Control Structures RepetitionorIterationorLooping Part I.

The The whilewhile Statement Statement

loop

Exit the Exit the whilewhile

0 0 ororFalseFalse

Test theexpression

statements to execute

1 1 ororTrueTrue

Page 9: Control Structures RepetitionorIterationorLooping Part I.

Something to Note Note Note...Something to Note Note Note...

count = 1;count = 1;

while (count <= 10)while (count <= 10){{

cout << “Yankees are #1\n”;cout << “Yankees are #1\n”;cout << “and will win the series\n”; cout << “and will win the series\n”;

}}next statementnext statement

*

How do we get out?

Page 10: Control Structures RepetitionorIterationorLooping Part I.

The The whilewhile Statement Statement loop control variable is initialized before loop control variable is initialized before

while statementwhile statement evaluation or test is performed within the evaluation or test is performed within the

expressionexpression the body may contain any number of the body may contain any number of

statements, including branches and other statements, including branches and other loopsloops

the control variable is changed during the control variable is changed during loop execution in order to exit looploop execution in order to exit loop

the statement immediately after thethe statement immediately after the while while is executed upon exitingis executed upon exiting

* * * * *

Page 11: Control Structures RepetitionorIterationorLooping Part I.

int num;int num;cout << "NUMBER SQUARE CUBE\n"cout << "NUMBER SQUARE CUBE\n" << "------ ------ ----\n"; << "------ ------ ----\n";

A Simple ExampleA Simple Example

num = 1;while (num < 11){

cout << setw(3) << num << " " << setw(3) << num * num << " " << setw(4) << num * num * num <<‘\n’;num++; // increment num

}

* * *

Page 12: Control Structures RepetitionorIterationorLooping Part I.

Simple Example OutputSimple Example Output

NUMBER SQUARE CUBENUMBER SQUARE CUBE----------------------------------------------------------------------------------------------------------------------

11 11 1 1

22 44 8 8

33 99 27 27

……

1010 100 100 10001000

Page 13: Control Structures RepetitionorIterationorLooping Part I.

double celsius, fahren;double celsius, fahren;cout << "CELSIUS FAHRENHEIT\n"cout << "CELSIUS FAHRENHEIT\n" << "------- ----------\n"; << "------- ----------\n";

Another ExampleAnother Example

celsius = 5; // starting Celsius valuewhile (celsius <= 50){ fahren = (9.0/5.0) * celsius + 32.0; cout << setw(4) << celsius

<< setiosflags(ios::showpoint) << setw(13) << setprecision(2) << fahren << '\n';

celsius = celsius + 5;}Note: The text shows CONSTANTS in this program on page 179

* * *

Page 14: Control Structures RepetitionorIterationorLooping Part I.

Problem Solving:Problem Solving:Finding the Largest ValueFinding the Largest Value

The program asks for the number of The program asks for the number of items in the list.items in the list.

Checks to see if that number is positive.Checks to see if that number is positive. Gets user input.Gets user input. Assigns the largest to variable Assigns the largest to variable max.max.

* * * *

Page 15: Control Structures RepetitionorIterationorLooping Part I.

int count = 0, n = 0;int count = 0, n = 0; double max = 0, x = 0;double max = 0, x = 0;

cout << "The maximum value will be computed.\n";cout << "The maximum value will be computed.\n";

cout << "How many numbers do you wish to enter? ";cout << "How many numbers do you wish to enter? ";cin >> n;cin >> n;

while (n <= 0)while (n <= 0){{ cout << "\nERROR: Positive integer required.\n\n”;cout << "\nERROR: Positive integer required.\n\n”;

cout << "How many numbers to enter? ";cout << "How many numbers to enter? ";cin >> n;cin >> n;

}}

cout << “Enter a real number: “;cin >> x;max = x; // first value to max * * * *

Page 16: Control Structures RepetitionorIterationorLooping Part I.

while (count++ < (n-1))while (count++ < (n-1)) // first n accepted above{{

cout << “Enter a real number: “;cout << “Enter a real number: “;cin >> x;cin >> x;if (max < x)if (max < x) max = x; max = x;

}}cout << “Maximum value: “ << max << “\n”;cout << “Maximum value: “ << max << “\n”;

}}

OutputOutputThe maximum value will be computed.The maximum value will be computed.How many numbers do you wish to enter? 4How many numbers do you wish to enter? 4Enter a real number: 1.01 Enter a real number: 1.01 Enter a real number: -3 Enter a real number: -3 Enter a real number: 2.2Enter a real number: 2.2Enter a real number: 7.07000 Enter a real number: 7.07000 Maximum value: 7.07Maximum value: 7.07 * * *

Page 17: Control Structures RepetitionorIterationorLooping Part I.

Counter++Counter++n = 5;n = 5;

count = 0;count = 0;

cout << “Enter “ << n << … cout << “Enter “ << n << … cin >> x;cin >> x;max = x;max = x; // count = 0

11 while (count++ < (n-1))while (count++ < (n-1))

2 {{

3 cout << “LOOP number: cout << “LOOP number: ““

cin >> x;cin >> x;

4 if (max < x)if (max < x)

5 max = x;max = x;

6 }}

cout <<“Max is “<<max;cout <<“Max is “<<max;

loopcount n executed 1 5 1 2 2 3 3 4 4 5

*

Page 18: Control Structures RepetitionorIterationorLooping Part I.
Page 19: Control Structures RepetitionorIterationorLooping Part I.

Common Use: Running TotalsCommon Use: Running Totals(Accumulator)(Accumulator)

while (count <=4)while (count <=4){{

cout << “Enter a number: “;cout << “Enter a number: “;cin >> num;cin >> num;total = total + num;total = total + num;cout << “The total is “ << total;cout << “The total is “ << total;count++;count++;

}}

count =1; // variables must be initialized

total = 0; // before loop

*

Page 20: Control Structures RepetitionorIterationorLooping Part I.

Common Use: AverageCommon Use: Average

While (count <=4)While (count <=4){{ cout <<“Enter a number ”;cout <<“Enter a number ”; cin >> number;cin >> number; total += number;total += number; count++;count++;}}average = total / (count-1); average = total / (count-1); cout << “The average is “ << average << endl;cout << “The average is “ << average << endl;

count =1;

total = 0;

float average;

Why count – 1?

Page 21: Control Structures RepetitionorIterationorLooping Part I.

Sentinel Loops – exit controlled by Sentinel Loops – exit controlled by useruser

Different from fixed-count loopsDifferent from fixed-count loops

Actually “variable-condition” loopsActually “variable-condition” loops

User can be asked: “Do you want to continue?”User can be asked: “Do you want to continue?”

Or, entry of unusual data value will end loopOr, entry of unusual data value will end loop

Book example: Program 5-8 on page 189Book example: Program 5-8 on page 189

A grades program, where entry of a grade A grades program, where entry of a grade higher than 100 will exit the loophigher than 100 will exit the loop

Page 22: Control Structures RepetitionorIterationorLooping Part I.

Sentinel exampleSentinel example

grade = 0; total = 0;grade = 0; total = 0;cout << “To stop, type number higher than 100”;cout << “To stop, type number higher than 100”; while (grade < 100)while (grade < 100){{ total = total + grade;total = total + grade;

cout << “Enter a grade: “;cout << “Enter a grade: “;cin >> grade; cin >> grade;

}}cout << “\nThe total of the grades is “cout << “\nThe total of the grades is “

<< total << endl;<< total << endl;

Page 23: Control Structures RepetitionorIterationorLooping Part I.

Common ErrorsCommon Errors

Improper braces in nested structuresImproper braces in nested structures

Using Using == in place of in place of ====

!= versus == This changes the logic, be != versus == This changes the logic, be especially careful when used with especially careful when used with && or && or ||||

infinite loops: != versus && versus infinite loops: != versus && versus ||||

**


Recommended