// Comment to describe the function of the loop
Loop Head
< executable code >
Return to Loop Head
|
Note: The comments before the loop head are for the benefit of the
reader and are ignored by the compiler.
In general, a loop performs the following tasks:
In C++, we have three kinds of loops: while,   do...while,   for
syntax (form):
while(logical expression)
statement
|
-----------------------------------
An aside. Variables of type char
can hold a single character, and character constants are delimited by single
quotes. We use the ASCII character set; see the table in your text.
Note: a space is a valid character. To input a character into a
char variable, you
merely type the character; you do not enclose it in single quotes.
Be aware that the ASCII character '4' is stored in one byte of memory
and is different from the integer   4   which is stored in
2s-complement.
Example
char ch; // loop control variable (lcv), holds input char
// skip leading blanks in the input stream
cin >> ch; // prime read
while(ch == ' ')
cin >> ch;
|
Note:    while loops use
pretesting. The logical expression is evaluated to true or
false
    to determine whether
or not the loop body is executed.
Question:    What happens if we place a semi-colon after the
loop header?   while(ch == '  ' );
Question:    What is the value of ch when the loop terminates?
Notice the syntax:
// include a comment to describe what loop does
while(logical expression) {
statement 1;
statement 2;
...
statement n;
}
|
Question:    What happens if we place a semi-colon before the opening brace in the loop header?   while(logical expression) ;   {
Question:    What happens if we place a semi-colon after the opening brace in the loop header?   while(logical expression)   { ;
Example
Often we must "prime" the loop, such as with an initial or prime read before the loop head.
const int SENTINEL = -99999;
...
int number; // holds individual input value
// read and echo zero or more integers
cout << "Enter an integer, -99999 to quit. ";
cin >> number;
while(number != SENTINEL) {
cout << number << endl;
cout << "Enter an integer, -99999 to quit. ";
cin >> number;
}
|
Write a code segment to skip over leading non-alphabetic characters in the input stream.
char ch; // holds input character, lcv
// skip over leading non-alphabetic characters in input
cin >> ch;
while( !(ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') )
cin >> ch;
|
Question: What is (always) the value of  ch  when the loop terminates?
Is this good code? It is hard to read, and I would write the logical expression as a function, alphabetic( ). Then the code would be:
char ch; // holds input character, lcv
// skip over leading non-alphabetic characters in input
cin >> ch;
while( !alphabetic(ch) )
cin >> ch;
|
Of course, we would include a prompt for input, but I didn't want to clutter the code.
Question: Can you write function alphabetic( )?
________________________________________
Note:
You must alter the loop control variable, or lcv, during
execution of the loop.
Below, we get trapped in an infinite loop
when the input is negative.
int x;
cin >> x;
while(x < 0)
cout << x << endl;
|
This is an infinite loop because the value of the lcv  x 
is not modified in the body of the loop.
Thus, the stopping condition
  x >= 0   may never be met.
Warning: Endless loops are not cool.
syntax:
do
statement
while(logical expression)
|
Example
char response;
// Check for a valid response.
do {
cout << "Continue? (Y or N)";
cin >> response;
} while(response != 'Y' && response != 'N');
|
syntax:
for(expression 1; expression 2; expression 3)
statement
|
How for loop works:
Example
What is output of the following code fragment?
for(count = 0; count < 4; count++)
cout << count << " ";
cout << endl;
|
count: output: |
Example
In a for loop, expression 1 (and expression 3) can have multiple parts.
int x, y; // Assume MAX and N are global constants
for(x = 0, y = MAX; x <= N; x++) {
cout << x + y << " ";
if( (x + 1) % 5 == 0)
cout << endl;
}
cout << endl;
|
N + 1
- With paper and pencil, determine what (not how) this code does.
Use a
trace table. Try  MAX = 10; N = 3. Then try  N = 7; N = 12. Example
// Print out every Nth number between 0 and 100, inclusively.
const int N = 10;
int i; // lcv
for(i = 0; i <= 100; i += N)
cout << i << " ";
cout << endl;
|
11
110
Example
// Print the numbers from 100 through 1, one per line.
for(i = 100; i >= 1; i--)
cout << i << endl;
|
N will
start execution of the loop?   terminate the loop?for(i = 0; i < N; i++)
. . .
for(i = 0; i < N; ++i)
. . .
i += 1;x = i++; is functionally equivalent to   x = i;   i += 1;
x = ++i; is functionally equivalent to   i += 1;   x = i;
i = i + 1;   to increment variable i by one.Print out an answer sheet for a multiple choice test with 50 questions, 5 choices per question.
int number; // line number being processed
char ch // represents an answer choice a to e
// Print the 50 lines.
for(number = 1; number <= 50; number++) {
cout << number << ". ";
if(number <= 9) cout << " ";
// Within each line, print the letter choices.
for(ch ='a'; ch <= 'e'; ch++)
cout << ch << " ";
cout << endl << endl;
}
|
How many times is each cout statement executed?
cout << number << ". ";
      ______________cout << endl << endl;
______________
cout << ch);
     ______________
for(i = m; i <= n; i++)
...
for(i = m; i < n; i++)
...
for(i = m; i < n; i += x)
. . .
Write code to output the first two columns:
0 1 // 2 ^ 0 = 1
1 2 // 2 ^ 1 = 2
2 4 // 2 ^ 2 = 4
3 8 // 2 ^ 3 = 8
4 16 // 2 ^ 4 = 16
5 32 // 2 ^ 5 = 32
6 64 // 2 ^ 6 = 64
The first column is easy: i++
The second column represents powers of two, 2^.  
#include<iomanip>
int i; // first column, a simple count
int power_2; // second column, (2 ^ i)
i = 0;   power_2 = 1;
// To prevent overflow, i must be <= 30 (we are safe with 6).
while(i <= 6) {
cout << i << setw(4) << power_2 << endl;
i++;
power_2 = power_2 * 2;
}
-OR-
i = 0;  power_2 = 1;
while(power_2 <= 64) {
cout << i << setw(4) << power_2 << endl;
i++;
power_2 = power_2 * 2;
}
|
Rewrite the while loop as a
for loop.
for(i = 0, power_2 = 1; i <= 6; i++, power_2 *= 2)
cout << i << setw(4) << power_2 << endl;
|
const int N = 100; // number of input values
...
/***------------------lsearch()----------------------
Search up to N input values for a target integer.
Input: target value
Return: 1 if found, and 0 otherwise.
---------------------------------------------------***/
int lsearch(int target)
{
int i, // loop control variable or lcv
x, // holds input value
found; // target found yet?
found = 0; // not found yet
for(i = 0; i < N && !found; i++) {
cin >> x;
if(x == target) found = 1;
}
return found; // single exit point
}
|
// -OR- Change loop head; loop still executes same number of times.
for(i = 1; i <= N && !found; i++)
...
What is the value of lcv i  when the the target is not found? What happens if we omit the variable found?
Answer:   If the logical expression is   (i < N),   i
equals N ;
if it is   (i <= N),   i equals N+1.
In calling program:
cin >> hunt_for;
if(lsearch(hunt_for))
cout << hunt_for << " found!\n";
else
cout << hunt_for << " not there.\n";
|
const int N = 100;
int lsearch3(int target)
{
int i, x;
for(i = 0; i < N; i++) {
cin >> x;
if(x == target)
return 1; // exit, target found
}
return 0; // exit, target not found
}
|
int x, y = 0;
cin >> x;
while(x != 0) {
y = (x % 10) + (y * 10);
x /= 10;
}
cout << endl << y << endl;
|
Trace with x values 12, 452, and 1825. What about negative values?
(b) What does the following code do?
int x, y;
for(y = 0, cin >> x; // expression 1
x != 0; // expression 2
y = x % 10 + y * 10, x /= 10); // expression 3 and null body (the semi-colon)
cout << endl << y << endl;
|
Trace with small x values 12, 452, and 1825.
Notice that all the work is performed by the loop head.
Are the two previous codes functionally equivalent?
// format of a for loop
for(expression_1; expression_2; expression_3)
body of loop
// format of a while loop
expression_1
while(expression_2) {
body of loop
expression_3
}
|
expression_1
body of loop
expression_3
while(expression_2) {
body of loop
expression_3
}
|
Do on the machine: Write a sample piece of code, using each of the three types of loops. Watch the final lcv value!
expression_1
if(expression_2)
do {
body of loop
expression_3
} while(expression_2)
|
The body is always executed in do...while; thus, the initial test is
needed to simulate a for or while loop.