control structures repetition or iteration or looping part ii
TRANSCRIPT
![Page 1: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/1.jpg)
Control StructuresControl Structures
Repetition
or
Iteration
or
Looping
Part II
![Page 2: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/2.jpg)
Loop ControlsLoop Controls
Counter-controlled loopsrepeat a specific number of times (You can calculate the number of iterations.) Use a for loop
Event-controlled loopsrepeats until something happens in the loop body to change the evaluation of the expression
![Page 3: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/3.jpg)
SentinelsSentinels
These are used in event-controlled loops. The loop can be executed any number of times. It stops only when a specific event occurs.
A sentinal is a unique value that can be used to signal an event. This value cannot be valid for normal processing, I.e., -1 may be valid for degrees farenheit, but not for test scores.
*
Test Scores
67, 89, 94, 82, -1
![Page 4: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/4.jpg)
Running TotalsRunning Totals
count =1 //read or assigntotal = 0;while (count <=4){
}
cout << “\nEnter a number: “;cin >> num;total = total + num;cout “The total is now “ << total << endl;count++;
*
![Page 5: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/5.jpg)
total = 0;num = 0;while ( num != 999num != 999 ){
total = total + num;cout “\nThe total is now “ << total;cout << “Enter a number: “;cin >> num; // user causes the event
}
Sentinal Value – An input eventSentinal Value – An input event999 must not be valid in this context
![Page 6: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/6.jpg)
flag = 1;flag = 1;while ( flagflag ){
total = total + num;cout “\nThe total is now “ << total;cout << “Enter a number: “;cin >> num;if( num > 999)
flag = 0;flag = 0;}
Flag ExampleFlag Example
A flag is any variable whose value indicates program status
![Page 7: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/7.jpg)
while ( count <=4count <=4 ){
total = total + num;cout “\nThe total is now “ << total;cout << “Enter a number: “;cin >> num;count++;count++;
}
Sentinel ExampleSentinel Examplecout << “\nEnter a number: “;cin >> num; }primary read
num != 999
* * * *
![Page 8: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/8.jpg)
Average – again, using Average – again, using whilewhileint num, count = 1;float average, total = 0.0;cout << "Enter a number: "; // priming readcin >> num;
while (count <= 4){
total = total + num; // accumulating a totalcout << “The total is “ << total << ‘\n’;
cout << "Enter a number: ";cin >> num;count++; // how many times ?
} // Can you see the weakness in this program?count--; // WHY?average = total / count;cout << "\nThe average is " << average << '\n';
![Page 9: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/9.jpg)
Average – again, using Average – again, using forforint num, count;float average, total = 0.0;for (count = 1; count <= 4; count++){
cout << "Enter a number: ";cin >> num;total = total + num; // accumulating a total cout << “The total is ” << total << ‘\n’;
} // how many times ?count--; // WHY?average = total / count;cout << "\nThe average is " << average << '\n';
![Page 10: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/10.jpg)
breakbreak and and continuecontinue StatementsStatements
Interrupt the normal flow of control.
break causes an exit from innermost enclosing loop or switch statement.
continue cause current iteration of a loop to stop and the next iteration to begin immediately.
continuecontinue may only be used in may only be used in whilewhile, , forfor, , and and dodo loops. loops.
* * *
![Page 11: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/11.jpg)
TheThe break break Statement Statement
int j =50;1 while (j < 80)2 {3 j += 10;4 if (j == 70)5 break;6 cout << “j is “ << j<< ‘\n’;
7 }
8 cout << “We are out of the loop.\n”;
![Page 12: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/12.jpg)
TheThe break break Statement Statement
Outputj is 60We are out of the loop.
Sequence of execution:
1 2 3 4 6 7 1 2 3 4 5 8
![Page 13: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/13.jpg)
TheThe continue continue Statement Statement
int j =50;1 while (j < 80)2 {3 j += 10;4 if (j == 70)5 continuecontinue;6 cout << “j is “ << j<< ‘\n’;
7 }
8 cout << “We are out of the loop.\n”;
![Page 14: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/14.jpg)
TheThe continue continue Statement Statement
Outputj is 60j is 80We are out of the loop.
Sequence of execution:
1 2 3 4 6 7 1 2 3 4 5
1 2 3 4 6 7 1 8
![Page 15: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/15.jpg)
break break andand continue continue
while ( - - - ){
statement-1;if( - - - )
continuecontinuestatement-2;
}statement-3;
while ( - - - ){
statement-1;if( - - - )
breakbreakstatement-2;
}statement-3;
*
![Page 16: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/16.jpg)
The The dodo Statement StatementVariant of the Variant of the whilewhile statement statement
Syntax
dodostatement
whilewhile (expression);next statement
![Page 17: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/17.jpg)
The The dodo Statement Statement
Exit the Exit the dodo
0 0 ororFalseFalse
loop Test theexpression
statements to execute
1 1 ororTrueTrue
Always executes at least once
![Page 18: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/18.jpg)
Example:
dodo{
cout << “Enter your age: “;cin >> age;if (age <=0)
cout << “Invalid age.\n”;else
cout << "DO SOMETHING\n";
} while (age <=0)while (age <=0);
do Statmentsdo Statments
![Page 19: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/19.jpg)
cout << "Enter your age: ";cin >> age;
whilewhile (age <= 0){ if (age <=0) {
cout << "Invalid age.\n"; cout << "Enter your age: "; cin >> age;
} else
cout << "DO SOMETHING\n";}
do do vs. vs. whilewhile
![Page 20: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/20.jpg)
sum = 0;count = 1;count = 1;
dodo{
I/OI/Osum += count; count++;
} while (count <=n);
sum = 0;count = 1;count = 1;I/O // priming readI/O // priming readwhile (count <=n){
sum += count;count++; I/OI/O
}
do do vs. vs. whilewhile
Make sure that count and sum are correct
![Page 21: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/21.jpg)
do do while while for for
sum = 0;cnt = 1;cnt = 1;dodo{
sum += cnt;cnt++;
} while (cnt <=n);
sum = 0;cnt = 1;cnt = 1;while (cnt <=n){
sum += cnt;cnt++;
}
sum = 0;for (cnt = 1cnt = 1; cnt <= n; cnt++)
sum += cnt;
// what if…
// cin >> n;
// read a zero?
![Page 22: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/22.jpg)
Guidelines for choosing:Guidelines for choosing:
If simple count-controlled, use a for.
If event-controlled and body is executed at least once, use do.
If event-controlled and nothing is known about the first execution, use while.
When in doubt use while.
![Page 23: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/23.jpg)
Validity CheckingValidity Checking
Validity checking or data validation
is a way of notifying the user of
invalid data. You should validate
every input value for which any
restrictions apply.
*
![Page 24: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/24.jpg)
A Sample ProblemA Sample Problem
Write a program that accepts a user
determined number of experiments
with a user determined number of
scores for each experiment. It displays
the average of the scores for each
experiment.
![Page 25: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/25.jpg)
How many experiments are there? 2How many scores are there? 3 Enter the scores for experiment 1:Enter result of test 1 : 98Enter result of test 1 : 56Enter result of test 1 : 34The average for experiment 1 is 63
How many scores are there? 4 Enter the scores for experiment 2:Enter result of test 2 : 21Enter result of test 2 : 32Enter result of test 2 : 16Enter result of test 2 : 29The average for experiment 2 is 25Press any key to continue
![Page 26: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/26.jpg)
Plan for Sample ProgramPlan for Sample Program
read # experimentsread # experimentsforfor
read # scoresread # scoresforfor
read individual scoresread individual scoresincrement totalincrement total
average scoresaverage scoresdisplay averagedisplay average
* * ** * *
![Page 27: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/27.jpg)
{ int exper, test, howmany1, howmany2;double total, score, avg;
cout << "How many experiments are there? "; cin >> howmany1;
for (exper =1; exper<=howmany1; exper=exper +1)for (exper =1; exper<=howmany1; exper=exper +1) {{ cout << "How many scores are there? ";cout << "How many scores are there? "; cin >> howmany2;cin >> howmany2; cout << "\tEnter the scores for experiment "cout << "\tEnter the scores for experiment "
<< exper <<": \n"; total = 0;<< exper <<": \n"; total = 0;
for (test = 1; test <=howmany2; test = test +1)for (test = 1; test <=howmany2; test = test +1) {{ cout << "Enter result of test " << test <<" : ";cout << "Enter result of test " << test <<" : "; cin >> score;cin >> score; total = total + score; total = total + score; }}
avg = total/(test-1);avg = total/(test-1); cout << "The average for experiment " << exper cout << "The average for experiment " << exper << " is " << setprecision(2) << avg << "\n\n";<< " is " << setprecision(2) << avg << "\n\n";
}} }
![Page 28: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/28.jpg)
Reverse_digits exampleReverse_digits example
Write a program to reverse the digits of a positive integer. For example if the number is 8735, the displayed number should be 5378.
*
Hint: Use a do statement and continually strip off and display the units digit of the number (number % 10). After the units digit is displayed, dividing the number by 10 strips off the current units digit and sets up number for the next iteration. Thus, (8735 % 10) is 5 and (8735 / 10) is 873. The do statement executes until number is zero.
![Page 29: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/29.jpg)
Palindrome ExamplePalindrome Example
A palindrome is a phrase (number or text) that reads the same backwards as forwards. For example, the following are palindromes:
12321, madam i'm adam.
Write a program that reads a five-digit integer and determines whether or not it is a palindrome. Ask the user if another possible palindrome is to be entered.
![Page 30: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/30.jpg)
The EndThe End The End
The EndThe EndThe EndThe End
The EndThe End
the endthe end
![Page 31: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/31.jpg)
Common ErrorsCommon Errors
UsingUsing == in place ofin place of == ==
Placing aPlacing a ;; after the after the forfor’s parentheses’s parenthesesor after a while condition – before the or after a while condition – before the loop statements.loop statements.
Using aUsing a ,, to separate items in ato separate items in a for for expression - you need aexpression - you need a ;;
Omitting the finalOmitting the final ;; in the in the dodo statement statement
![Page 32: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/32.jpg)
Common ErrorsCommon Errors
!=!= versus versus ==== This changes the logic, be This changes the logic, be especially careful when used with especially careful when used with &&&& or or ||||
( ) ( ) &&&& ( ) ( ) &&&& ( ) ( )versusversus
( ) ( ) |||| ( ) ( ) |||| ( ) ( ) }}note thisnote this
![Page 33: Control Structures Repetition or Iteration or Looping Part II](https://reader035.vdocuments.us/reader035/viewer/2022070401/56649f205503460f94c3850c/html5/thumbnails/33.jpg)
DebuggingDebugging
Syntax errors vs. Logic errorSyntax errors vs. Logic error
Prevention - plan first!Prevention - plan first!Valuation tables: expected outputValuation tables: expected outputDisplay intermediate valuesDisplay intermediate values
C++ DebuggerC++ Debugger
**