Upload
hayley
View
53
Download
0
Tags:
Embed Size (px)
DESCRIPTION
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; - PowerPoint PPT Presentation
Citation preview
Chapter 5:
Loops
Slide 5- 2
Outline
Increment and Decrement while loop do-while loop for loop
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++;
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--;
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
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 14num = --val; // sets val to 13,
// stores 13 in numnum = val--; // stores 13 in num,
// sets val to 12
Slide 5- 9
Outline
Increment and Decrement while loop do-while loop for loop
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
Slide 5- 12
Slide 5- 13
The process used by the computer in evaluating a while statement is:
1. test the expression2. 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
Slide 5- 15
The Logic of a while Loop
Slide 5- 16
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++;}
Slide 5- 20
An Infinite Loop
int number = 1;while (number <= 5){ cout << "Hello\n";}
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
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
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
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;}
}
The Power of the while statementNote: 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).
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)
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;}
Slide 5- 28
Outline
Increment and Decrement while loop do-while loop for loop
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
Slide 5- 31
The Logic of a do-while Loop
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.
Slide 5- 35
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 < 100 || ident_number >
1999);
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 < 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);
Slide 5- 38
Outline
Increment and Decrement while loop do-while loop for loop
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.
Slide 5- 40
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 )
Slide 5- 41
The for Loop
• General Format:for(initialization; test; update)
statement; // or block in { }
• for Loop - Mechanics1) Perform initialization2) Evaluate test expression
• If true, execute statement• If false, terminate loop execution
3) Execute update, then re-evaluate test expression
Slide 5- 43
A Closer Look at the Previous Example
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;
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;}
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
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;
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;
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.
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 accumulatorwhile (num <= 10){ sum += num;
num++;}cout << "Sum of numbers 1 – 10 is" << sum << endl;
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;}
OutputHow many numbers would you like to total?4Please enter a number: 56Please enter a number: 45Please enter a number: 85Please enter a number: 43The total of the numbers you entered is: 229The average of the numbers you entered is: 57.25
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
Slide 5- 61
Slide 5- 62
Slide 5- 63
Outline
Increment and Decrement while loop do-while loop for loop
nested for loop
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++) //outerfor (col=1; col<=3; col++)//inner
cout << row * col << endl;
Examplefor (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.
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
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.
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.
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;}
• 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: 99Enter an exam grade for this student: 87Enter an exam grade for this student: 56Enter an exam grade for this student: 78The average for student 1 is 80
Enter an exam grade for this student: 100Enter an exam grade for this student: 99Enter an exam grade for this student: 98Enter an exam grade for this student: 97The average for student 2 is 98.5
Etc…..
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: