Counter-Controlled Repetition
Essentialsof Counter-Controlled Repetition
1. the name of a control variable (or loop counter)
2. the initial value of the control variable
3. the loop-continuation condition that tests for the final value
of the control variable (i.e., whether looping should continue)
4. the increment (or decrement) by which the control variable is
modified each time through the loop.
Counter-Controlled Repetition
1. intmain()
2. {
int counter = 1; // declare and initialize control variable
while ( counter <=10 ) // loop-continuation condition
{
cout << counter << " ";
counter++;
} // end while
cout << endl; // output a newline
3. return 0;
4. } // end main
6.
Counter-Controlled Repetition
intcounter; // declare control variable
counter = 1; // initialize control variable to 1
while (counter <= 10 ) // loop-continuation condition
cout << counter << " ";
counter++;
7.
Example : while
stringans = “n”;
while (ans != “Y” && ans != “y”)
{
cout << “Would you help me with the assignment?”;
cin >> ans;
}
cout << “Great!!”;
(ans != “Y” || ans != “y”)
Can I put ;
here?
No!!
8.
Example : while
inta,b,sum;
cout << “This program will return the ”;
cout << “summation of integers from a to b.nn”;
cout << “Input two integers a and b:”;
cin >> a >> b;
while (a <= b)
{
sum += a;
a++;
}
cout << “The sum is ” << sum << endl;
sum = 0;
sum = sum + a;
Don’t forget to set
sum = 0;
10
Nested while loop
int i=1;
int j=1;
int rows=8;
while (i <= rows)
{
while (j <= i)
{
cout<<j;
j++;
}
cout<<"n";
i++;
j = 1;
}
11.
For Repetition Statements
for(Initialization_action; Condition; Condition_update)
{
statement_list;
}
1 2 3
Specifies the counter-controlled repetition details in a single
line of code.
The general format for a loop
12.
For Loop
1. //Counter-controlledrepetition with the for statement.
2. int main() {
3. // for statement header includes initialization,
4. // loop-continuation condition and increment.
for ( int counter = 1; counter <= 10; counter++ )
{
cout << counter << " ";
}
5. cout << endl; // output a newline
6. return 0;
7. } // end main
13.
13
Compare: for andwhile
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}
int n,f=1;
cin >> n;
for (i=2; i<=n; i++)
{
f *= i;
}
cout << “The factorial of ” << n << “ is ” << f << “.”;
i=2;
while (i<=n)
{
f *= i;
i++;
}
1 2 3
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}
14.
Compare: for andwhile
int n,i;
n = 100;
for (i=1; i <= n; i++)
{
statement_list;
}
int n,i;
n = 100;
i = 1;
while (i <= n)
{
statement_list;
i++;
}
v.s.