Tải bản đầy đủ (.pdf) (20 trang)

Lecture Programming in C++ - Chapter 6: Repetition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (325.79 KB, 20 trang )

Chapter 6 ­ Repetition
       


while Loop
Simplest loop
Two parts: test expression and loop body
Pre­tested loop
– Execute loop body if test true
– Bypass loop body if test false

 
Lesson 6.1

 


General Structure
while
(expression)
{
Logical expression (variable or arithmetic expression)
Boolean results (True or False)
statement1
statement2

Lesson 6.1 }


Steps In Using a while Loop
 1.  Initialize  variable acting as test expression


 2.  Evaluate the boolean test
 3.  If true execute statements within loop
 4.  Update the variable
 5.  Go back to step 2
Note: if no change to variable then
infinite loop (never ends) is created
Lesson 4.1


Example while Loop
Initialize variables
int i= 0, number = 1;
while (number) Variable as expression
    {
value other than zero tests true
         cout << “Please type a number.  ”
       << “Type 0 (zero) to stop execution.\n”;
         cin >> number;
Loop body
         i++;
         if (i > 50) break;
    }
Statements that provide exit from loop
Lesson 6.2


Example while Loop
Initialize test expression variable
int i= 0;
while (i <= 5) Expression evaluated, when

    {
true, statements in loop executed
         cout << “Loop number is “ << i;
Statements within loop
         i++;
     }
Changing variable to
 provide exit from loop

Lesson 6.2


do­while Loop
Used when you want to execute loop 
at least once
Loops on test being true and exits 
when test is false

Lesson 6.3


General Syntax
 do
     { 
        statement1;
        statement2;
        … 
      } while (expression);
Lesson 6.3



do while Loop Example
do
    { cout << “\n enter an id number:”;
       cin >> id_num;
    } while ((id_num < 100) || (id_num>1999));
Bare bones
Does not alert user of problems
Lesson 6.3


Better do while Loop

do
{ cout << “\n Enter an id number:”;
  cin  >>  id_num;
  if ((id_num < 100) || (id_num > 1999))
  {  cout << “\n invalid number entered”
              << “\n please check and re­enter”;
   }
Decision Statement – Chapter 5
   else
Exit loop if id number is valid
      break;
Expression always true
} while (1);
Lesson 6.3


Recap  while(s)

while
– Most commonly used when repetition not 
counter controlled
– Pre­tested
– Loop body may not be executed

do­while
– Convenient when at least one repetition needed
– Post­tested 
Lesson 6.3


For Loop
Convenient for counter controlled loops
Pre­tested loop
Same behavior as while
– Set lcv to initial value
– Test lcv against terminating value
– Update lcv to next value

All done in for header statement
 
Lesson 6.4

 


General Syntax
for (initialize lcv; test lcv; update lcv)
             {

statement;
                statement;
           }
Lesson 6.4


for Loop  (cont.)
Example:

      for (int i = 0; i < 10; i++)
cout << i;
Initialization, testing and updating in same 
statement
Semicolons required
Braces optional if only one statement
 
Lesson 6.4

 


Example:
int finalValue;
False
True
True
cin >> finalValue;
for (int counter = 0; counter < finalValue; counter++)
      cout << "*";


3

3

***

Display Screen
 
Lesson 6.4

finalValue

 

0321

counter


For Loop Examples
for (int count = 0; count < n; count++)
cout << ch;
float sum = 0;
for (float x = 0.5;  x < 20.1;  x += 0.5)
sum += sqrt (x);
 
Lesson 6.4

 



int finalvalue;
Comparison:
cin >> finalValue;
for (int counter = 0; counter < finalValue; counter++)
      cout << "*";
int finalvalue;
cin >> finalValue;
for (int counter = 0;
counter < finalValue;
counter ++)
cout << "*";
 
Lesson 6.4

 

int counter, finalValue;
counter = 0;
cin >> finalValue;
while (counter < finalValue)
{  cout << "*";
    counter++;}


Debugging and Testing
Off by one errors
– Check loops to ensure you are executing the 
correct number of times
– x < 10     or      x <= 10


Check loop boundaries
– Can create infinite loop

Does answer make sense
 
Lesson 6.4

 


For Loop Modifications
break statement
– Can use within loop to terminate early
– Controversial 

Multiple expressions for initialization and 
increment
– Use comma separated list
– for (I = 1, j = 2; I < 10; I++, j++)
Lesson 6.4


Summary
Learned how to:
Create while loops
Create do­while loops
Create for loops
Trace and debug loops
Use loops to solve problems


Chapter 6



×