control structures repetition or iteration or looping part ii
Post on 04-Jan-2016
219 Views
Preview:
TRANSCRIPT
Control StructuresControl Structures
Repetition
or
Iteration
or
Looping
Part II
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
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
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++;
*
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
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
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
* * * *
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';
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';
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.
* * *
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”;
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
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”;
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
break break andand continue continue
while ( - - - ){
statement-1;if( - - - )
continuecontinuestatement-2;
}statement-3;
while ( - - - ){
statement-1;if( - - - )
breakbreakstatement-2;
}statement-3;
*
The The dodo Statement StatementVariant of the Variant of the whilewhile statement statement
Syntax
dodostatement
whilewhile (expression);next statement
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
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
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
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
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?
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.
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.
*
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.
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
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
* * ** * *
{ 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";
}} }
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.
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.
The EndThe End The End
The EndThe EndThe EndThe End
The EndThe End
the endthe end
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
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
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
**
top related