Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop.

Similar presentations


Presentation on theme: "Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop."— Presentation transcript:

1 Chapter 5: Loops

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

3 Slide 5- 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++;

4 Slide 5- 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--;

5 Slide 5- 5 (Program Continues)

6 Slide 5- 6

7 Slide 5- 7 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

8 Slide 5- 8 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

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

10 Slide 5- 10 Introduction to Loops: The while Loop Loop: a control structure that causes a statement or statements to repeat General format of the while loop: while (expression) statement; statement; can also be a block of statements enclosed in { }

11 Slide 5- 11 The general form of the while statement is: while (expression) statement; OR while (expression) { statement1; statement2; } Introduction to Loops: The while Loop

12 Slide 5- 12

13 Slide 5- 13 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

14 Slide 5- 14 while Loop – How It Works while (expression) statement; expression is evaluated – if true, then statement is executed, and expression is evaluated again – if false, then the loop is finished and program statements following statement execute

15 Slide 5- 15 The Logic of a while Loop

16 Slide 5- 16

17 Slide 5- 17 How the Loop in Lines 9 through 13 Works

18 Slide 5- 18 Flowchart of the Loop

19 Slide 5- 19 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++; }

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

21 Slide 5- 21 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

22 Slide 5- 22 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

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

24 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 ) { int num = 1; //Display Heading cout << "Number Square Cube\n" << "----------- --------- -------\n"; while (num < 11) { cout << num << " " << pow(num, 2) << " " << pow(num, 3) << " "<< endl; num = num + 1; } }

25 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).

26 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)

27 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; }

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

29 Slide 5- 29 The do-while Loop do-while : a posttest loop – execute the loop, then test the expression General Format: do statement; // or block in { } while (expression); Note that a semicolon is required after (expression)

30 Slide 5- 30 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 ; The do-while Loop

31 Slide 5- 31 The Logic of a do - while Loop

32 Slide 5- 32 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.

33 Slide 5- 33 do-while Loop Notes Loop always executes at least once Execution continues as long as expression is true, stops repetition when expression becomes false Useful in menu-driven programs to bring user back to menu to make another choice (see Program in the next slide)

34

35 Slide 5- 35

36 Slide 5- 36 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 1999);

37 Slide 5- 37 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 1999) { cout << "\nAn invalid number was just entered"; cout << "\nPlease check the ID number and re-enter."; } }while(ident_number 1999);

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

39 Slide 5- 39 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.

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

41 Slide 5- 41 The for Loop General Format: for(initialization; test; update) statement; // or block in { } for Loop - Mechanics 1)Perform initialization 2)Evaluate test expression If true, execute statement If false, terminate loop execution 3)Execute update, then re-evaluate test expression

42 Slide 5- 42 for Loop - Example int count; for (count = 1; count <= 5; count++) cout << "Hello" << endl;

43 Slide 5- 43 A Closer Look at the Previous Example

44 Slide 5- 44 Flowchart for the Previous Example

45 while initializing statements; while (expression) { loop statements;. expression-altering statements; }

46 Examples While int count = 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;

47 Excercise While int count = 2; while(count <= 20) { cout << count ; count = count + 2; //or count += 2; } Same loop as above but coded using the for statement: for (int count = 2; count <= 20; count += 2) cout << count;

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

49 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

50 Slide 5- 50 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;

51 Slide 5- 51 for Loop - Modifications You can have multiple statements in the initialization expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Initialization Expression

52 Slide 5- 52 for Loop - Modifications You can also have multiple statements in the update expression. Separate the statements with a comma: int x, y; for (x=1, y=1; x <= 5; x++, y++) { cout << x << " plus " << y << " equals " << (x+y) << endl; } Update Expression

53 Slide 5- 53 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;

54 Slide 5- 54 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.

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

56 int main ( void ) { int total_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; }

57 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

58 Slide 5- 58 (Program Continues)

59 Slide 5- 59

60 Slide 5- 60 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

61 Slide 5- 61

62 Slide 5- 62

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

64 Slide 5- 64 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;

65 Example for (int i = 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.

66 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

67 Example Use a nested loop to compute the average grade for each student in a class of 20 students. Each student has taken four exams during the course of the semester. The final grade is calculated as the average of these examination grades.

68 Example The outer loop in our program will consist of 20 passes. Each pass through the outer loop is used to compute the average for one student. The inner loop will consist of 4 passes. One examination grade is entered in each inner-loop pass. As each grade is entered, it is added to the total for the student, and at the end of the loop, the average is calculated and displayed.

69 const int NUMGRADES = 4; const int NUMSTUDENTS = 20; int main ( void ) { double grade = 0.0, total = 0.0, average = 0.0; for (int i = 1; i <= NUMSTUDENTS; i++) // start outer loop { total = 0; for (int j = 1; j <= NUMGRADES; j++) // start inner loop { cout << "Enter an exam grade for this student: "; cin >> grade; total = total + grade; } // end inner loop average = total / NUMGRADES; cout << "\nThe average for student " << i << " is " << average << "\n\n"; } // end of outer loop return 0; }

70 Note: Pay attention to the initialization of total within the outer loop, before the inner loop in entered. Total is initialized 20 times, once for each student. Also note that the average is calculated and displayed immediately after the inner loop is finished. Because the statements that compute and print the average are also contained within the outer loop, 20 averages are calculated and displayed. Output: Enter an exam grade for this student: 99 Enter an exam grade for this student: 87 Enter an exam grade for this student: 56 Enter an exam grade for this student: 78 The average for student 1 is 80 Enter an exam grade for this student: 100 Enter an exam grade for this student: 99 Enter an exam grade for this student: 98 Enter an exam grade for this student: 97 The average for student 2 is 98.5 Etc…..

71 Slide 5- 71 Nested Loops - Notes Inner loop goes through all repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops.

72 Slide 5- 72 Breaking Out of a Loop Can use break to terminate execution of a loop Use sparingly if at all – makes code harder to understand and debug When used in an inner loop, terminates that loop only and goes back to outer loop

73 Slide 5- 73 Breaking Out of a Loop Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end.

74 Breaking Out of a Loop The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:

75

76 Fixed Repetition Versus Variable Condition Loops Fixed repetition loops are used when it can be determined in advance how often a segment of code needs to be repeated. For instance, you might know that you need a predetermined number of repetitions of a segment of code for a program that adds the integers from 1 to 100 or for a program that uses a fixed number of data lines, for example, game statistics for a team of 12 basketball players. The for loop is considered a fixed repetition loop.

77 Fixed Repetition Versus Variable Condition Loops Variable condition loops are needed to solve problems for which conditions change within the body of the loop. These conditions can involve sentinel values or arithmetic expressions. A variable condition loop provides more power than a fixed repetition loop. The while and the do-while loops are variable condition loops.

78 Choosing the Correct Loop “Which type of loop should I choose?” – A question often faced by programmers. A partial answer is: if a loop is to be repeated a predetermined number of times during execution, a for loop is preferable. If the number of repetitions is not known, one of the variable control loops is preferred.

79 Choosing the Correct Loop “Which type of loop should I choose?” The more difficult part of the answer is deciding which variable control loop is appropriate. Simply stated: – if a control check is needed before the loop is executed, use a while loop. – If the check is needed at the end of the loop, use a do- while loop. Remember, however, that a do-while loop must always be executed at least once. – Therefore, if there is a possibility that the loop will never be executed, a while loop must be used.

80 Slide 5- 80 Deciding Which Loop to Use while : pretest loop; loop body may not be executed at all do-while : posttest loop; loop body will always be executed at least once for : pretest loop with initialization and update expression; useful with counters, or if precise number of repetitions is needed

81 String Input with getline The >> (extraction operator) cannot be used to enter a string containing spaces. #include using namespace std; int main() { string name; cout << “Please enter your full name: “; cin >> name; cout << “Your name is: “ << name; return 0; } I/O: Please enter your full name: Mary Jones Your name is: Mary

82 String Input with getline To solve this problem, the string library provides the function getline. This function reads characters, including tabs and spaces, from an input stream into a string variable until a newline (‘\n’) character is detected. The newline character is not stored in the string variable. The syntax for the getline function is: getline(, );

83 String Input with getline Thus the following segment of code would allow a name containing spaces to be entered from the keyboard. int main() { string name; cout << “Please enter your full name: “; getline(cin, name); cout << “Your name is: “ << name; return 0; } I/O: Please enter your full name: Mary Jones Your name is: Mary Jones

84 String Input with getline Because getline does not ignore leading white space characters, you should take special care when using it in conjunction with >> (extraction operator). Consider the following example: int main( ) { string name; int age; cout << "Please enter your age: "; cin >> age; cout << "Please enter your full name: "; getline(cin, name); cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your age: 25 Please enter your full name:, you are 25

85 String Input with getline This program segment will allow the user to enter the age. It then prompts for the name but displays the results immediately without pausing for the input of the name. The reason is that >> (extraction operator) reads and stores characters up to the newline character in age. getline then detects this newline character as the first character “in” the input of the name, so it returns with an empty string before the user can enter any characters. There are two ways to avoid this problem: Reverse the order of the inputs, with getline being called before >>. A call to getline can come after another call to getline, but never after a call to >>. Thus, you can correct the code as follows:

86 String Input with getline int main( ) { string name; int age; cout << "Please enter your full name: "; getline(cin, name); cout << "Please enter your age: "; cin >> age; cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your full name: Mary Jones Please enter your age: 25 Mary Jones, you are 25

87 String Input with getline In cases where at least one call of >> must come before a call of getline, you must “consume” the trailing newline character first. A simple way to do this is to declare a “dummy” string variable and run getline with it after the >> operation. This has the effect of “throwing away” the extra newline character before the next call to getline. A correct code segment that uses this method is:

88 int main( ) { string name, dummy; int age; cout << "Please enter your age: "; cin >> age; getline(cin,dummy); cout << "Please enter your full name: "; getline(cin, name); cout << name << ", you are " << age << endl; return 0; } I/O: Please enter your age: 25 Please enter your full name: Mary Jones Mary Jones, you are 25 *Note: We use >> when we want to read a single word into a string variable, and we use getline when we want to read an entire line of words into a string variable.


Download ppt "Chapter 5: Loops. Slide 5- 2 Outline Increment and Decrement while loop do-while loop for loop."

Similar presentations


Ads by Google