COS401a Compiler Theory

advertisement
Page 1
COS120 Software Development Using C++ – Lecture 13
AUBG, COS dept
Lecture 13
Control Flow. Repetition (loop) structures (continued).
Logical and functional classification of loop (iterative) algorithms.
Preparation for the midterm exam.
K&R, Sec 1.3, 3.5
H&K, Chap 5
F&K, Chap 5
Loop statements: General Concept:
 loop – a control structure that repeats a group of steps (statements) in a program;
 loop body – the statements that are repeated in the loop.
Logical and functional classification of loop (iterative, repetitive, cycled) algorithms:
if (know in advance how many times to repeat)
{
use Counter controlled loop;
}
else
{
use Sentinel controlled loop;
use End File controlled loop;
use Input Validation loop;
use General conditional loop;
}
or
or
or
Build programs based on loop algorithms:
 counter controlled loops based on for and while statements;
 sentinel controlled loop: input of a single list of data of any length terminated by
a special value;
 end file controlled loop: input of a single list of data of any length terminated by
the end of file indicator (Ctrl/Z in MSDOS/Windows, Ctrl/D in UNIX/Linux);
 input validation loop: input of a data value until a value within the valid range is
entered;
 using a for statement to implement a sentinel controlled loop;
 to display the first n (n is entered as integer input value) elements of Fibonacci
sequence 1, 1, 2, 3, 5, 8 … ;
 using user defined function long facti(int n); for iterative computation of the
factorial(n)=n!
More on back >>
Page 2
Example of Counter controlled loop
int I, sum=0, var;
int I, sum=0, var;
for (I=0; I<=5; I++) { cin >> var;
I=0;
sum += var; }
while (I<=5) { cin >> var;
cout << sum;
sum += var; I = I +1; }
cout << sum;
Example of Sentinel controlled loop
#define SENTINEL (-99)
1. Read the first data item.
...
2. While the sentinel value
int sum=0, var;
has not been read.
cout << "\nEnter value:"; cin >> var;
3. Process the data item.
while (var != SENTINEL) {
4. Read the next data item.
sum += var; cin >> var;
}
cout << sum;
Example of Flag controlled loop
1. Set the flag to false.
char getDigit()
2. while the flag is false
{
perform some action.
char nextChar;
bool digitRead;
reset the flag to true if
digitRead = false;
the anticipated event occurs
while (!digitRead)
{
cin >> nextChar;
digitRead = ( isdigit(nextChar) );
}
return nextChar;
}
Example of End File (End of Data) controlled loop
int var, sum=0;
cout << "\nEnter value:"; cin >> var;
while ( !(cin.eof()) ) {
sum+=var;
cout << "\n" << sum << " Enter new value:"; cin >> var;
}
cout << "\n\nSum=" << sum ;
Example of Input validation loop
int numobs;
...
cout << “\nEnter number of observed values:”; cin >> numobs;
while (numobs <=0 ){
cout << “\nNegative or Zero number of observations invalid. Try again:”;
cin >> numobs;
}
Download