Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Counter-Controlled Repetition: A Case Study in Algorithm Formulation, Slides of Programming for Engineers

A case study on counter-controlled repetition, a repetition structure in programming where the loop is repeated until a counter reaches a certain value. Examples in c++ and discusses the essentials of counter-controlled repetition, such as the need for a control variable, initialization, repetition condition, and increment. It also covers the use of assignment operators and break/continue statements within loops.

Typology: Slides

2011/2012

Uploaded on 07/25/2012

hun_i
hun_i 🇮🇳

3.7

(3)

61 documents

1 / 68

Toggle sidebar

Related documents


Partial preview of the text

Download Counter-Controlled Repetition: A Case Study in Algorithm Formulation and more Slides Programming for Engineers in PDF only on Docsity! Programming for Engineers II (EE112 )‏ Chapter 4&5 Control Statements docsity.com Chapter 4 - Control Structures Outline Introduction Algorithms Pseudocode Control Structures if Selection Structure if/else Selection Structure while Repetition Structure Formulating Algorithms: Case Study 1 (Counter- Controlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Assignment Operators Increment and Decrement Operators Essentials of Counter-Controlled Repetition for Repetition Structure Examples Using the for Structure docsity.com Pseudocode  Pseudocode  Artificial, informal language used to develop algorithms  Similar to everyday English  Not executed on computers  Used to think out program before coding  Easy to convert into C++ program  Only executable statements  No need to declare variables docsity.com Control Structures  Sequential execution  Statements executed in order  Transfer of control  Next statement executed not next one in sequence  3 control structures (Bohm and Jacopini)  Sequence structure  Programs executed sequentially by default  Selection structures  if, if/else, switch  Repetition structures  while, do/while, for docsity.com Repetition Statements in C++  C++ provides three types of repetition statements (also called looping statements or loops) that enable programs to perform statements repeatedly as long as a condition (called the loop-continuation condition) remains true.  The repetition statements are the while, do...while and for statements.  The while and for statements perform the action in their bodies zero or more times if the loop- continuation condition is initially false, the action will not execute.  The do...while statement performs the action in its body at least once. docsity.com if Selection Structure  Selection structure  Choose among alternative courses of action  Pseudocode example: If student’s grade is greater than or equal to 60 Print “Passed”  If the condition is true  Print statement executed, program continues to next statement  If the condition is false  Print statement ignored, program continues  Indenting makes programs easier to read  C++ ignores whitespace characters (tabs, spaces, etc.) docsity.com if Selection Structure  Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed";  Diamond symbol (decision symbol)  Indicates decision is to be made  Contains an expression that can be true or false  Test condition, follow path  if structure  Single-entry/single-exit docsity.com if single-selection statement activity diagram  Flowchart of pseudocode statement docsity.com true false print “Failed” print “Passed” grade >= 60 docsity.com if/else Selection Structure  Nested if/else structures  One inside another, test for multiple cases  Once condition met, other statements skipped if student’s grade is greater than or equal to 90 Print “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” docsity.com if/else Selection Structure  Example if ( grade >= 90 ) // 90 and above cout << "A"; else if ( grade >= 80 ) // 80-89 cout << "B"; else if ( grade >= 70 ) // 70-79 cout << "C"; else if ( grade >= 60 ) // 60-69 cout << "D"; else // less than 60 cout << "F"; docsity.com The while Repetition Structure  Flowchart of while loop product <= 100 product = 3 * product true false docsity.com Formulating Algorithms (Counter- Controlled Repetition)  Counter-controlled repetition  Loop repeated until counter reaches certain value  Definite repetition  Number of repetitions known  Example A 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. docsity.com Formulating Algorithms (Counter- Controlled Repetition)  Pseudocode for example: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average  Next: C++ code for this example docsity.com Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 docsity.com Formulating Algorithms (Sentinel-Controlled Repetition)  Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run  In the previous class average example, the problem statement specified the number of students, so the number of grades (10) was known in advance. docsity.com  In this example, no indication is given of how many grades the user will enter during the program's execution.  The program must process an arbitrary number of grades.  How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average? docsity.com Nested Control Structures  Problem statement 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".  Notice that  Program processes 10 results Fixed number, use counter-controlled loop  Two counters can be used One counts number that passed Another counts number that fail  Each test result is 1 or 2  If not 1, assume 2 docsity.com Nested Control Structures  Top level outline Analyze exam results and decide if tuition should be raised  First refinement Initialize variables Input the ten quiz grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised  Refine Initialize variables to Initialize passes to zero Initialize failures to zero Initialize student counter to one docsity.com Nested Control Structures  Refine Input the ten quiz grades and count passes and failures to While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes Else Add one to failures Add one to student counter docsity.com 1 // Fig. 2.11: fig02_11.cpp 2 // Analysis of examination results. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function main begins program execution 10 int main() 11 { 12 // initialize variables in declarations 13 int passes = 0; // number of passes 14 int failures = 0; // number of failures 15 int studentCounter = 1; // student counter 16 int result; // one exam result 17 18 // process 10 students using counter-controlled loop 19 while ( studentCounter <= 10 ) { 20 21 // prompt user for input and obtain value from user 22 cout << "Enter result (1 = pass, 2 = fail): "; 23 cin >> result; 24 docsity.com 25 // if result 1, increment passes; if/else nested in while 26 if ( result == 1 ) // if/else nested in while 27 passes = passes + 1; 28 29 else // if result not 1, increment failures 30 failures = failures + 1; 31 32 // increment studentCounter so loop eventually terminates 33 studentCounter = studentCounter + 1; 34 35 } // end while 36 37 // termination phase; display number of passes and failures 38 cout << "Passed " << passes << endl; 39 cout << "Failed " << failures << endl; 40 41 // if more than eight students passed, print "raise tuition" 42 if ( passes > 8 ) 43 cout << "Raise tuition " << endl; 44 45 return 0; // successful termination 46 47 } // end function main docsity.com Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Passed 6 Failed 4 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 2 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Enter result (1 = pass, 2 = fail): 1 Passed 9 Failed 1 Raise tuition docsity.com Increment and Decrement Operators  Increment operator (++)  Increment variable by one  c++  Same as c += 1  Decrement operator (--) similar  Decrement variable by one  c-- docsity.com Increment and Decrement Operators  Preincrement  Variable changed before used in expression  Operator before variable (++c or --c)  Postincrement  Incremented changed after expression  Operator after variable (c++, c--) docsity.com Increment and Decrement Operators  If c = 5, then  cout << ++c;  c is changed to 6, then printed out  cout << c++;  Prints out 5 (cout is executed before the increment.  c then becomes 6 docsity.com 5 5 6 5 6 6 docsity.com Essentials of Counter-Controlled Repetition  Counter-controlled repetition requires  Name of control variable/loop counter  Initial value of control variable  Condition to test for final value  Increment/decrement to modify control variable when looping docsity.com 1 2 // Counter-controlled repetition. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 int counter = 1; // initialization 12 13 while ( counter <= 10 ) { // repetition condition 14 cout << counter << endl; // display counter 15 ++counter; // increment 16 17 } // end while 18 19 return 0; // indicate successful termination 20 21 } // end function main docsity.com for Repetition Structure  General format when using for loops for ( initialization; LoopContinuationTest; increment ) statement  Example for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl;  Prints integers from one to ten No semicolon after last statement docsity.com 1 // Fig. 2.17: fig02_17.cpp 2 // Counter-controlled repetition with the for structure. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 // Initialization, repetition condition and incrementing 12 // are all included in the for structure header. 13 14 for ( int counter = 1; counter <= 10; counter++ ) 15 cout << counter << endl; 16 17 return 0; // indicate successful termination 18 19 } // end function main docsity.com 1 2 3 4 5 6 7 8 9 10 docsity.com int _tmain() { int aCounter=0,bCounter=0,cCounter=0,dCounter=0,fCounter=0; char grade; for (int i= 1; i<=10;i++) { cout<<"Enter Grade"; cin>>grade; switch(grade) { case 'a': aCounter++; break; case 'b': bCounter++; break; case 'c': cCounter++; break; docsity.com case 'd': dCounter++; break; case 'f': fCounter++; break; default: cout<<"Invalid Grade"; break; } } cout<< "A = " << aCounter<<endl; cout<< "B = " << bCounter<<endl; cout<< "C = " << cCounter<<endl; cout<< "D = " << dCounter<<endl; cout<< "F = " << fCounter<<endl; return 0; } docsity.com do/while Repetition Structure  Similar to while structure  Makes loop continuation test at end, not beginning  Loop body executes at least once  Format do { statement } while ( condition ); docsity.com 1 2 3 4 5 6 7 8 9 10 docsity.com break and continue Statements  break statement  Immediate exit from while, for, do/while, switch  Program continues with first statement after structure  Common uses  Escape early from a loop  Skip the remainder of switch docsity.com 1 // Fig. 2.26: fig02_26.cpp 2 // Using the break statement in a for structure. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 12 int x; // x declared here so it can be used after the loop 13 14 // loop 10 times 15 for ( x = 1; x <= 10; x++ ) { 16 17 // if x is 5, terminate loop 18 if ( x == 5 ) 19 break; // break loop only if x is 5 20 21 cout << x << " "; // display value of x 22 23 } // end for 24 25 cout << "\nBroke out of loop when x became " << x << endl; docsity.com 1 // Fig. 2.27: fig02_27.cpp 2 // Using the continue statement in a for structure. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function main begins program execution 9 int main() 10 { 11 // loop 10 times 12 for ( int x = 1; x <= 10; x++ ) { 13 14 // if x is 5, continue with next iteration of loop 15 if ( x == 5 ) 16 continue; // skip remaining code in loop body 17 18 cout << x << " "; // display value of x 19 20 } // end for structure 21 22 cout << "\nUsed continue to skip printing the value 5" 23 << endl; 24 25 return 0; // indicate successful termination docsity.com 26 27 } // end function main 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5 docsity.com Logical Operators  Used as conditions in loops, if statements  && (logical AND)  true if both conditions are true if ( gender == 1 && age >= 65 ) ++seniorFemales;  || (logical OR)  true if either of condition is true if ( semesterAverage >= 90 || finalExam >= 90 ) cout << "Student grade is A" << endl; docsity.com
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved