Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
(Repetition)
Control Structures
}
Sequence Structure
2.
Selection Structure
3.
Repetition Structure
For
While
Do-while
Loops
}
Types of Loops
}
for loop
while loop
do while loop
1. for Loop
}
b)
c)
for Loop
}
for Loop
}
Nesting of Loops
Loops can also be nested like if statements.
void main ( )
{
int r, c, sum;
for ( r = 1; r<= 3; r++)
{
for( c =1; c <= 2; c++)
{
sum = r + c;
cout<<r =<< r;
cout<< c =<< c;
cout<<sum =<<sum<<endl;
}
}
}
Output of Program
Variable Visibility
}
//Error: j is undefined/
2. while Loop
}
Tips
}
while ( i <= 10 )
Tips
}
Output of Program
Counter-Controlled Repetition
}
Counter-controlled repetition
}
Definite repetition
}
Example
A class of ten students took a quiz. The grades (integers
in the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.
Contd
average = total / 10;
// display result
cout << "Class average is " << average << endl;
}
Output
Sentinel-Controlled Repetition
}
} How
end?
Contd
}
Sentinel value
}
-1 in this case
// initialize total
// initialize loop counter
Contd
// loop until sentinel value read from user
while ( grade != -1 )
{
total = total + grade;
gradeCounter = gradeCounter + 1;
cout << "Enter grade, -1 to end: ";
cin >> grade;
}
Contd
if ( gradeCounter != 0 )
{
average = total / gradeCounter;
cout << "Class average is " << average << endl;
}
else
cout << "No grades were entered" << endl;
}
//end main
Output
Exercise 1
Find the powers of 3 less than or equal to 100
1.
void main ( )
{
int product = 3;
while ( product <= 100)
{
cout<<"Product="<<product<<endl;
product = 3 * product;
}
}
Exercise 2
2.
void main ( )
{
int sum = 0, i;
while ( i <= 10)
{ sum=sum+i;
i++;
}
cout<<"sum="<<sum<<endl;
}
Task to be done
}
}Typically,
for statements are used for countercontrolled repetition and while statements are used
for sentinel-controlled repetition.
}
32
3. do/while loop
}
Format
do {
statement
} while ( condition );
33
Example Program
void main()
{
int counter = 1;
// initialize counter
do {
cout << counter << " "; // display counter
} while ( ++counter <= 10 ); // end do/while
cout << endl;
}
break Statement
}
break statement
}
Common uses
}
35
Example Program
void main() {
int x;
// loop 10 times
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
break;
// break loop only if x is 5
cout << x << " "; // display value of x
} // end for
cout << "\nBroke out of loop when x became " << x
<< endl;
}
continue Statement
}
continue statement
}
for structure
}
37
Example Program
void main()
{
for ( int x = 1; x <= 10; x++ )
{
// if x is 5, continue with next iteration of loop
if ( x == 5 )
continue;
// skip remaining code in loop body
cout << x << " "; // display value of x
} // end for structure
cout << "\nUsed continue to skip printing the value
5"
<< endl;
Thank You