Professional Documents
Culture Documents
Week#10
Week#10
Week#10
1
Repetition (looping)
Lecture Outline
1 What is a loop?
2 Count/Event Controlled Loops
3 While statement
4 Do-While statement
5 For statement
1. What is a loop?
SYNTAX
while ( condition )
{
loop body statements
}
3. While Statement
Example
Every while loop will always
contain three main elements:
int count ;
count = 4;
Priming: initialize your
while (count > 0)
variables.
{ cout<<count ;
count -- ;
Testing: test against some
}
known condition.
cout << “Done” ;
Updating: update the
variable that is tested.
The While loops
The While loops Initial
value
Stopping
• The while loop consists of 3 condition
major parts:
o Initial value
o Stopping condition
o update
update
3. While Statement
Example 1 Example 2 (Infinite Loop:
#include <iostream> A loop that never ends)
using iostream std;
main () #include <iostream>
{ using iostream std;
const int MAX =10; main ()
int index =1; {
while (index <= MAX) const int MAX =10;
{cout<<“index: “<< index<<endl; int index =1;
index = index + 1; while (index <= MAX)
} { cout<<“index: “<< index<<endl;
} }
}
The While loops
• Cases that causes infinite loops
3. While Statement
Example
Use a while loop to print the numbers from 1 to 20 each on a
separate line.
int count ;
count = 1 ;
while ( count < =20 )
{ cout<<“count = “<<count<<endl;
count++;
}
3. While Statement
Example
Use a while loop to read 10 numbers and get their average
int total=0,count,av ,n;
count = 0 ;
while ( count < 10 )
{
cin>>n;
total = total + n ;
count++ ;
}
av=total/10;
cout<<“\n The average = “ << av ;
3. While Statement
Example on event controlled looping
int x=0;
while (x!=10)
{ The code inside this loop will be
cout<<“try again!” ; repeated until the user enters
cin>>x; 10, hence the condition will be
} false.
4. Do-While Statement
SYNTAX
do
{
loop body statements
} while ( condition );
4. Do-While Statement
⮚ The do…while repetition statement is similar to the
while statement.
⮚ In the while statement, the loop-continuation
condition is tested at the beginning of the loop
before the body of the loop is performed.
⮚ The do…while statement tests the loop-continuation
condition after the loop body is performed.
⮚ Therefore, the loop body will be executed at least
once.
⮚ When a do…while terminates, execution continues
with the statement after the while clause .
4. Do-While Statement
Example
int x=1;
do
{ The text will be printed at least
cout<<“ I’m in the loop \n”; one time, then it will be repeated
cin>>x; until the user enter 0
} while (x!=0 );
5. For Statement
SYNTAX
27