Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.

Similar presentations


Presentation on theme: "Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition."— Presentation transcript:

1 Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition

2 2 Objectives You should be able to describe: Basic Loop Structures while Loops Interactive while Loops for Loops Loop Programming Techniques Nested Loops do-while Loops

3 Program Development and Design Using C++, Third Edition 3 Basic Loop Structures Loop: Section of code that is repeated Iteration: A repetition of loop  Pass through loop Repeating instructions typed only once  Inform program to repeat execution Three forms of repetition statements:  while  for  do-while

4 Program Development and Design Using C++, Third Edition 4 while Loops Constructed using while statement Syntax: expression is the condition tested  Determines if statement is executed Statement executed repeatedly as long as expression evaluates to nonzero value Infinite loop: Loop that never ends

5 Program Development and Design Using C++, Third Edition 5 while repetition structure Repetition structure  Action repeated while some condition remains true (i.e. evaluates to a non-zero value  Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list  while loop repeated until condition becomes false Example int product = 2; while ( product <= 10 ) product = 2 * product;

6 Program Development and Design Using C++, Third Edition 6 Flowchart of while loop product <= 10 product = 2 * product true false

7 Program Development and Design Using C++, Third Edition 7 Counter-Controlled Repetition Counter-controlled repetition  Loop repeated until counter reaches certain value Definite repetition  Number of repetitions known Example Print a line of 5 characters

8 Program Development and Design Using C++, Third Edition 8 #include using namespace std; void main() { int counter; char ch; cout << "Please enter a character: "; cin >> ch; counter=1; while (counter <= 5) { cout << ch; counter++; } cout << endl; } Displaying 5 characters (version 1)

9 Program Development and Design Using C++, Third Edition 9 #include using namespace std; void main() { int counter; char ch; cout << "Please enter a character: "; cin >> ch; counter=5; while (counter >= 1) { cout << ch; counter--; } cout << endl; } Displaying 5 characters (version 2)

10 Program Development and Design Using C++, Third Edition 10 Counter-Controlled Repetition (continued) Example Output the multiplication table for a user-defined number. E.g. if user enters 5, the program should output: 1*5=5 2*5=10 3*5=15 10*5=50

11 Program Development and Design Using C++, Third Edition 11 #include using namespace std; void main() { const int limit = 10; int number, count = 1; cout << "Multiplication Table Program"; cout << endl << endl; cout << "Please enter an integer number: "; cin >> number; while (count <= limit) { cout<<count<<" * "<<number<<"="<<count*number<<endl; count++; // increment the counter } The Multiplication table program

12 Program Development and Design Using C++, Third Edition 12 Counter-Controlled Repetition (continued) 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.

13 Program Development and Design Using C++, Third Edition 13 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

14 Program Development and Design Using C++, Third Edition 14 The Class Average program #include using namespace std; void main() { int total; // sum of grades input by user int gradeCounter; // number of grades entered so far int grade; // grade value int average; // average of grades total = 0; // initialize total gradeCounter = 1; // initialize loop counter while ( gradeCounter <= 10 ) { cout << "Enter grade: "; // prompt for input cin >> grade; // read grade from user total = total + grade; // add grade to total gradeCounter++; } average = total / 10; cout << "Class average is " << average << endl; } //end function main

15 Program Development and Design Using C++, Third Edition 15 Suppose problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run  Unknown number of students  How will program know when to end? Sentinel value  Indicates “end of data entry”  Loop ends when sentinel input  Sentinel chosen so it cannot be confused with regular input -1 in this case Sentinel-Controlled Repetition

16 Program Development and Design Using C++, Third Edition 16 Class Average Program with sentinel #include using namespace std; void main() { int total; // sum of grades int gradeCounter; // number of grades entered int grade; // grade value double average; // initialization phase total = 0; // initialize total gradeCounter = 0; // initialize loop counter cout << "Enter grade, -1 to end: "; //prompt for input cin >> grade;

17 Program Development and Design Using C++, Third Edition 17 while ( grade != -1 ) //loop until sentinel { total = total + grade; //add grade to total gradeCounter++; //increment counter cout << "Enter grade, -1 to end: "; cin >> grade; // read next grade } // end while //if user entered at least one grade... if ( gradeCounter != 0 ) { average = (double)( total ) / gradeCounter; cout<<"The class average is: " <<average<<endl; } else cout<<"No grades were entered! " <<endl; }//end main

18 Program Development and Design Using C++, Third Edition 18 for Loops General format when using for loops for ( initialization; LoopContinuationTest; increment ) statement Example for( counter = 1; counter <= 10; counter++ ) cout << counter << endl;  Prints integers from one to ten

19 Program Development and Design Using C++, Third Edition 19 while equivalent of for Any for loop can be rewritten as a while loop. while loop i=0; while(i<100) { cout<<"A"; i++; } for loop for(i=0; i<100; i++) cout<<"A";

20 Program Development and Design Using C++, Third Edition 20 while equivalent of for In general: Let e1, e2 and e3 stand for any expression and s stands for any statement): for(e1;e2;e3) s This loop can be rewritten as a while loop like this: e1; while(e2) { s; e3; }

21 Program Development and Design Using C++, Third Edition 21 Example of for loop #include using namespace std; //print the sum of integers from 1 to 100 inclusive void main() { int number, sum = 0; // initialize sum for ( number = 1; number <= 100; number++ ) sum =sum+number; // add number to sum cout << "Sum is " << sum << endl; } // end function main

22 Program Development and Design Using C++, Third Edition 22 Example of for loop (2) #include using namespace std; //print the sum of EVEN integers from 1 to 100 inclusive void main() { int number, sum = 0; // initialize sum for ( number = 2 ; number <= 100; number+=2 ) sum =sum+number; // add number to sum cout << "Sum is " << sum << endl; } // end function main

23 Program Development and Design Using C++, Third Edition 23 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 ); true false action(s) condition

24 Program Development and Design Using C++, Third Edition 24 Example program for do-while #include using namespace std; void main() { int counter = 1; do { cout << counter << " "; counter++; } while ( counter <= 10 ); cout << endl; }

25 Program Development and Design Using C++, Third Edition 25 Validity Checks do statement useful in filtering user-entered input and providing data validation checks do { cout << "Enter a number between 1 and 10: "; cin >> firstNum; } while (firstNum 10);

26 Program Development and Design Using C++, Third Edition 26 Example of input validation program #include using namespace std; void main() { int firstNum; int secondNum; cout << "Enter the first number: "; cin >> firstNum; do { cout << "Enter the second number(not zero): "; cin >> secondNum; } while (secondNum==0); cout <<"resulting division:"<<firstNum / secondNum; cout << endl; }

27 Program Development and Design Using C++, Third Edition 27 Same example using while #include using namespace std; void main() { int firstNum; int secondNum=0; cout << "Enter the first number: "; cin >> firstNum; while (secondNum == 0) { cout << "Enter the second number(not zero): "; cin >> secondNum; } cout <<"resulting division: "<<firstNum / secondNum; cout << endl; }

28 Program Development and Design Using C++, Third Edition 28 Nested Loops Nested loops: Loop contained within another loop  Inner and outer loops  All statements in inner loop contained within boundaries of outer loop  Use different variables to control each loop

29 Program Development and Design Using C++, Third Edition 29 Nested Loop example code int counter1 = 1, counter2; while (counter1 <=10) { cout << "Counter 1: " <<counter1<<endl; counter2 = 1; while (counter2 <= 10) { cout << " Counter 2: "<< counter2<<endl; counter2++; } counter1++; }

30 Program Development and Design Using C++, Third Edition 30 Same example using nested for -loops int counter1, counter2; for (counter1=1; counter1<=10;counter1++) { cout << "Counter 1: " <<counter1<<endl; for (counter2 = 1;counter2 <= 10; counter2++) cout << " Counter 2: "<< counter2<<endl; }

31 Program Development and Design Using C++, Third Edition 31 Common Programming Errors Inadvertently using assignment operator = instead of equality operator == in tested expression Repetition statements should not use equality operator == when testing floating-point or double-precision operands Placing semicolon at end of for’s parentheses, which frequently produces do- nothing loop

32 Program Development and Design Using C++, Third Edition 32 Common Programming Errors (continued) Using commas to separate the items in for statement instead of the required semicolons Omitting final semicolon from do statement

33 Program Development and Design Using C++, Third Edition 33 Exercises Q1: Read 5 numbers (positive or negative) and print the sum of positives and the sums of negatives. E.g. Numbers entered: 5 10 -3 1 -4 Output: positive sum = 16 negative sum = -7

34 Program Development and Design Using C++, Third Edition 34 Q2: Read grades (A, B, C, D and F) and count the number of A, B, C, D and F grades entered. The input should be terminated by the sentinel grade ‘X’. Your program should allow re-entering of invalid input (i.e. invalid letter grade). Example run: Please enter grade (A, B, C, D or F, X to finish):B Please enter grade (A, B, C, D or F, X to finish):A Please enter grade (A, B, C, D or F, X to finish):b Please enter grade (A, B, C, D or F, X to finish):X Totals for each letter grade: A:1 B:2 C:0 D:0 F:0

35 Exercises Pg. 272: ex. 5, 6, 7, 8 NEW EXERCISES:  Download the file Additional Exercises on Loops (Exercise Sheet 2) from web site and do all exercises.  Textbook: pg. 276: 1,2,3  Textbook: pg. 279: 1,2


Download ppt "Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition."

Similar presentations


Ads by Google