CS 111 - Week 14 Lecture 2 - 2016-12-01
* tomorrow's lab quiz:
* be able to declare an array and initialize it at
the time of declaration
* given an array declaration (possibly initialized),
you can:
* give the type of its elements
* give the indices of its elements
* write an expression representing one of
the array's elements
* write an expression representing the
entire array
* can you write a for-loop to do something
a set number of times?
* can you write a for-loop to do something to/with
each element in an array?
* continue with for loop intro:
int i = 0;
while (i < limit)
{
action;
i++;
}
...this is roughly the same action using
a for loop:
for (int i = 0; i < limit; i++)
{
action;
}
1. when a for-loop is reached,
its init part -- before the first ; --
is done
2. THEN its bool condition (before the second ; )
is checked;
IF it is true, you do the body,
and when the body is done, THEN
you do the update part (after the second ; )
and then go back to 2
IF it is false,
exit the loop.
a couple of informal examples:
// print MOOOOOOO to the screen 50 times
for (int ct = 0; ct < 50; ct++)
{
cout << "MOOOOOOO" << endl;
}
// create and initialize an array of 153 double grades
// to all have the value 100.0
const int NUM_GRADES = 153;
double grades[NUM_GRADES];
for (int i=0; i < NUM_GRADES; i++)
{
grades[i] = 100.0;
}
==========
another array example: write a function to find the
smallest element in a given array
signature: smallest: double[] int -> double
purpose: expects an array of values and its size, and
returns the smallest value in that array.
Returns 0.0 for an empty array (for an array of size
0)
header:
double smallest(double values[], int size)
examples:
const int NUM_VALS = 5;
double vals[NUM_VALS] = {50, 2, 45.4, 22, 7};
smallest(vals, NUM_VALS) == 2
smallest(vals, 0) == 0.0
const int NUM_WIDGETS = 4;
double widg_hts[NUM_WIDGETS] = {-10, -11, 0, e};
smallest(widg_hts, NUM_WIDGETS) == -11
pseudocode:
if the array is empty,
return 0.0
else
make the 1st element the smallest yet seen
look at each element in the array
if the latest element is less than smallest yet seen,
set smallest yet seen to the latest element
return smallest yet seen
=========
NOT all loops are count controlled!
=========
* here are two more example patterns for NON-count-controlled
loops
* NOTE: while loops are the better choice for NON-count-controlled
loops than for loops...
SENTINEL controlled loop
* you loop giving desired data until you give
a special non-data value called the sentinel
get first piece of data
while (the current data is NOT the sentinel)
{
handle data
get next piece of data
}
QUESTION-CONTROLLED loop:
ask if they want to go on
while (answer is yes)
{
get the data
handle the data
ask if they want to go on
}