1 / 56

Chapter 5: Loops

Chapter 5: Loops. Outline. Increment and Decrement while loop do-while loop for loop. Slide 5- 2. The Increment and Decrement Operators. ++ is the increment operator. It adds one to a variable. val ++; is the same as val = val + 1;

colt-hewitt
Download Presentation

Chapter 5: Loops

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5: Loops

  2. Outline • Increment and Decrement • while loop • do-while loop • for loop Slide 5- 2

  3. The Increment and Decrement Operators • ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; • ++ can be used before (prefix) or after (postfix) a variable: ++val; val++; Slide 5- 3

  4. The Increment and Decrement Operators • -- is the decrement operator. It subtracts one from a variable. val--; is the same as val = val - 1; • -- can be also used before (prefix) or after (postfix) a variable: --val; val--; Slide 5- 4

  5. Prefix vs. Postfix • ++ and -- operators can be used in complex statements and expressions • In prefix mode (++val, --val) the operator increments or decrements, then returns the value of the variable • In postfix mode (val++, val--) the operator returns the value of the variable, then increments or decrements Slide 5- 7

  6. Prefix vs. Postfix - Examples int num, val = 12; cout << val++; // displays 12, // val is now 13; cout << ++val; // sets val to 14, // then displays 14 num = --val; // sets val to 13, // stores 13 in num num = val--; // stores 13 in num, // sets val to 12 Slide 5- 8

  7. Outline • Increment and Decrement • while loop • do-while loop • for loop Slide 5- 9

  8. Introduction to Loops: The while Loop The general form of the while statement is: while (expression) statement; OR while (expression) { statement1; statement2; }

  9. The process used by the computer in • evaluating a while statement is: • 1. test the expression • 2. if the expression has a nonzero (true) value • a. execute the statement following the parentheses • b. go back to step 1 • else • exit the while statement

  10. The Logic of a while Loop

  11. while is a Pretest Loop • expression is evaluated before the loop executes. The following loop will never execute: int number = 6;while (number <= 5){ cout << "Hello\n"; number++;}

  12. An Infinite Loop int number = 1;while (number <= 5){ cout << "Hello\n";}

  13. Watch Out for Infinite Loops • The loop must contain code to make expression become false • Otherwise, the loop will have no way of stopping • Such a loop is called an infinite loop, because it will repeat an infinite number of times

  14. Example: void main ( void ) { int count = 1; while(count <= 10) { cout << count << " "; count = count + 1; //count++; //count += 1; } } Output: 1 2 3 4 5 6 7 8 9 10

  15. What is the output from the next segment of code? void main ( void ) { int i; i = 10; while(i >= 1 ) { cout << i << " "; i = i - 1; //count--; count -= 1; } } Output: 10 9 8 7 6 5 4 3 2 1

  16. The Power of the while statement • To illustrate the power of the while statement, consider the task of printing a table of numbers from 1 to 10 with their squares and cubes. This can be done with a simple while statement: void main ( void ) { intnum = 1; //Display Heading cout << "Number Square Cube\n" << "----------- --------- -------\n"; while (num < 11) { cout << num << " " << pow(num, 2) << " " << pow(num, 3) << " "<< endl; num = num + 1; } }

  17. The Power of the while statement Note: The expression (num <= 10) could have been used in place of (num < 11). Number Square Cube ------------ ---------- -- ----------- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 If we wanted to use the previous program to produce a table of 1000 numbers, all we have to do is change the expression in the while statement from (num < 11) to (num < 1001).

  18. cin within a while loop • Combining interactive data entry with the repetition capabilities of the • while statement produces very adaptable and powerful programs. To • understand the concept involved consider the following program which • asks the user to enter a user specified amount of numbers and then • displays the total of those numbers. • Prompt user for how many numbers to be entered. • Prompt user for the numbers. • Add each number to a variable named total which accumulates the • total of all numbers entered. • Initialize total to zero before the loop begins. • Accumulate the numbers (total = total + number)

  19. int main ( void ) { int numbers_entered = 0, total = 0, number = 0; int counter = 1; cout << "How many numbers do you wanted added?" << endl; cin >> numbers_entered; while (counter <= numbers_entered) { cout << "Please enter a number: "; cin >> number; total = total + number; //total += number; counter = counter + 1; //counter++; counter += 1; } cout << "\nThe total of the numbers entered is " << total; return 0; }

  20. Outline • Increment and Decrement • while loop • do-while loop • for loop Slide 5- 28

  21. The do-while Loop The do statement allows us to execute some statements before an expression is evaluated. The general form of the do statement is: do statement; while(expression); //don’t forget the ; OR do { statement1; statement2; }while(expression); //don’t forget the ;

  22. The Logic of a do-while Loop

  23. do-while Example int x = 1;do{cout << x << endl;} while(x < 0); Although the test expression is false, this loop will execute one time because do-while is a posttest loop.

  24. Validity Checks (Data Validation) The do statement is particularly useful in filtering user-entered input and providing data validity checks. For example, assume that an operator is required to enter a valid customer identification number between the numbers 100 and 1999. A number outside this range is to be rejected and a new request for a valid number made. The following section of code provides the necessary data filter to verify the entry of a valid identification number. do { cout << "\nEnter an identification number: "; cin >> ident_number; }while(ident_number < 100 || ident_number > 1999);

  25. Here, a request for an identification number is repeated until a valid number is entered. This section of code is "bare bones" in that it neither alerts the operator to the cause of the new request for data nor allows premature exit from the loop if a valid identification number cannot be found. An alternative that removes the first drawback is do { cout << "\nEnter an identification number: "; cin >> ident_number; if (ident_number < 100 || ident_number > 1999) { cout << "\nAn invalid number was just entered"; cout << "\nPlease check the ID number and re-enter."; } }while(ident_number < 100 || ident_number > 1999);

  26. Outline • Increment and Decrement • while loop • do-while loop • for loop Slide 5- 38

  27. Loop • There are two types of the loop: • Conditional loop: executes as long as a particular condition exists (you don’t know how many times of the loop will continue). • Count-controlled loop: when you know the exact number of iterations that a loop must perform.

  28. The for Loop • Useful for counter-controlled loop • General Format:for(initialization; test; update) statement; // or block in { } • No semicolon after 3rd expression or after the )

  29. The for Loop • General Format:for(initialization; test; update) statement; // or block in { } • for Loop - Mechanics • Performinitialization • Evaluate test expression • If true, execute statement • If false, terminate loop execution • Execute update, then re-evaluate test expression

  30. A Closer Look at the Previous Example

  31. Examples • While intcount = 1; while (count <= 10) { cout << count ; count++; //or count += 1; or count = count + 1; } • Same loop as above but coded using the for statement: for (int count = 1; count <= 10; count++) cout << count;

  32. Example • What is produced from the following segments of programs? constint MAXNUMS = 10; int main ( void ) { intnum; cout << "Number Square Cube\n" << "------- -------- ------\n" << endl; for (num = 1; num <= MAXNUMS; num++) cout << num << " " << num * num << " " << num * num * num << endl; return 0; }

  33. Example - Output Number Square Cube ----------- --------- -------- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

  34. for loop – pretest loop • When to Use the for Loop? • In any situation that clearly requires • an initialization • a false condition to stop the loop • an update to occur at the end of each iteration • The for loop tests its test expression before each iteration, so it is a pretest loop. • The following loop will never iterate:for (count = 11; count <= 10; count++) cout << "Hello" << endl;

  35. for Loop - Modifications • You can omit the initialization expression if it has already been done: int sum = 0, num = 1; for (; num <= 10; num++) sum += num;

  36. for Loop - Modifications • You can declare variables in the initialization expression: int sum = 0; for (int num = 0; num <= 10; num++) sum += num; The scope of the variable num is the for loop.

  37. Keeping a Running Total • running total: accumulated sum of numbers from each repetition of loop • accumulator: variable that holds running total intsum=0, num=1; // sum is the accumulator while (num <= 10) { sum += num; num++; } cout << "Sum of numbers 1 – 10 is" << sum << endl;

  38. int main ( void ) { inttotal_numbers, number, total = 0 ; // total is the accumulator cout << "How many numbers would you like to total?" << endl; cin >> total_numbers; for(int counter = 0; counter < total_numbers; counter++) { cout << "Please enter a number: " << endl; cin >> number; total = total + number; //or total += number; } cout << "\nThe total of the numbers you entered is: "<< total; cout <<"\nThe average of the numbers you entered is: " << total/double (total_numbers); return 0; }

  39. Output How many numbers would you like to total? 4 Please enter a number: 56 Please enter a number: 45 Please enter a number: 85 Please enter a number: 43 The total of the numbers you entered is: 229 The average of the numbers you entered is: 57.25

  40. Sentinels • sentinel: value in a list of values that indicates end of data • Special value that cannot be confused with a valid value, e.g., -999 for a test score • Used to terminate input when user may not know how many values will be entered

  41. Outline • Increment and Decrement • while loop • do-while loop • for loop • nested for loop Slide 5- 63

  42. Nested Loops • A nested loop is a loop inside the body of another loop • Inner (inside), outer (outside) loops: for (row=1; row<=3; row++) //outer for (col=1; col<=3; col++)//inner cout << row * col << endl;

  43. Example for (inti = 1; i <= 5; i++) // start outer loop { cout << "\n i is now " << i << endl; for (int j = 1; j <= 4; j++) // start inner loop cout << " j = " << j; // end of inner loop } // end of outer loop The first loop, controlled by the value of i, is called the outer loop. The second loop, controlled by the value of j, is called the inner loop. For each single trip through the outer loop, the inner loop runs through its entire sequence. Thus, each time the i counter increases by 1, the inner for loop executes completely.

  44. Output • Below is the output from the previous nested loop: i is now 1 j = 1 j = 2 j = 3 j = 4 i is now 2 j = 1 j = 2 j = 3 j = 4 i is now 3 j = 1 j = 2 j = 3 j = 4 i is now 4 j = 1 j = 2 j = 3 j = 4 i is now 5 j = 1 j = 2 j = 3 j = 4

More Related