COS401a Compiler Theory

advertisement
Page 1
COS120 Software Development Using C++ – Lecture 15
AUBG, COS dept
Lecture 15
Control Flow. (continued).
Nested do-loops. Design and implementation of programs illustrating
linear, branch and loop algorithms.
K&R, Sec 1.3, 3.5
H&K, Chap 5
F&K, Chap 5
Build programs implementing linear algorithms, branch algorithms and loop algorithms:
 Build a function int getint(int nmin, int nmax) to return an integer that is in the
range specified by its two arguments nmin and nmax. A loop would repeatedly
prompt the user for a value in the desired range.
 Character input/output by using end file controlled loop;
Design:
read a character;
while (character is not end-of-file indicator)
{
display the character just read;
read a new character;
}
Demo programs CPPCountCharEOF.cpp and CCountCharEOF.cpp
previous lecture
from
 To compute 5 Pythagorean triples;
Input: two positive integer values m, n; m>n
Output:
side1 = m2 – n2;
side2 = 2mn;
hypotenuse = m2 + n2;
 To compute the greatest common divisor of two positive integers using the
Euclid’s algorithm;
Input: two positive integer values m, n
Algorithm: loop including division of both values while the remainder is != 0
int m, n, rem, gcd;
cin >> m >> n;
// scanf (“%d%d”, &m, &n);
while ( (rem= m%n) != 0){
m = n;
n = rem;
}
gcd = n;
cout << gcd;
// printf(“%d”, gcd);
More
source texts on back page >>
Page 2
The source text of a function int getint(int nmin, int nmax) to return an integer
that is in the range specified by its two arguments nmin and nmax. A loop would
repeatedly prompt the user for a value in the desired range.
// GetIntCPPVersion
#include <iostream>
using namespace std;
int getint(int, int);
int main()
{
for (int k=1; k<=3; k++)
{
cout << "\nDriver program testing function getint(p1,p2)";
cout << "\nYou entered value " << getint(10, 20) << "\n";
}
system("pause");
return 0;
}
int getint(int nmin, int nmax)
{
int inval, errorflag;
do
{
errorflag = 0;
cout<<"\nEnter integer in range from " << nmin << " to "<< nmax;
cin >> inval;
if (inval < nmin || inval > nmax)
{
errorflag = 1;
cout <<"\n Number " << inval << "not in range";
}
} while (errorflag);
return inval;
}
Download