Title: Lecture 10:Control Structures II (Repetition)
1Lecture 10Control Structures II (Repetition)
- Introduction to Computer Science
- Spring 2006
2(No Transcript)
3(No Transcript)
4The while Loop
- The general form of the while statement is
- while(expression)
-
- statement1
- statement2
-
-
- while is a reserved word
- While Loop works in the following procedure
- Expression provides an entry condition
- Statement executes if the expression initially
evaluates to true - Loop condition is then reevaluated
- Statement continues to execute until the
expression is no longer true - Infinite loop continues to execute endlessly
5Counter-Controlled while Loops
- If you know exactly how many pieces of data need
to be read, the while loop becomes a
counter-controlled loop - The syntax is
- counter 0
- while(counter lt N)
-
-
- counter
-
-
6Counter-Controlled while Loops
include ltiostreamgt using namespace std int
main() int i i0 while (ilt20) coutltlti
ltlt" " ii5 coutltltendl return(0)
7Sentinel-Controlled while Loops
- Sentinel variable is tested in the condition and
loop ends when sentinel is encountered - The syntax is
- cingtgtvariable
- while(variable ! sentinel)
-
- .
- cingtgt variable
- .
-
8Sentinel-Controlled while Loops
include ltiostreamgt using namespace std const
int SENTINEL-999 int main() int
number cout ltlt "If you want to terminate the
program, please enter -999."ltltendl cout ltlt
"Enter a number " cingtgtnumber while (number
! SENTINEL) coutltltnumberltlt" "ltltendl cout
ltlt "Enter a number " cingtgtnumber coutltlten
dl return(0)
9Flag-Controlled while Loops
- A flag-controlled while loop uses a Boolean
variable to control the loop - The flag-controlled while loop takes the form
- found false
- while(!found)
-
-
- if(expression)
- found true
-
-
10Flag-Controlled while Loops
include ltiostreamgt using namespace std int
main() bool found int number foundfalse
while (!found) cout ltlt "Enter a number
" cingtgtnumber cout ltlt "Your input is "
ltltnumberltltendl if (number gt 10) foundtrue
coutltltendl return(0)
11EOF-Controlled while Loops
- Use an EOF (End Of File)-controlled while loop
- The logical value returned by cin can determine
if the program has ended input - The syntax is
- cin gtgt variable
- while (cin)
-
- .
- cin gtgt variable
- .
-
12EOF-Controlled while Loops
include ltiostreamgt include ltstringgt using
namespace std int main() int
x cingtgtx while(cin) coutltltx cingtgtx
return 0
13The eof Function
- The function eof can determine the end of file
status - Like other I/O functions (get, ignore, peek), eof
is a member of data type istream - The syntax for the function eof is
- istreamVar.eof()
- where istreamVar is an input stream variable,
such as cin
14The eof Function
include ltfstreamgt include ltiostreamgt using
namespace std int main() ifstream
infile char ch infile.open("c\\tmp\\input.da
t") infile.get(ch) while (!infile.eof())
cout ltlt ch infile.get(ch) coutltltendl re
turn(0)
15End of lecture 10