Please send questions to
st10@humboldt.edu .
CIS 130 - Week 12 - Monday, April 12, 2010
* REPETITION!!!
* the 4th "basic" structure of programming
(along with sequence, branching, and procedure)
...because computers are better at doing things
over and over and over and over ad infinitum
than people!
* the most general, basic C++ repetition statement:
the while statement
syntax:
while (bool_expression)
statement;
although since you can replace a single statement with
a block (a block is considered a single "statement"):
(a block is
{
anything;
}
)
while (bool_expression)
{
statement1;
statement2;
...
}
semantics:
* ideally, see the flow chart drawn on the board
(hopefully in your notes)
* made a PDF after class; see
basic-while-flow-chart.pdf
* this is called a leading decision loop,
because the decision to do the body
is made "first";
...note that you MIGHT not ever execute
the while loop's statement!!
example:
this will be a loop where I know how many times
I want to repeat something, going in --
a count-controlled loop
* goal: to burp to the screen 15 times
* if I want to do something a certain number of times,
how can I set that up so a bool_expr will be
true for that many times, and then false?
...for a count-controlled loop,
a local variable called a counter is often
used for this;
int count = 0;
const int NUM_BURPS = 15;
while (count < NUM_BURPS)
{
cout << "BURP!" << endl;
count++;
}
* this fragment is in burp.cpp, and you can see
that it does perform as advertised...
* do you see how count is CHANGED in the body
of the while loop, so that eventually the loop
condition becomes false?
...you need to make sure that the LOOP CONTROL
VARIABLE(s), that are letting you control the
loop repetition, get affected by the loop
so that loop eventually will end
(the loop condition will become false)
...if you don't, and INFINITE LOOP results!
(hit ctrl-c as fast as you can!!!!!)
* a second example:
I want to ask a user for 5 grades,
read them in,
and compute their average
...that isn't pseudocode yet!
set up a local variable to hold the latest grade
set up a local variable to hold the sum of all the grades
so far -- set it to 0 to start
set up a local variable to hold the count, set it to 0 to
start
set up a local named constant for the number of grades
while count is less than the number of grades desired
ask for a grade
read in that grade
add in that grade to the sum so far
count++
print out the result of (sum so far / number of grades)
now let's try to convert our pseudocode to C++:
/* set up needed local variables */
double latest_grade;
double sum_grades = 0;
int count = 0;
const int NUM_GRADES = 5;
/* read in and adding up the grades */
while (count < NUM_GRADES)
{
cout << "Please enter a grade: ";
cin >> latest_grade;
sum_grades = sum_grades + latest_grade;
count++;
}
cout << "The average is: " << sum_grades / NUM_GRADES
<< endl;
* and some examples of these converted into
non-main functions; see examples along with these
notes