SlideShare a Scribd company logo
Starting Out with C++ from Control Structures to
Objects 8th Edition Gaddis Solutions Manual
download pdf
https://testbankfan.com/product/starting-out-with-c-from-control-
structures-to-objects-8th-edition-gaddis-solutions-manual/
Visit testbankfan.com to explore and download the complete
collection of test banks or solution manuals!
We have selected some products that you may be interested in
Click the link to download now or visit testbankfan.com
for more options!.
Starting Out with C++ from Control Structures to Objects
8th Edition Gaddis Test Bank
https://testbankfan.com/product/starting-out-with-c-from-control-
structures-to-objects-8th-edition-gaddis-test-bank/
Starting Out With C++ From Control Structures To Objects
9th Edition Gaddis Solutions Manual
https://testbankfan.com/product/starting-out-with-c-from-control-
structures-to-objects-9th-edition-gaddis-solutions-manual/
Starting Out With C++ From Control Structures To Objects
7th Edition Gaddis Solutions Manual
https://testbankfan.com/product/starting-out-with-c-from-control-
structures-to-objects-7th-edition-gaddis-solutions-manual/
Americas History Concise Edition Volume 2 9th Edition
Edwards Test Bank
https://testbankfan.com/product/americas-history-concise-edition-
volume-2-9th-edition-edwards-test-bank/
Chemistry 7th Edition McMurry Test Bank
https://testbankfan.com/product/chemistry-7th-edition-mcmurry-test-
bank/
Microeconomics 9th Edition Parkin Test Bank
https://testbankfan.com/product/microeconomics-9th-edition-parkin-
test-bank/
Business Ethics Ethical Decision Making and Cases 12th
Edition Ferrell Test Bank
https://testbankfan.com/product/business-ethics-ethical-decision-
making-and-cases-12th-edition-ferrell-test-bank/
Managerial Accounting 3rd Edition Braun Test Bank
https://testbankfan.com/product/managerial-accounting-3rd-edition-
braun-test-bank/
Principles of Microeconomics 8th Edition Mankiw Test Bank
https://testbankfan.com/product/principles-of-microeconomics-8th-
edition-mankiw-test-bank/
Environment The Science Behind the Stories 6th Edition
Withgott Test Bank
https://testbankfan.com/product/environment-the-science-behind-the-
stories-6th-edition-withgott-test-bank/
PURPOSE 1. To introduce and allow students to work with arrays
2. To introduce the typedef statement
3. To work with and manipulate multidimensional arrays
PROCEDURE 1. Students should read the Pre-lab Reading Assignment before coming to lab.
2. Students should complete the Pre-lab Writing Assignment before coming to lab.
3. In the lab, students should complete labs assigned to them by the instructor.
L E S S O N S E T
7 Arrays
Contents Pre-requisites
Approximate
completion
time
Page
number
Check
when
done
Pre-lab Reading Assignment 20 min. 114
Pre-lab Writing Assignment Pre-lab reading 10 min. 122
LESSON 7A
Lab 7.1
Working with One- Basic understanding of 30 min. 123
Dimensional Arrays one-dimensional arrays
Lab 7.2
Strings as Arrays of Basic understanding of 20 min. 126
Characters arrays of characters
LESSON 7B
Lab 7.3
Working with Two- Understanding of multi- 30 min. 129
Dimensional Arrays dimensional arrays
Lab 7.4
Student Generated Code Basic understanding 30 min. 134
Assignments of arrays
113
114 LESSON SET 7 Arrays
PRE-LAB READING ASSIGNMENT
One-Dimensional Arrays
So far we have talked about a variable as a single location in the computer’s
memory. It is possible to have a collection of memory locations, all of which
have the same data type, grouped together under one name. Such a collection
is called an array. Like every variable, an array must be defined so that the com-
puter can “reserve” the appropriate amount of memory. This amount is based upon
the type of data to be stored and the number of locations, i.e., size of the array,
each of which is given in the definition.
Example: Given a list of ages (from a file or input from the keyboard), find
and display the number of people for each age.
The programmer does not know the ages to be read but needs a space for the
total number of occurrences of each “legitimate age.” Assuming that ages 1,
2, . . . , 100 are possible, the following array definition can be used.
const int TOTALYEARS = 100;
int main()
{
int ageFrequency[TOTALYEARS]; //reserves memory for 100 ints
:
return 0;
}
Following the rules of variable definition, the data type (integer in this case) is
given first, followed by the name of the array (ageFrequency), and then the total
number of memory locations enclosed in brackets. The number of memory loca-
tions must be an integer expression greater than zero and can be given either as
a named constant (as shown in the above example) or as a literal constant (an
actual number such as 100).
Each element of an array, consisting of a particular memory location within
the group, is accessed by giving the name of the array and a position with the array
(subscript). In C++ the subscript, sometimes referred to as index, is enclosed in
square brackets. The numbering of the subscripts always begins at 0 and ends with
one less than the total number of locations. Thus the elements in the ageFrequency
array defined above are referenced as ageFrequency[0] through ageFrequency[99].
0 1 2 3 4 5 . . . . . . 97 98 99
If in our example we want ages from 1 to 100, the number of occurrences of
age 4 will be placed in subscript 3 since it is the “fourth” location in the array.
This odd way of numbering is often confusing to new programmers; however, it
quickly becomes routine.1
1
Some students actually add one more location and then ignore location 0, letting 1 be the
first location. In the above example such a process would use the following definition: int
agefrequency[101]; and use only the subscripts 1 through 100. Our examples will use
location 0. Your instructor will tell you which method to use.
Pre-lab Reading Assignment 115
Array Initialization
In our example, ageFrequency[0] keeps a count of how many 1s we read in,
ageFrequency[1] keeps count of how many 2s we read in, etc. Thus, keeping
track of how many people of a particular age exist in the data read in requires
reading each age and then adding one to the location holding the count for that
age. Of course it is important that all the counters start at 0. The following shows
the initialization of all the elements of our sample array to 0.
for (int pos = 0; pos < TOTALYEARS; pos++)
// pos acts as the array subscript
{
ageFrequency[pos] = 0;
}
A simple for loop will process the entire array, adding one to the subscript each
time through the loop. Notice that the subscript (pos) starts with 0. Why is the con-
dition pos < TOTALYEARS used instead of pos <= TOTALYEARS? Remember that
the last subscript is one less than the total number of elements in the array.
Hence the subscripts of this array go from 0 to 99.
Array Processing
Arrays are generally processed inside loops so that the input/output processing
of each element of the array can be performed with minimal statements. Our
age frequency program first needs to read in the ages from a file or from the key-
board. For each age read in, the “appropriate” element of the array (the one cor-
responding to that age) needs to be incremented by one. The following examples
show how this can be accomplished:
from a file using infile as a logical name from a keyboard with –99 as sentinel data
cout << "Please input an age from one"
<< "to 100. input -99 to stop"
<< endl;
infile >> currentAge; cin >> currentAge;
while (infile)
while (currentAge != -99)
{ {
ageFrequency[currentAge-1] = ageFrequency[currentAge-1] =
ageFrequency[currentAge-1] + 1; ageFrequency[currentAge-1] + 1;
infile >> currentAge; cout << "Please input an age from "
<< "one to 100. input -99 to stop"
<< endl;
cin >> currentAge;
} }
The while(infile) statement means that while there is more data in the file
infile, the loop will continue to process.
To read from a file or from the keyboard we prime the read,2
which means
the first value is read in before the test condition is checked to see if the loop
2
Priming the read for a while loop means having an input just before the loop condition
(just before the while) and having another one as the last statement in the loop.
4 0 14 5 0 6 1 0
116 LESSON SET 7 Arrays
should be executed. When we read an age, we increment the location in the
array that keeps track of the amount of people in the corresponding age group.
Since C++ array indices always start with 0, that location will be at the subscript
one value less than the age we read in.
0 1 2 3 4 5 . . . . . . 98 99
1 year 2 years 3 years 4 years 5 years 6 years 99 years 100 years
Each element of the array contains the number of people of a given age. The data
shown here is from a random sample run. In writing the information stored in the
array, we want to make sure that only those array elements that have values
greater than 0 are output. The following code will do this.
for (int ageCounter = 0; ageCounter < TOTALYEARS; ageCounter++)
if (ageFrequency[ageCounter] > 0)
cout << "The number of people " << ageCounter + 1 <<" years old is "
<< ageFrequency[ageCounter] << endl;
The for loop goes from 0 to one less than TOTALYEARS (0 to 99). This will test every
element of the array. If a given element has a value greater than 0, it will be
output. What does outputting ageCounter + 1 do? It gives the age we are deal-
ing with at any given time, while the value of ageFrequency[ageCounter] gives
the number of people in that age group.
The complete age frequency program will be given as one of the lab assign-
ments in Lab 7.4.
Arrays as Arguments
Arrays can be passed as arguments (parameters) to functions. Although variables
can be passed by value or reference, arrays are always passed by pointer, which
is similar to pass by reference, since it is not efficient to make a “copy” of all ele-
ments of the array. Pass by pointer is discussed further in Lesson Set 9. This
means that arrays, like pass by reference parameters, can be altered by the call-
ing function. However, they NEVER have the & symbol between the data type and
name, as pass by reference parameters do. Sample Program 7.1 illustrates how
arrays are passed as arguments to functions.
Sample Program 7.1:
// The grade average program
// This program illustrates how one-dimensional arrays are used and how
// they are passed as arguments to functions. It contains two functions.
// The first function is called to allow the user to input a set of grades and
// store them in an array. The second function is called to find the average
// grade.
#include <iostream>
using namespace std;
Pre-lab Reading Assignment 117
const int TOTALGRADES = 50; // TOTALGRADES is the maximum size of the array
// function prototypes
void getData(int array[], int& sizeOfArray);
// the procedure that will read values into the array
float findAverage(const int array[], int sizeOfArray);
// the procedure that will find the average of values
// stored in an array. The word const in front of the
// data type of the array prevents the function from
// altering the array
int main()
{
int grades[TOTALGRADES]; // defines an array that holds up to 50 ints
int numberOfGrades = 0; // the number of grades read in
float average; // the average of all grades read in
getData(grades, numberOfGrades); // getData is called to read the grades into
// the array and store how many grades there
// are in numberOfGrades
average = findAverage(grades, numberOfGrades);
cout << endl << "The average of the " << numberOfGrades
<< " grades read in is " << average << "." << endl << endl;
return 0;
}
//***********************************************************************
// getData
//
// task: This function inputs and stores data in the grades array.
// data in: none (the parameters contain no information needed by the
// getData function)
// data out: an array containing grades and the number of grades
//***********************************************************************
void getData(int array[], int& sizeOfArray)
{
int pos = 0; // array index which starts at 0
int grade; // holds each individual grade read in
cout << "Please input a grade or type -99 to stop: " << endl;
cin >> grade;
continues
118 LESSON SET 7 Arrays
while (grade != -99)
{
array[pos] = grade; // store grade read in to next array location
pos ++; // increment array index
cout << "Please input a grade or type -99 to stop: " << endl;
cin >> grade;
}
sizeOfArray = pos; // upon exiting the loop, pos holds the
// number of grades read in, which is sent
// back to the calling function
}
//****************************************************************************
// findAverage
//
// task: This function finds and returns the average of the values
//
// data in: the array containing grades and the array size
// data returned: the average of the grades contained in that array
//****************************************************************************
float findAverage (const int array[], int sizeOfArray)
{
int sum = 0; // holds the sum of all grades in the array
for (int pos = 0; pos < sizeOfArray; pos++)
{
sum = sum + array[pos];
// add grade in array position pos to sum
}
return float(sum)/sizeOfArray;
}
Notice that a set of empty brackets [ ] follows the parameter of an array which
indicates that the data type of this parameter is in fact an array. Notice also that
no brackets appear in the call to the functions that receive the array.
Since arrays in C++ are passed by pointer, which is similar to pass by reference,
it allows the original array to be altered, even though no & is used to designate
this. The getData function is thus able to store new values into the array. There
may be times when we do not want the function to alter the values of the array.
Inserting the word const before the data type on the formal parameter list pre-
vents the function from altering the array even though it is passed by pointer. This
is why in the preceding sample program the findAverage function and header
had the word const in front of the data type of the array.
float findAverage (const int array[], int sizeOfArray); // prototype
float findAverage (const int array[], int sizeOfArray) // function header
Pre-lab Reading Assignment 119
The variable numberOfGrades contains the number of elements in the array to
be processed. In most cases not every element of the array is used, which means
the size of the array given in its definition and the number of actual elements
used are rarely the same. For that reason we often pass the actual number of
ele- ments used in the array as a parameter to a procedure that uses the array.
The variable numberOfGrades is explicitly passed by reference (by using &) to
the getData function where its corresponding formal parameter is called
sizeOfArray.
Prototypes can be written without named parameters. Function headers must
include named parameters.
float findAverage (const int [], int); // prototype without named parameters
The use of brackets in function prototypes and headings can be avoided by
declaring a programmer defined data type. This is done in the global section
with a typedef statement.
Example: typedef int GradeType[50];
This declares a data type, called GradeType, that is an array containing 50 inte-
ger memory locations. Since GradeType is a data type, it can be used in defining
variables. The following defines grades as an integer array with 50 elements.
GradeType grades;
It has become a standard practice (although not a requirement) to use an upper-
case letter to begin the name of a data type. It is also helpful to include the word
“type” in the name to indicate that it is a data type and not a variable.
Sample Program 7.2 shows the revised code (in bold) of Sample Program 7.1 using
typedef.
Sample Program 7.2:
// Grade average program
// This program illustrates how one-dimensional arrays are used and how
// they are passed as arguments to functions. It contains two functions.
// The first function is called to input a set of grades and store them
// in an array. The second function is called to find the average grade.
#include <iostream>
using namespace std;
const int TOTALGRADES = 50; // maximum size of the array
// function prototypes
typedef int GradeType[TOTALGRADES]; // declaration of an integer array data type
// called GradeType
continues
120 LESSON SET 7 Arrays
void getData(GradeType array, int& sizeOfArray);
// the procedure that will read values into the array
float findAverage(const GradeType array, int sizeOfArray);
// the procedure that will find the average of values
// stored in an array. The word const in front of the
// data type of the array prevents the function from
// altering the array
int main()
{
GradeType grades; // defines an array that holds up to 50 ints
int numberOfGrades = 0; // the number of grades read in
float average; // the average of all grades read in
getData(grades, numberOfGrades);// getData is called to read the grades into
// the array and store how many grades there
// are in numberOfGrades
average = findAverage(grades, numberOfGrades);
cout << endl << "The average of the " << numberOfGrade
<< " grades read in is " << average << "." << endl << endl;
return 0;
}
//***********************************************************************
// getData
//
// task: This function inputs and stores data in the grades array.
// data in: none
// data out: an array containing grades and the number of grades
//***********************************************************************
void getData(GradeType array, int& sizeOfArray)
{
int pos = 0; // array index which starts at 0
int grade; // holds each individual grade read in
cout << "Please input a grade or type -99 to stop: " << endl;
cin >> grade;
while (grade != -99)
{
array[pos] = grade; // store grade read in to next array location
pos ++; // increment array index
cout << "Please input a grade or type -99 to stop: " << endl;
cin >> grade;
}
Pre-lab Reading Assignment 121
sizeOfArray = pos; // upon exiting the loop, pos holds the
// number of grades read in, which is sent
// back to the calling function
}
//****************************************************************************
// findAverage
//
// task: This function finds and returns the average of the values
//
// data in: the array containing grades and the array size
// data returned: the average of the grades contained in that array
//****************************************************************************
float findAverage (const GradeType array, int sizeOfArray)
{
int sum = 0; // holds the sum of all grades in the array
for (int pos = 0; pos < sizeOfArray; pos++)
{
sum = sum + array[pos];
// add grade in array position pos to sum
}
return float(sum)/sizeOfArray;
}
This method of using typedef to eliminate brackets in function prototypes and
headings is especially useful for multi-dimensional arrays such as those intro-
duced in the next section.
Two-Dimensional Arrays
Data is often contained in a table of rows and columns that can be implement-
ed with a two-dimensional array. Suppose we want to read data representing
profits (in thousands) for a particular year and quarter.
Quarter 1 Quarter 2 Quarter 3 Quarter 4
72 80 10 100
82 90 43 42
10 87 48 53
This can be done using a two-dimensional array.
Example:
const NO_OF_ROWS = 3;
const NO_OF_COLS = 4;
typedef float ProfitType[NO_OF_ROWS][NO_OF_COLS]; //declares a new data type
//which is a 2 dimensional
//array of floats
continues
122 LESSON SET 7 Arrays
int main()
{
ProfitType profit; // defines profit as a 2 dimensional array
for (int row_pos = 0; row_pos < NO_OF_ROWS; row_pos++)
for (int col_pos = 0; col_pos < NO_OF_COLS; col_pos++)
{
cout << "Please input a profit" << endl;
cin >> profit[row_pos][col_pos];
}
return 0;
}
A two dimensional array normally uses two loops (one nested inside the other)
to read, process, or output data.
How many times will the code above ask for a profit? It processes the inner
loop NO_OF_ROWS * NO_OF_COLS times, which is 12 times in this case.
Multi-Dimensional Arrays
C++ arrays can have any number of dimensions (although more than three is rarely
used). To input, process or output every item in an n-dimensional array, you
need n nested loops.
Arrays of Strings
Any variable defined as char holds only one character. To hold more than one
character in a single variable, that variable needs to be an array of characters. A
string (a group of characters that usually form meaningful names or words) is
really just an array of characters. A complete lesson on characters and strings
is given in Lesson Set 10.
PRE-LAB WRITING ASSIGNMENT
Fill-in-the-Blank Questions
1. The first subscript of every array in C++ is and the last is
less than the total number of locations in the array.
2. The amount of memory allocated to an array is based on the
and the of locations
or size of the array.
3. Array initialization and processing is usually done inside a
.
4. The statement can be used to declare an array type and
is often used for multidimensional array declarations so that when passing
arrays as parameters, brackets do not have to be used.
5. Multi-dimensional arrays are usually processed within
loops.
6. Arrays used as arguments are always passed by .
Lesson 7A 123
7. In passing an array as a parameter to a function that processes it, it is often
necessary to pass a parameter that holds the of
used in the array.
8. A string is an array of .
9. Upon exiting a loop that reads values into an array, the variable used as
a(n) to the array will contain the size of that array.
10. An n-dimensional array will be processed within nested
loops when accessing all members of the array.
LESSON 7A
LAB 7.1 Working with One-Dimensional Arrays
Retrieve program testscore.cpp from the Lab 7 folder. The code is as follows:
// This program will read in a group of test scores (positive integers from 1 to 100)
// from the keyboard and then calculate and output the average score
// as well as the highest and lowest score. There will be a maximum of 100 scores.
// PLACE YOUR NAME HERE
#include <iostream>
using namespace std;
typedef int GradeType[100]; // declares a new data type:
// an integer array of 100 elements
float findAverage (const GradeType, int); // finds average of all grades
int findHighest (const GradeType, int); // finds highest of all grades
int findLowest (const GradeType, int); // finds lowest of all grades
int main()
{
GradeType grades; // the array holding the grades.
int numberOfGrades; // the number of grades read.
int pos; // index to the array.
float avgOfGrades; // contains the average of the grades.
int highestGrade; // contains the highest grade.
int lowestGrade; // contains the lowest grade.
// Read in the values into the array
pos = 0;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
continues
124 LESSON SET 7 Arrays
cin >> grades[pos];
while (grades[pos] != -99)
{
// Fill in the code to read the grades
}
numberOfGrades = ; // Fill blank with appropriate identifier
// call to the function to find average
avgOfGrades = findAverage(grades, numberOfGrades);
cout << endl << "The average of all the grades is " << avgOfGrades << endl;
// Fill in the call to the function that calculates highest grade
cout << endl << "The highest grade is " << highestGrade << endl;
// Fill in the call to the function that calculates lowest grade
// Fill in code to write the lowest to the screen
return 0;
}
//********************************************************************************
// findAverage
//
// task: This function receives an array of integers and its size.
// It finds and returns the average of the numbers in the array
// data in: array of floating point numbers
// data returned: average of the numbers in the array
//
//********************************************************************************
float findAverage (const GradeType array, int size)
{
float sum = 0; // holds the sum of all the numbers
for (int pos = 0; pos < size; pos++)
sum = sum + array[pos];
return (sum / size); //returns the average
}
Lesson 7A 125
//****************************************************************************
// findHighest
//
// task: This function receives an array of integers and its size.
// It finds and returns the highest value of the numbers in the array
// data in: array of floating point numbers
// data returned: highest value of the numbers in the array
//
//****************************************************************************
int findHighest (const GradeType array, int size)
{
/ Fill in the code for this function
}
//****************************************************************************
// findLowest
//
// task: This function receives an array of integers and its size.
// It finds and returns the lowest value of the numbers in the array
// data in: array of floating point numbers
// data returned: lowest value of the numbers in the array
//
//****************************************************************************
int findLowest (const GradeType array, int size)
{
// Fill in the code for this function
}
Exercise 1: Complete this program as directed.
Exercise 2: Run the program with the following data: 90 45 73 62 -99
and record the output here:
Exercise 3: Modify your program from Exercise 1 so that it reads the informa-
tion from the gradfile.txt file, reading until the end of file is encoun-
tered. You will need to first retrieve this file from the Lab 7 folder and
place it in the same folder as your C++ source code. Run the program.
126 LESSON SET 7 Arrays
Lab 7.2 Strings as Arrays of Characters
Retrieve program student.cpp from the Lab 7 folder.
// This program will input an undetermined number of student names
// and a number of grades for each student. The number of grades is
// given by the user. The grades are stored in an array.
// Two functions are called for each student.
// One function will give the numeric average of their grades.
// The other function will give a letter grade to that average.
// Grades are assigned on a 10 point spread.
// 90-100 A 80-89 B 70-79 C 60-69 D Below 60 F
// PLACE YOUR NAME HERE
#include <iostream>
#include <iomanip>
using namespace std;
const int MAXGRADE = 25; // maximum number of grades per student
const int MAXCHAR = 30; // maximum characters used in a name
typedef char StringType30[MAXCHAR + 1];// character array data type for names
// having 30 characters or less.
typedef float GradeType[MAXGRADE]; // one dimensional integer array data type
float findGradeAvg(GradeType, int); // finds grade average by taking array of
// grades and number of grades as parameters
char findLetterGrade(float); // finds letter grade from average given
// to it as a parameter
int main()
{
StringType30 firstname, lastname;// two arrays of characters defined
int numOfGrades; // holds the number of grades
GradeType grades; // grades defined as a one dimensional array
float average; // holds the average of a student's grade
char moreInput; // determines if there is more input
cout << setprecision(2) << fixed << showpoint;
// Input the number of grades for each student
cout << "Please input the number of grades each student will receive." << endl
<< "This must be a number between 1 and " << MAXGRADE << " inclusive”
<< endl;
cin >> numOfGrades;
Lesson 7A 127
while (numOfGrades > MAXGRADE || numOfGrades < 1)
{
cout << "Please input the number of grades for each student." << endl
<< "This must be a number between 1 and " << MAXGRADE
<< " inclusiven";
cin >> numOfGrades;
}
// Input names and grades for each student
cout << "Please input a y if you want to input more students"
<< " any other character will stop the input" << endl;
cin >> moreInput;
while (moreInput == 'y' || moreInput == 'Y')
{
cout << "Please input the first name of the student" << endl;
cin >> firstname;
cout << endl << "Please input the last name of the student" << endl;
cin >> lastname;
for (int count = 0; count < numOfGrades; count++)
{
cout << endl << "Please input a grade" << endl;
// Fill in the input statement to place grade in the array
}
cout << firstname << " " << lastname << " has an average of ";
// Fill in code to get and print average of student to screen
// Fill in call to get and print letter grade of student to screen
cout << endl << endl << endl;
cout << "Please input a y if you want to input more students"
<< " any other character will stop the input" << endl;
cin >> moreInput;
}
return 0;
}
continues
128 LESSON SET 7 Arrays
//***********************************************************************
// findGradeAvg
//
// task: This function finds the average of the
// numbers stored in an array.
//
// data in: an array of integer numbers
// data returned: the average of all numbers in the array
//
//***********************************************************************
float findGradeAvg(GradeType array, int numGrades)
{
// Fill in the code for this function
}
//***********************************************************************
// findLetterGrade
//
// task: This function finds the letter grade for the number
// passed to it by the calling function
//
// data in: a floating point number
// data returned: the grade (based on a 10 point spread) based on the number
// passed to the function
//
//***********************************************************************
char findLetterGrade(float numGrade)
{
// Fill in the code for this function
}
Exercise 1: Complete the program by filling in the code. (Areas in bold)
Run the program with 3 grades per student using the sample data below.
Mary Brown 100 90 90
George Smith 90 30 50
Dale Barnes 80 78 82
Sally Dolittle 70 65 80
Conrad Bailer 60 58 71
You should get the following results:
Mary Brown has an average of 93.33 which gives the letter grade of A
George Smith has an average of 56.67 which gives the letter grade of F
Dale Barnes has an average of 80.00 which gives the letter grade of B
Sally Dolittle has an average of 71.67 which gives the letter grade of C
Conrad Bailer has an average of 63.00 which gives the letter grade of D
Lesson 7B 129
LESSON 7B
LAB 7.3 Working with Two-Dimensional Arrays
Look at the following table containing prices of certain items:
12.78 23.78 45.67 12.67
7.83 4.89 5.99 56.84
13.67 34.84 16.71 50.89
These numbers can be read into a two-dimensional array.
Retrieve price.cpp from the Lab 7 folder. The code is as follows:
// This program will read in prices and store them into a two-dimensional array.
// It will print those prices in a table form.
// PLACE YOUR NAME HERE
#include <iostream>
#include <iomanip>
using namespace std;
const MAXROWS = 10;
const MAXCOLS = 10;
typedef float PriceType[MAXROWS][MAXCOLS]; // creates a new data type
// of a 2D array of floats
void getPrices(PriceType, int&, int&); // gets the prices into the array
void printPrices(PriceType, int, int); // prints data as a table
int main()
{
int rowsUsed; // holds the number of rows used
int colsUsed; // holds the number of columns used
PriceType priceTable; // a 2D array holding the prices
getPrices(priceTable, rowsUsed, colsUsed); // calls getPrices to fill the array
printPrices(priceTable, rowsUsed, colsUsed);// calls printPrices to display array
return 0;
}
continues
130 LESSON SET 7 Arrays
//*******************************************************************************
// getPrices
//
// task: This procedure asks the user to input the number of rows and
// columns. It then asks the user to input (rows * columns) number of
// prices. The data is placed in the array.
// data in: none
// data out: an array filled with numbers and the number of rows
// and columns used.
//
//*******************************************************************************
void getPrices(PriceType table, int& numOfRows, int& numOfCols)
{
cout << "Please input the number of rows from 1 to "<< MAXROWS << endl;
cin >> numOfRows;
cout << "Please input the number of columns from 1 to "<< MAXCOLS << endl;
cin >> numOfCols;
for (int row = 0; row < numOfRows; row++)
{
for (int col = 0; col < numOfCols; col++)
// Fill in the code to read and store the next value in the array
}
}
//***************************************************************************
// printPrices
//
// task: This procedure prints the table of prices
// data in: an array of floating point numbers and the number of rows
// and columns used.
// data out: none
//
//****************************************************************************
void printPrices(PriceType table, int numOfRows, int numOfCols)
{
cout << fixed << showpoint << setprecision(2);
for (int row = 0; row < numOfRows; row++)
{
for (int col = 0; col < numOfCols; col++)
// Fill in the code to print the table
}
}
Lesson 7B 131
Exercise 1: Fill in the code to complete both functions getPrices and
printPrices, then run the program with the following data:
Exercise 2: Why does getPrices have the parameters numOfRows and
numOfCols passed by reference whereas printPrices has those parameters
passed by value?
Exercise 3: The following code is a function that returns the highest price in
the array. After studying it very carefully, place the function in the above
program and have the program print out the highest value.
float findHighestPrice(PriceType table, int numOfRows, int numOfCols)
// This function returns the highest price in the array
{
float highestPrice;
highestPrice = table[0][0]; // make first element the highest price
for (int row = 0; row < numOfRows; row++)
for (int col = 0; col < numOfCols; col++)
if ( highestPrice < table[row][col] )
highestPrice = table[row][col];
return highestPrice;
}
continues
132 LESSON SET 7 Arrays
NOTE: This is a value returning function. Be sure to include its prototype
in the global section.
Exercise 4: Create another value returning function that finds the lowest price
in the array and have the program print that value.
Exercise 5: After completing all the exercises above, run the program again
with the values from Exercise 1 and record your results.
Exercise 6: (Optional) Look at the following table that contains quarterly sales
transactions for three years of a small company. Each of the quarterly
transactions are integers (number of sales) and the year is also an integer.
YEAR Quarter 1 Quarter 2 Quarter 3 Quarter 4
2000 72 80 60 100
2001 82 90 43 98
2002 64 78 58 84
We could use a two-dimensional array consisting of 3 rows and 5 columns.
Even though there are only four quarters we need 5 columns (the first
column holds the year).
Retrieve quartsal.cpp from the Lab 7 folder. The code is as follows:
// This program will read in the quarterly sales transactions for a given number
// of years. It will print the year and transactions in a table format.
// It will calculate year and quarter total transactions.
// PLACE YOUR NAME HERE
#include <iostream>
#include <iomanip>
using namespace std;
const MAXYEAR = 10;
const MAXCOL = 5;
typedef int SalesType[MAXYEAR][MAXCOL]; // creates a new 2D integer data type
void getSales(SalesType, int&); // places sales figures into the array
void printSales(SalesType, int); // prints data as a table
void printTableHeading(); // prints table heading
int main()
{
int yearsUsed; // holds the number of years used
SalesType sales; // 2D array holding
// the sales transactions
getSales(sales, yearsUsed); // calls getSales to put data in array
Lesson 7B 133
printTableHeading(); // calls procedure to print the heading
printSales(sales, yearsUsed); // calls printSales to display table
return 0;
}
//*****************************************************************************
// printTableHeading
// task: This procedure prints the table heading
// data in: none
// data out: none
//
//*****************************************************************************
void printTableHeading()
{
cout << setw(30) << "YEARLY QUARTERLY SALES" << endl << endl << endl;
cout << setw(10) << "YEAR" << setw(10) << "Quarter 1"
<< setw(10) << "Quarter 2" << setw(10) << "Quarter 3"
<< setw(10) << "Quarter 4" << endl;
}
//*****************************************************************************
// getSales
//
// task: This procedure asks the user to input the number of years.
// For each of those years it asks the user to input the year
// (e.g. 2004), followed by the sales figures for each of the
// 4 quarters of that year. That data is placed in a 2D array
// data in: a 2D array of integers
// data out: the total number of years
//
//*****************************************************************************
void getSales(SalesType table, int& numOfYears)
{
cout << "Please input the number of years (1-" << MAXYEAR << ')' << endl;
cin >> numOfYears;
// Fill in the code to read and store the next value
continues
134 LESSON SET 7 Arrays
}
//*****************************************************************************
// printSales
//
// task: This procedure prints out the information in the array
// data in: an array containing sales information
// data out: none
//
//*****************************************************************************
void printSales(SalesType table, int numOfYears)
{
// Fill in the code to print the table
}
Fill in the code for both getSales and printSales.
This is similar to the price.cpp program in Exercise 1; however, the
code will be different. This is a table that contains something other than
sales in column one.
Exercise 7: Run the program so that the chart from Exercise 6 is printed.
LAB 7.4 Student Generated Code Assignments
Option 1: Write the complete age population program given in the Pre-lab
Reading Assignment.
Statement of the problem:
Given a list of ages (1 to 100) from the keyboard, the program will tally
how many people are in each age group.
Sample Run:
Lesson 7B 135
Option 2: Write a program that will input temperatures for consecutive days.
The program will store these values into an array and call a function that
will return the average of the temperatures. It will also call a function that
will return the highest temperature and a function that will return the
lowest temperature. The user will input the number of temperatures to be
read. There will be no more than 50 temperatures. Use typedef to declare
the array type. The average should be displayed to two decimal places.
Sample Run:
Option 3: Write a program that will input letter grades (A, B, C, D, F), the
number of which is input by the user (a maximum of 50 grades). The
grades will be read into an array. A function will be called five times (once
for each letter grade) and will return the total number of grades in that
category. The input to the function will include the array, number of
elements in the array and the letter category (A, B, C, D or F). The pro-
gram will print the number of grades that are A, B, etc.
136 LESSON SET 7 Arrays
Sample Run:
Exploring the Variety of Random
Documents with Different Content
dragon fly, I can tell you. I had six tiny spider-like legs, but not a sign
of wings, and when I breathed it was not as I do now, like all perfect
insects, through openings on each side of my body. I had gills, and a
tube at the end of my body brought fresh water to them. This tube
was a funny affair. It really helped me along, for when I spurted
water through it I was pushed forward. Then I had a wonderful
mouth, with a long under lip, that I could dart out and catch
anything within reach, while I did not need to move my body at all.”
“Just like frogs and toads!” cried Ruth.
“Not at all,” answered the dragon fly. “They only send out their
tongues. I send out my whole under lip. If you could only keep quiet
you would not show your ignorance so plainly.”
Once more Ruth was snubbed, and the dragon fly continued:
“In time I became a pupa.”
Ruth looked the question she dared not ask.
“I’ll explain,” said the dragon fly, amiably. “Larva—that’s what I
was at first—means mask, or something that hides you. You will find
out in time, if you do not know now, that the larva of an insect is
really a mask which hides its true form. The plural of the word is
larvæ. Now pupa, plural pupæ, means baby. It is usually the state of
sleep in which the larva lies after spinning its cocoon or cradle, but in
my case it didn’t suit at all. Dragon flies, far from sleeping in the
pupa state, seem to grow more active, and their appetites are larger.
Indeed, I will say right here, everything that came my way, and was
not too big, went into my mouth. In fact, I finally reached my limit
and burst.”
“Gracious!” cried Ruth in a shocked tone. “How did you get
yourself together again?”
“Well, you see, the whole of me didn’t burst. I simply grew too big
for my skin, or my pupa case, as the wise men call it, and it cracked
right open. I was climbing on a water plant when this happened, for
all at once I had felt a longing to leave the water and get to the open
air. My first effort was to get rid of the useless old shell which still
clung to me, but I had quite a tussle before I could do so, and
afterward I was very weak and tired. But the result was worth all my
labour, for I found myself with these four wings, and the rest of my
beautiful body, and I needed only to dry myself before sailing away
on the wind, the swiftest thing on wings, and the most renowned
mosquito killer on record. Of course, my legs aren’t arranged for
walking. Why should they be? All six of them go forward, as if they
were reaching for something, and so they are, reaching for something
to eat. Woe betide any insect I start after. I catch him every time. I
ought to, for I have thousands of eyes, and I can fly forward,
backward, or any old way. I never stop to eat my dinner either. I hold
it, and eat it as I go. Now if I had time, I would tell you how the
children of Japan make a holiday, and go out to catch us for pets, and
how they sing pretty songs to us and——”
“It is about time you stopped,” interrupted Mrs. Ant Lion. “You
have tried our patience long enough, and I mean to speak this very
minute. I’ve been told I am much like the dragon flies,” she added to
the company, “but my babies are not at all like theirs. They do not
belong to the water, and I am glad of it. I’m tired of water babies. I’ve
heard so much of them to-day. My mother had the good sense to lay
her eggs in sand, and I shall do the same. I was hungry from the
minute I was hatched, and I would have run after something to eat
right away, only I found I couldn’t. My legs were fixed in such a way I
had to walk backward.”
“Backward?” echoed Ruth.
“Yes, backward. So there was nothing to do but to dig a trap for my
dinner, and I set about it pretty quick. No one showed me how,
either. I simply used my shovel-shaped head, and before long I had
made quite a pit, broad and rounded at the top, and sloping to a
point like a funnel at the bottom. You have seen them, of course?”
“I think I have,” answered Ruth.
“They are not hard to find if you keep your eyes open,” went on the
ant lion.
“Well, as I said, I made one of these pits, and in the funnel end I
lay in wait for ants. Soon one came along, slipped over the edge, as I
expected, and tumbled right into my open mouth. Nor was she the
only one. Some were strong enough to turn, even while they were
slipping, and start to crawl up again, but I just heaped some sand on
my head and threw it at them, and down they would come. My aim
was always good, so were the ants, though I only sucked their juice.
Of course I did not leave their skins around to frighten away other
ants. I piled them on my head, and gave them a toss, which sent
them some distance away. After a time I stopped eating, and made a
cocoon. Then I went to sleep!—for many days—during which I
changed wonderfully, as any one must know who has seen ant lion
babies and now sees me. This is all of my story, and I suppose we will
hear about another tiresome water baby.”
“‘I MADE ONE OF THESE PITS AND IN
THE FUNNEL END I LAY IN WAIT FOR
ANTS’”
“You shall hear about a water baby,” replied Mrs. Caddice Fly,
waving her antennæ by way of salute, “but tiresome will do for your
own homely children. I will begin by saying that, with the accidents
of life, it is a wonder that any of us are here. When we caddice flies
were hatched we were soft, white, six-footed babies. We were called
worms, though we were not worms. Think of it! Soft bodied, with not
very strong legs, white, and living at the bottom of the pond. Could
anything be worse? No wonder we seemed to do nothing at first but
try to get away from things that wanted to eat us. I tell you, pond life
is most exciting. After a while the front part of our bodies and our
heads began to turn brown, and, as the rest of us was white, and
seemed likely to stay so, we all decided to make a case or house to
cover our white part. So we set to work and of bits of sticks, tiny
stones, and broken shells, glued together with silk from our own
bodies, we made these cases. True, many of us went down the throat
of Belostoma, the giant water bug, before we had finished, but those
of us who didn’t crawled into our little houses, locking ourselves in
by two strong hooks which grew at the end of our bodies. We could
move about, but of course we carried our houses with us and——”
“How ridiculous!” said Mrs. Ant Lion. “Why didn’t you stay still?”
“Because we didn’t wish to,” answered the caddice fly. “We had to
eat, and we had to get away from those who wished to eat us. At last
we went to sleep, after first spinning a veil of silk over our front and
back doors. I can’t answer for the others, but when I awoke I tore
open my silken door, threw aside my pupa skin, and found I had
wings. Since then I have had a new life, but even that has its enemies,
and one never knows what will happen.”
With which doleful saying Mrs. Caddice Fly sailed away to the
pond to lay some eggs among the water plants.
“Dear me,” said Mrs. Lacewing, “we seem to need something
cheerful after that. I am glad I never lived in the water, if it makes
one so blue. Now I shall tell you what my babies will do, not what I
have done. Of course it is the same thing, but it is looking forward
rather than to the past. After this meeting is over I shall lay some
eggs, on just what plant I haven’t yet decided, but it will be in the
midst of a herd of aphides. Be sure of that. Aphides are plant lice,”
she explained, seeing the question in Ruth’s eyes. “You will learn
more of them later. Now as to the way I shall lay my eggs: First, from
the tip of my body I shall drop a thick gummy fluid, and draw it out
into a long, stiff, upright thread, and upon the end of this thread I
shall fasten an egg. I shall lay a number of eggs in this way, each on
its own pole, so to speak. Some people may think my way odd, but it
is very wise. A lacewing knows her children. They are not beautiful.
Such short-legged, spindle-shaped things couldn’t be pretty, but they
are sturdy, and they have an endless appetite.”
“I should think they would feel lonely on those ridiculous poles,”
said Mrs. Ant Lion.
“Not at all. They are not there long enough to feel lonely. They are
in too great a hurry for dinner. They are hungry, with a big H. Now
just suppose I should lay my eggs as the rest of you do, ever so many
together, what do you think would happen? I will tell you in a few
words. The dear child who came out first would eat all his unhatched
brothers and sisters. He doesn’t, only because he can’t reach them.”
“It’s a wonder he doesn’t eat his pole,” said Ruth, her face showing
what she thought of such babies.
“Yes, it is,” agreed Mrs. Lacewing, “but, strange to say, he doesn’t
seem to care for it. Indeed, he leaves it as quickly as he can, and goes
hunting. Of course he needn’t hunt far, for he is in the midst of
aphides. Every mother looks out for that, and really it is quite a
pleasure to see him suck the juice from aphid after aphid, holding
each one high in the air in his own funny way. So you can see why
lacewing babies are friends to the farmer and the fruit grower, for
aphides kill plants and trees, and young lacewings kill aphides. They
can eat and eat and eat, and never grow tired of aphides. Indeed,
they really deserve their name—aphislion. When they do stop eating
it is to fall into their long sleep, but first they weave a cocoon as
beautiful as a seed pearl, in which they change into a most lovely
creature—one like me. Now our meeting is adjourned, and I hope a
certain person has learned a few things.”
“Oh, ever and ever so many, thank you,” answered Ruth gratefully.
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual
R
CHAPTER VI
RUTH GOES TO A CONCERT
Oh, sweet and tiny cousins that belong,
One to the fields, the other to the hearth,
Both have your sunshine.
—Leigh Hunt.
uth and Belinda were crossing the meadow, when a big
grasshopper made a flying leap, and landed on Belinda’s head.
“Do excuse me,” he said; “I missed my aim. No one hurt, I hope, or
frightened?”
“Oh, no,” answered Ruth. “Belinda is real sensible; she isn’t afraid
of anything, and I am just as glad—as glad—to see you. Maybe you
will——”
Ruth hesitated, hoping he would know what she meant to say. She
was sure he could tell her a great many things, if only he would. He
was so polite and nice; besides, he looked very wise.
“I suppose you’re going to the concert,” said Mr. Grasshopper,
after waiting a second for Ruth to finish her sentence.
“Concert?” she repeated, opening her eyes wide. “What concert?”
“Why the Straightwings’ Concert. They give one every sunny day in
Summer. Didn’t you know that? Dear me, where were you hatched
and where have you been living since? Well, why do you stare at me
so? Don’t you like my looks?”
“Oh, yes,” Ruth hastened to answer. “You look very nice—
something like a little old man.”
“I’ve heard that before, and there’s a story about it. Shall I tell it?”
“Yes, please; I just love stories.”
“Very well. Once upon a time, long, long ago, there lived in Greece
a beautiful young man named Tithonus. Now it chanced that
Tithonus loved Aurora, the Goddess of the Dawn.”
“Greece?” said Ruth. “Why, that’s where Arachna lived, the one
who turned into a spider, you know?”
“Do you want to hear my story or don’t you?” asked Mr.
Grasshopper, sharply.
“I do want to hear it. I really do.”
“Very well, then, don’t interrupt me again. As I was saying,
Tithonus loved Aurora, and every morning he would lie in the
meadow and wait for her coming. Then the fair goddess would give
him her sweetest smiles. But one day Tithonus grew pale and ill, and
all the love of Aurora could not make him well again. ‘Alas!’ he cried,
‘I am mortal, and I must die.’ ‘Nay,’ answered Aurora, ‘you shall not
die, for I will win for you the gift of the gods.’ And, speeding to the
mighty Jupiter, she begged that Tithonus might be as a god, and live
forever. So for a while they were happy together, but as the years
passed Tithonus grew old and bent, for Aurora had forgotten to ask
that he might always be young. Grieving much, Tithonus lay under
the shadow of the trees and sighed through the long days.”
“‘Ah, my Tithonus,’ whispered Aurora, ‘I love you too well to see
you thus unhappy. No more shall you be sad or bend beneath an old
man’s weakness, but, as a child of the meadow, happy and free, you
shall sing and dance through the golden hours.’ In that moment
Tithonus became a grasshopper, and ever since then his descendants
have danced and sung in the sunshine. That’s the end of the story. I
might have made it twice as long, but Summer is so short, and I want
to dance.”
“It was a very nice story,” said Ruth, “but do you really dance?”
“Of course, our kind of dancing.”
“But don’t you do lots of other things too?”
“Yes; we give concerts, and we eat. We are hatched with big
appetites, and a strong pair of jaws, and we start right in to use them
on the tender grasses around us. We only follow our instincts,
though men call it doing damage. You eat, don’t you?”
“Why, yes, but I don’t eat grass, you know.”
“Because it isn’t your food. You see it’s this way: In the kingdom of
nature all creatures have a certain work to do, and each is exactly
fitted for its place, for all are governed by laws more wonderful than
any man has made. Not that I wish to speak lightly of man, he is
good enough in his place, but he is apt to think himself the whole
thing, and he isn’t. Maybe he doesn’t know that for every human
creature on earth there are millions of plants and animals.”
“Oh,” said Ruth, “really and truly?”
“Really and truly. You couldn’t begin to count them, and do you
know, if the earth was to grow quite bare, with only one living plant
left on it, the seeds from that one plant could make it green again in a
very few years. But if certain insects were left without other creatures
to eat and keep them down, the poor old earth would soon be bare
once more. So you see there must be laws to fix all these things.
Nature balances one set of creatures against the other, so there will
not be too many of any kind.”
Ruth had listened in open-eyed astonishment. Surely this was a
very wise grasshopper.
“You know a great deal,” she managed to say at last.
“Yes, I do,” was the answer. “I heard two men say the things I’ve
just told you. They were walking across this meadow, and I listened
and remembered. You see, I believe in learning even from men. But
do listen to the concert—we are right in the middle of it.”
THE WISE
GRASSHOPPE
R
They certainly were in the middle of it. The zip, zip, zip, zee-e-ee-e
of the meadow grasshoppers seemed to come from every part of the
sunny field, while the shorthorns, or flying locusts, were gently
fiddling under the grass blades, their wing covers serving for strings,
and their thighs as fiddle bows, and the field crickets, not to be
outdone, were scraping away with the finely notched veins of the fore
wings upon their hind wings.
The longhorns were also there, some in green, others in brown or
gray, all drumming away on the drum heads set in their fore wings.
“You would hear katydid too,” said Mr. Grasshopper, “only he
refuses to sing in the day. He hides under the leaves of the trees
while it is light, and comes out at night. If you think me wise, I don’t
know what you would say of him. He is such a solemn-looking chap,
always dressed in green, and his wing covers are like leaves. You
might think him afraid if you saw him wave his long antennæ, but he
isn’t. He is curious, that’s all. It is a high sort of curiosity, too, like
mine—a wish to learn. I suppose you know we don’t make our music
with our mouths?” he asked suddenly. “Well, that is something,” he
added, as Ruth nodded “Yes.”
“I sing with the upper part of my wing covers, but my cousins, the
shorthorns, sing with their hind legs. Why do you laugh? Aren’t legs
as good to sing with as anything else?”
“I—I suppose so,” said Ruth. “It sounds funny, because I am not
used to that kind of singing.”
“Just it. Now I shall tell you a few more facts about us. We belong
to the order of the Straightwings, or the Orthoptera, as the wise men
call it.”
“Will you please tell me what that means?” asked Ruth. “Do all
insects belong to something ending in tera? Most everything I have
talked to does except toads and spiders.”
“And they are not insects,” said Mr. Grasshopper. “Not even the
spiders. The word insect means cut into parts, and all insects have
three parts, a head, and behind that the thorax or chest, and the
abdomen. Then, too, they always have six jointed legs. Now maybe
you have noticed that spiders are not built on this plan? There are
only two parts of them. The head and thorax are in one. It is called
the cephalothorax. I’d feel dreadfully carrying such a thing around
with me, but the spiders do not seem to mind it. Their other part is
their abdomen. I heard a little boy say it was like a squashy bag; and
between ourselves that is about what it is. Of course you know that
spiders have eight legs and that alone would settle the question. True
insects never have but six. Now as to the orders: All insects are
divided into groups, and it is something about the wings which gives
them their names. That is why they all end in ptera, because ptera
comes from pteron, a word which means wing. It isn’t an English
word, you know, but is taken from a language called Greek.”
Ruth listened very patiently. If she had heard all this in school it
would have seemed very dry, but when a grasshopper is telling you
things it is of course quite different.
“But I am sure I can never remember it all,” she said.
“Ah, yes, you can. Remembering is easy if you only practise it.”
“Why, that’s like the White Queen,” cried Ruth. “She practised
believing things till she could believe six impossible things at once,
before breakfast.”
“I don’t know the person,” said the grasshopper.
“She lived in the Looking Glass Country,” began Ruth, but Mr.
Grasshopper was not listening.
“You have met the Diptera, or Two Wings,” he said. “That’s easy.
Then you’ve met the Neuroptera, or Nerve Wings. That’s easy too.
And now you have met the Orthoptera, or Straightwings, meaning
me, and if I’m not easy, I should like to know who is. You see our
wings are——”
“Wings?” said Ruth in surprise.
“Of course. Look here,” and opening his straight wing covers, Mr.
Grasshopper showed as nice a pair of wings as one could wish to
possess. “Not all of us have wings,” he added, folding his own away,
“but those of us who have not live under stones. Our order includes
graspers, walkers, runners, and jumpers. Not all are musicians. The
graspers live only in hot countries. Maybe you have seen the picture
of one of them—the praying mantis he is called, just because he holds
up his front legs as if he were praying. But it isn’t prayers he is
saying. He is waiting for some insect to come near enough so he may
grab and eat it. That will do for him. Next come the walkers. The
walking stick is one, and he isn’t a good walker either, but the stick
part of the name fits him. He is dreadfully thin. There is one on that
twig now, and he looks so much like the twig you can scarcely tell
which is which.”
“Why, so he does,” said Ruth, poking her finger at the twig Mr.
Grasshopper pointed out. “Isn’t he funny?”
“Indeed,” grumbled the walking stick. “Maybe you think it polite to
come staring at a fellow, and sticking your finger at him, and then
call him funny, but I don’t. I want to look like a twig. That’s why I am
holding myself so stiff. I have a cousin in the Tropics who has wings
just like leaves.”
“Yes,” added the grasshopper, “and his wife is so careless she just
drops her eggs from the tree to the ground and never cares how they
fall.”
“Well, if that suits her no one else need object,” snapped the
walking stick. “I believe in each one minding his own business.”
“An excellent idea,” said Mr. Grasshopper. “Now let me see, where
was I? Oh! the runners; but you’ll excuse me, I will not speak of them
at all. They include croton bugs and cock roaches, and it is quite
enough to mention their names. With the jumpers it is different.
They are the most important members of the order. I’m a jumper, I
am also a true grasshopper. You can tell that by my long slender
antennæ, longer than my body. For that reason I am called a
longhorn, but my antennæ are really not horns.”
“I don’t see how any one could call them horns,” said Ruth.
“No more do I, but some people have queer ideas about things.
Well, I don’t care much. There is my mate over there. Do you notice
the sword-shaped ovipositor at the end of her body? She uses it to
make holes in the ground and also to lay her eggs in the hole after it
is finished. Yes, she is very careful. Her eggs stay there all Winter,
and hatch in the Spring, not into grubs or caterpillars, or anything of
that sort. They will be grasshoppers, small, it is true, and without
wings, but true grasshoppers, which need only to grow and change
their skins to be just like us. And I’m sure we have nothing to be
ashamed of. We have plenty of eyes, six legs, and ears on our
forelegs, not like you people who have queer things on the sides of
your heads. Such a place for hearing! but every one to his taste. Well,
to go on, we have wing covers, and lovely wings under them, a head
full of lips and jaws, and a jump that is a jump. What more could one
wish? Do you know what our family name is?”
Ruth didn’t know they had a family name, so of course she could
not say what it was.
“It is Locustidae,” said Mr. Grasshopper, answering his own
question. “Funny too, for there isn’t a locust among us. Locusts are
the shorthorned grasshoppers—that is, their antennæ are shorter
than ours. They are cousins, but we are not proud of them. They are
not very good.”
“No one is asking you to be proud,” said a grasshopper, jumping
from a nearby grass blade. She had a plump gray and green body, red
legs, and brown wings, with a broad lemon-yellow band.
“What’s the matter with me?” she demanded. “I guess you don’t
know what you are talking about. It’s the Western fellow that is so
bad. We Eastern locusts are different.”
“Well, I suppose you are,” agreed the longhorn. “I know the
Western locusts travel in swarms and eat every green thing in sight.
They are called the hateful grasshoppers.”
“No one can say that our family has ever been called hateful or
anything like it,” said a little cricket with a merry chirp. “We are
considered very cheery company, and one of the sweetest stories ever
written was about our English cousin, the house cricket.”
“I am sure you mean ‘The Cricket on the Hearth,’” said Ruth. “It is
a lovely story, and I think crickets are just dear. Are you a house
cricket too?”
“No, I belong to the fields, and I sing all day. Sometimes I go into
the house when Winter comes and sing by the fire at night, but my
real home is in the earth. I dig a hole in a sunny spot and Mrs.
Cricket lays her eggs at the bottom, and fastens them to the ground
with a kind of glue. Sometimes there are three hundred of them, and
you can imagine what a lively family they are when they hatch.”
“I should like to see them,” said Ruth, for it was quite impossible
for her to imagine so many baby crickets together.
“Well, it is a sight, I assure you,” answered the little cricket. “Did
you ever come across my cousin the mole cricket? She is very large
and quite clever. She makes a wonderful home with many halls
around her nest. She is always on guard too so that no one may touch
her precious eggs. Then I have another cousin, who doesn’t dress in
brown like me, but is all white. He lives on trees and shrubs and
doesn’t eat leaves and grass as we do. He prefers aphides. You can
hear him making music on Summer evenings. We crickets seldom
fly. We——”
The sentence was not finished, for just then a long droning note
grew on the air, increasing in volume, until it rose above the meadow
chorus.
“Oh!” cried Ruth, spying a creature with great bulging eyes and
beautiful, transparent wings, glittering with rainbow tints, “There’s a
locust! Isn’t he beautiful, Belinda? Maybe he will tell us some things.
Oh, Belinda, aren’t we in luck?”
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual
“A
CHAPTER VII
RUTH MEETS MANY SORTS AND
CONDITIONS
The shrill cicadas, people of the pine,
Make their summer lives one ceaseless song.
—Byron.
locust, indeed,” said the newcomer, and Ruth could see plainly
that he was not pleased. “It does seem to me you should know
better than that. Can’t you see I have a sucking beak and not a biting
one, like the grasshopper tribe? Besides, my music isn’t made like
theirs. No faint, fiddly squeak for me, but a fine sound of drums.”
“I think I’ll move on,” said Mr. Grasshopper, and Ruth could see
that he was quite angry. She turned to look at the cricket, but he was
far across the field, fiddling to his mate.
“I wish you wouldn’t go,” she said to the grasshopper. “You have
been so nice to me and I have learned ever so much from you.”
“Oh, I dare say,” was the answer. “More than you will learn from
some people I could mention, but I really must leave you. My mate
wants me.” And a flying leap carried him quite away.
“There, we are rid of the old grandfather,” said the cicada, “and
now what can I do for you?”
“Tell me your real name if it is not locust,” answered Ruth.
“It certainly is not locust. I’ve been called a harvest fly, though I
am not a fly either. I’m a cicada, and nothing else, and I belong to the
order of bugs.”
“And what kind of tera is it?”
“Tera?” repeated the cicada, looking at her with his big eyes. “Oh,
yes, yes, I understand. You mean our scientific name. It is
Hemiptera, meaning half-wings. I know we have some objectionable
members, but I don’t have to associate with them, and I rarely
mention their names. I have a cousin who lives in the ground
seventeen years. Think of it! Of course he is only a grub and doesn’t
care for air and sun. I lived there two years myself, but I was a grub
also then. You see my mother put her eggs in the twig of a tree, and
when I came out of one of them I wanted to get to the ground more
than I wanted anything else, so I just crawled out to the end of the
branch and let go. Down I went, over and over, to the ground, where
I soon bored my way in, and began to suck the juices of the roots
about me. I liked it then, but I couldn’t stand it now. Of course the
moles were trying. They were always hungry and we were one of the
things they liked for dinner. One day something seemed to call me to
the world of light, and I came out a changed being—in fact, the
beautiful creature you see before you now. Perhaps you do not know
how much attention we have attracted? In all ages poets have sung of
us, even from the days of Homer. Maybe you will not believe me, but
the early Greeks thought us almost divine, and when Homer wished
to say the nicest things about his orators he compared them to
cicadas. A while ago I told you we were sometimes called harvest
flies. We have also been given the name Lyremen. Shall I tell you
why?”
“A story!” cried Ruth, clapping her hands. “Oh, yes, please tell it!”
“Very well. Once upon a time, ages ago, a young Grecian player
was competing for a prize, and so sweet was the music he drew from
his lyre that all who heard it felt he must surely win. But alas! when
he was nearly finished one of his strings snapped, and, with a sad
heart, he thought that all his hope was gone. Not so, however, for a
cicada, drawn from the woods by the sweet sounds, had perched
upon the lyre and when the musician’s trembling fingers touched the
broken string it gave forth a note that was clear and true. Thus again
and again the cicada answered in tones that were sweet and full.
When the happy player realized that the cicada had won the prize for
him, he was so filled with gratitude that he caused a full figure of
himself to be carved in marble, and in his hand a lyre with a cicada
perched upon it. Now wouldn’t you be proud if your family had such
a nice story about them?”
“I’m sure it is very nice,” agreed Ruth.
“Yet I’m not one to brag,” added the cicada, “and I am never
ashamed to say I’m a bug. Now if you will come with me to the pond
I will show you some of my cousins. They are very interesting.”
And with a whiz the gauzy-winged fellow darted up into the
sunshine, and Ruth, following him across the meadow, could only
hug Belinda in a rapture of expectation, and whisper in a low voice:
“Aren’t we in luck, Belinda—just the best kind of luck?”
They had gone only a little way, however, when a mole pushed his
strong little snout above the ground.
“Gracious! what a noise,” he said. “If I had had a chance when you
were a baby you wouldn’t be here now to disturb quiet-minded
people.”
Ruth jumped. She thought the mole meant he would have eaten
her. Then she laughed. “Of course it was the cicada he was talking
to,” but the cicada didn’t mind.
“I know that very well,” he answered, cheerfully, “but you didn’t
get me. That makes all the difference, and now you can’t.”
“Well, nobody wants you now. You would be mighty dry eating,
but when you were a grub, oh, my! so fat and juicy, like all the other
grubs and slugs and worms. I eat you all. Yet what thanks do I get
from man for doing away with so many of his enemies? Complaints,
nothing but complaints, and just because I raise a few ridges in the
ground. I can’t help that. When I move underground I push the earth
before me, and, as it has to go somewhere, it rises up.”
“What do you push with?” asked Ruth, sitting down in front of the
mole.
“With my snout and forepaws,” he answered, “what else? The
muscle which moves my head is very powerful, and you can see how
broad my forepaws are, and, also, that they turn outward. They help
to throw back the earth as I make my way forward. I have ever so
many sharp little teeth, too, and my fur lies smooth in all directions,
so it never rumples and——”
“Do come on,” interrupted the cicada; “that fellow isn’t
interesting.”
“That’s so,” said a thin little voice, as an earthworm cautiously
lifted his head from the ground. “Has he gone?” he asked anxiously.
“He’d eat me sooner than wink if he saw me. It is warm and damp
this morning, that is why I am so near the surface. I don’t like dry or
cold weather. My house——”
“Have you a house?”
Ruth had turned upon him in a second, full of questions as usual.
“Certainly I have a house. It is a row of halls, lined with glue from
my own body. The walls are so firm they can’t fall in. Underground is
really a delightful place to live, snug and soft, cool in Summer, warm
in Winter. Lots to see, too. All the creeping, twining roots and stems
reaching out for food, storing it away, or sending it up as sap to the
leaves. The seeds waking up in the Spring, and hosts of meadow and
wood people wrapped in egg and cocoon, who spend their baby days
there. Quite a little world, I assure you. Of course I can’t see any of
these things. I have no eyes.”
“Oh!” said Ruth, “how dreadful!”
“No, it is just as well. If I had eyes I might get earth in them. I go
through the ground so much.”
“But isn’t that awful hard work?” asked Ruth, shutting her eyes to
realize what having no eyes might mean.
“It isn’t hard when one has a nice set of bristles, as I have to help
me along.” The earthworm was one who saw the best side of
everything. “I am made up of more than a hundred rings,” he went
on, “and on each are small stiff hair-like bristles so, though I have
neither eyes, ears, hands, nor feet, I am quite independent. I can
move very fast, and the slime that covers me keeps the earth from
sticking to me. Do you know I am the only jointed animal that has
red blood? It is so. I do no harm, either, to growing things, and I help
to build the world. My tunnels let air into the ground and help to
keep it loose. I also bring up rich soil from below, and lay it on the
surface. I also——”
“Well, that’s enough,” interrupted the cicada, moving his wings
impatiently. “I thought you wanted to see my relations?” he added to
Ruth.
“So I do,” answered Ruth. “Where are they?”
“There are a number of them right in this meadow, though you
would never think it, to look at them. They are not at all like me. See
that white froth clinging to those grass stems? A cousin made that.
Of the sap of the plant too. If you look, you will find her in the midst
of it. She is green and speckled and very small. Then there are the
tree hoppers, as funny in shape as brownies, and the leaf hoppers.
They are all my cousins. The aphides too. Of course you know the
aphides?”
“I believe they were the things Mrs. Lacewing told me I should
learn about later,” said Ruth, with sudden remembrance.
“Very likely. Mrs. Lacewing’s children should know about them.
The aphides are very bad, though they are so very tiny. But what they
lack in size they make up in numbers. Really there are millions of
them. They are not travellers, either, but stay just where they are
hatched, and suck, suck, suck. In that way they kill many plants, for
it is the sap of the plant, its life juice, which serves them for food.
They eat so much of this that their bodies can’t hold it all, and what
they don’t need is given off as honey dew. The ants like this honey so
well that to get it they take good care of the aphides. But there are
some aphides which do not give off honey dew. Do you see this white
stuff on the alder bushes?”
“Yes. I’ve often seen it before, too. It looks like soft white fringe.”
“Well, it isn’t. It is a lot of aphides, each with a tuft of wool on its
body, and a beak fast stuck in the alder stem.”
They had now reached the pond, which lay smiling in the
sunshine.
“It would be so pretty,” said Ruth, throwing herself down on the
grass, “if it wasn’t for the horrid, green, oozy stuff all over it.”
“Horrid, green, oozy stuff?” repeated the cicada. “Child, you don’t
know what you are talking about. That green stuff is made up of tiny
green plants more than you could count. Each has a rootlet hanging
down like a silver thread and leaves almost too small to be called so.
They are green though and they do the mighty work of all green
leaves, for, besides shading the pond world from the hot rays of the
sun, they make for the many inhabitants the life-giving oxygen
without which they would die. And I want to tell you something
more: In that duckweed—for what you call green, oozy stuff is
duckweed—there are millions of tiny living things too small to be
seen by the eye except with the aid of a microscope.”
Ruth looked quite as astonished as the cicada meant she should be.
“You have a great deal to learn, I assure you. Maybe you haven’t
thought of the pond as a world, but just see what a busy place it is.”
Ruth looked and agreed with the cicada. Dragon flies were darting
here, there, and everywhere; frogs, with their heads out of the water,
seemed to be admiring the scenery when they were not swallowing
air or whatever else came in their way; glancing minnows and bright-
eyed tadpoles played amongst the swaying water weeds; even the
wrigglers were there, standing on their heads in their own funny
way; and the water striders, skating after their own queer fashion.
Yes, it was a busy place.
A party of whirligig beetles came dashing by, circling, curving,
spinning, and making such a disturbance that a backswimmer lost
his patience and told them to be quiet.
They didn’t like that at all, so they threw about him a very
disagreeable milky fluid which made the backswimmer dive for the
bottom in a hurry.
“That settled him,” said one of the whirligigs. “Hello! friend
Skipper Jack,” he called to a water strider, “what are you doing?”
“Skating, of course,” answered the water strider. “There, they are
gone,” he added, to the cicada, “and I am glad of it. They are
nuisances.”
“You are right,” agreed the cicada.
“I am glad they don’t belong to our order.”
“Don’t they?” asked Ruth. “I think they are awfully funny.”
“Funny or not, they are beetles,” answered the water strider. “You
had better use your eyes. Do you know why I can skate and not get
my feet wet? No, of course you don’t, and yet it is as plain as the nose
on your face. I have a coat of hairs on the under side of my body.
That’s why. I spend my time on the surface of the water, for my
dinner is right here. Plenty of gnats, insect eggs, and other eatables.
Then if I wish I can spring up in the air for the things that fly. My
Winters I spend under water, but for other seasons give me the
surface.”
“And I like the bottom best,” said a water boatman, showing
himself quite suddenly, his air-covered body glittering like silver
armour.
“Another cousin,” whispered the cicada in Ruth’s ear. “He is called
the water cicada, as well as water boatman.”
“He looks more like a boat than he does like you,” said Ruth.
“My body is boat-shaped,” spoke up the boatman; “and see my
hind legs; they really are like oars, aren’t they?”
“I am wondering what brought you to the surface,” said the cicada.
“Why, I let go my hold on that old water weed, and you know the
air that covers my body makes it lighter than the water and unless I
cling to something I naturally rise. It is inconvenient, for I do not
need to come to the surface for air. I can breathe the same air over
and over, because I know how to purify it.”
“How do you do it?” asked Ruth. Surely these insects were
wonderfully clever.
“Oh, I simply hang to something with my front legs, while I move
my back ones just as I do in swimming, and that makes a current of
water pass over my coat of air and purify it. That fellow swimming on
his back over there is obliged to come to the surface every little while.
He carries air down in a bubble under his wings.”
“Do you mean me?” asked the backswimmer, making a sudden
leap in the air, and flying away.
“Gracious!” cried Ruth in surprise. “I didn’t know he could fly.”
“There’s a good deal you don’t know,” replied the water boatman, a
remark Ruth had heard before. “I can fly too,” and he also spread his
wings and was off.
“Well,” said the cicada, “I guess we might as well be off too. There
seems to be no one in sight to interest us.”
“What about cousin Belostoma?” asked a sort of muffled voice, as a
great pair of bulging eyes showed themselves above the water, and
out came the giant water bug as big as life.
“I’ve just had my dinner,” he said. “It really is funny to see how
everything hides when Belostoma shows his face. My wife is the only
one who doesn’t seem to be afraid of me and she—well, she’s a terror
and no mistake.”
“Why, what’s the matter now?” asked the cicada.
“And what has happened to your back?” added Ruth, with eager
curiosity.
“My wife’s happened, that’s what,” answered Belostoma in a
doleful tone. “She laid her eggs a while ago and glued every blessed
one to my back. It is nothing to laugh at either. There’s no joke in
being a walking incubator. Well, I must be going now. It is dinner
time.”
“I thought you just had your dinner,” said Ruth.
“Yes, but it’s time again. It is always time. How silly you are.”
“I must go too,” said the cicada, “but it isn’t dinner that calls me. I
feel sure my mate is longing for some music and I’m off to give her a
bit. See you later.”
And, spreading his wings, the cicada flew away, beating his drums
as he went.
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual
S
CHAPTER VIII
MRS. TUMBLE BUG AND OTHERS
Their wings with azure green
And purple glossed.
—Anna L. Barbauld.
omething exciting was going on. Ruth could not tell just what it
was at first. She could only watch and wonder. Then her eyes
grew large and bright. Surely some fairy’s wand had touched the old
orchard, for suddenly it seemed alive with beetles—big beetles and
little beetles; beetles in sober colourings, and beetles gleaming with
all the tints of the rainbow. Ruth had never dreamed that there could
be so many of them or that they were so beautiful.
The gorgeously coloured, graceful tigers attracted her first, though
she didn’t know their name.
“Oh,” she cried, “how lovely!”
“And how strange,” added a voice just above her head, “how very
strange, their children should be so homely.”
“What’s that?” asked one of the tigers, a metallic green fellow, with
purple lights, and two pale yellow dots on the edge of each wing
cover. “Our children not so beautiful as we are, did you say? Of
course, they are not; a fat grub couldn’t be, you know. But let me tell
you, there are few things as smart as a tiger beetle baby. I say,” he
added, looking full at Ruth, “have you ever seen the hole he digs? It is
often a foot deep, while he is less than an inch long. He has only his
jaws and fore legs to work with too. Yet he piles the earth on his flat
head as if it were the easiest thing in the world, and then, climbing to
the top, he throws it off, and is ready for another load.”
“I suppose he digs a hole to catch things,” said Ruth, “like the ant
lion, and does he stay at the bottom and——”
“No, he doesn’t stay at the bottom. He watches near the top of his
hole for his dinner, hanging on by a pair of hooks which grow out of a
hump on his back. He always goes to the bottom to eat his dinner,
though; he seems to like privacy. Yes, we are a fierce family from the
beginning, for we grown tigers can catch our prey either running or
flying, and we usually manage to get it, too. But, then, farmers need
not complain of us, for we never eat plants, and that is more than can
be said of many here.”
“Such taste,” said a cloaked, knotty horn, holding herself in a
position that showed off her changeable blue and green dress, and
her short yellow cape.
But the tiger did not answer. He was off after his dinner. Several
tree borers, however, nodded their heads in agreement.
“I believe in a vegetable diet myself,” said Mrs. Sawyer, who wore
as usual her dress of brown and gray. “It is just such people as the
tigers who make things like that necessary in a respectable meeting,”
and as she spoke she waved her very long antennæ toward a big sign
which read:
“THE AUDIENCE ARE REQUESTED NOT TO EAT EACH OTHER DURING THE
MEETING”
“I am glad to say I am not one of that kind. I wonder if any one of
you know why the members of our family are called sawyers. Perhaps
I had better tell you: It is because our children saw into the trunks of
evergreen trees, and sometimes they make holes large enough to kill
the trees. Smart, isn’t it, for a baby?”
“But it doesn’t seem to be very nice,” began Ruth. Then she
stopped, for Mrs. Sawyer was looking at her and the borers were
nodding their heads again.
“Our children do not saw,” said the borers, “but they do bore, and
it is pretty much the same thing for the tree.”
“My friends,” broke in a very solemn voice.
Every beetle stopped talking, and Ruth jumped to her feet, then
flopped down on the grass again, waiting for what was coming.
The speaker, a large, clean-looking beetle, had just flown to a twig
in the very middle of the meeting. He was black in colour, well
sprinkled above and below with pale straw yellow in dots and points,
but the queer thing about him was the two oval velvety black spots,
each with a narrow line of straw colour around it, on his thorax. They
were like great eyes, and made him look very wise.
“He is the eyed-elater,” whispered Mrs. Sawyer to Ruth. “There he
is speaking again.”
“My friends,” the big beetle was saying in tones as solemn, as
before, “the important thing in any meeting is to keep to the main
issue.”
“The main issue?” said the goldsmith beetle, a beautiful little
creature with wing covers of golden yellow, and a body of metallic
green covered with white, woolly fuzz. “What is the main issue?”
“Dinner,” replied the tiger beetle, returning to his old place. “If it
isn’t breakfast or supper.”
“No, my friend,” said the eyed-elater, with a grave glance, “the
main issue is——”
Then he stopped and fixed his two real eyes and the two spots
which looked like eyes on some small beetles which were leaping in
the air, turning somersaults, and making quite a noise.
“Will you be still?” he said in his sternest voice.
“How foolish,” said Mrs. Sawyer, “to expect click beetles to be
still!”
But Ruth was all curiosity.
“I’ve seen you before,” she said, going closer and touching one of
the funny little fellows.
Suddenly it curled up its legs, dropped as if shot, then lay like one
dead.
“Here, here!” called the elater. “No more of that! We know all
about your tricks!”
“All right,” said the would-be dead one, and he gave a click,
popped into the air several inches, and came down on his back.
“That won’t do at all,” he said, and, clicking and popping once
more, he came down on his feet.
“There,” he added, “you need to have patience with click beetles.
You ought to know that, friend elater, for you are one of us.”
“Well, I’m bigger, and not so foolish, and my children are not so
harmful as yours. Think of being a parent of those dreadful wire
worms! That is what you click beetles are, and you know the farmer
hasn’t a worse enemy. Now we must get back to the main issue.”
“Back?” said Mrs. Sawyer. “Were we ever there to begin with? You
can’t scare me,” she added, “no matter how hard you stare. You
haven’t any more eyes than the rest of us. Those two spots are not
real eyes, and you know it.”
“The main issue,” repeated the elater in a very loud voice, “is, What
makes us beetles?”
“That’s something I’d like to know,” said a handsome little beetle
in a striped coat. “I’m a beetle, if there ever was one, yet I have a
world-wide reputation as a bug.”
“Pray don’t get excited, Mrs. Potato Bug. It isn’t your time to talk
yet. We are on the main issue, and I will answer my own question.”
Ruth was glad some one would answer it, for at this rate it seemed
they would never get anywhere.
“We are beetles for several reasons,” went on the elater. “In the
first place, we belong to the order Coleoptera.”
Another tera, thought Ruth.
“That name is taken from a language called Greek, and means
sheath wing. It is given to us because we have handsome outside
wings which we use to cover our real flying wings. All beetles have
them, though those of our cousin, Mr. Rove Beetle, are quite short.”
“That’s a fact,” said a rove beetle, “and no one need think we have
outgrown our coats. It is simply a fashion in our family to wear our
sheath wings short. We can always fold our true wings under them,
and I’d like to see the fellow who says we can’t.”
“Well, you needn’t get so mad about it,” answered the elater in
mild tones.
“And don’t curl your body up as if you were a wasp,” added Mrs.
Sawyer. “Everybody knows you can’t sting.”
“I don’t care,” said the rove beetle. “I hate to be misunderstood.
We are useful too. I heard a man call us scavengers. I don’t know
what it means, but something good, I am sure, from the way he said
it. I must be going soon. It is so dry here. You know my home is in
damp places under stones or leaves.”
“You may go when you wish,” answered the elater. “We are still on
the main issue. As I said before, we are beetles, and there is no
reason to take us for bugs. Calm yourself, Mrs. Potato Bug. We have
no sucking beak as the bugs have, but we have two sets of horny jaws,
which move sideways, and not up and down. These are to bite roots,
stems, and leaves of plants, so most of our order live on vegetable
food and are enemies to the farmer, but some of us are his friends,
for we eat the insects that injure his crops. Our children are called
grubs. Some of them make a sort of glue, with which they stick
together earth or bits of wood for a cocoon; others make tunnels in
tree trunks or wood and transform in them. We may well be proud,
for we belong to a large and beautiful order, and we are found in all
parts of the world. We are divided into two sub-orders—true beetles
and snout beetles. I hope our cousins, the snout beetles, will not be
offended. They are real in a way.”
“The farmer and fruit grower think so anyway,” said a little weevil.
“We have been called bugs just because we have a snout, but any one
can see at a glance that it isn’t a bug’s snout. It is not a tube at all, but
has tiny jaws at the tip.”
“I don’t believe I could see all that,” said Ruth rather timidly, for
these clever little people had a way of making her feel she knew very
little.
“Maybe you can’t,” was the short answer, “and I dare say you can’t
tell how we use our snouts either. We punch holes with them in
plums, peaches, cherries, and other fruits, not to mention nuts and
the bark of trees. I am a peach curculio, but that is not important. We
all work in the same way—that is, drop an egg in the hole made by
our snout, then use the snout again to push the egg down. Mrs. Plum
Weevil is busy now in the plum orchard back of us; so of course she
couldn’t come to this meeting. ‘Duty before pleasure,’ she said. She
will lay eggs in quite a number of plums, and the plums will drop
from the trees before they are ripe.”
“And there’ll be a lump of gum on them!” cried Ruth, clapping her
hands.
The weevil looked at her with approval. “You do notice some
things,” she said.
“The gum oozes out of the hole made by our snouts. Of course our
egg hatches inside the fruit, and the baby has its dinner all around it.
As it hasn’t a leg to walk on——”
“Dear! dear!” sighed the elater. “You seem to forget that we are
trying to keep to the main issue. As I said before——”
“You are always saying what you said before,” snapped Mrs.
Sawyer.
“Now, they are beginning again,” thought Ruth, but the elater paid
no attention to Mrs. Sawyer.
“As I said before,” he repeated, “we have reason to be proud, for
though we build no cities, like ants, wasps, and bees, and make no
honey or wax, or have, in fact, any special trades, yet we are
interesting and beautiful. The ancient Egyptians thought some of us
sacred and worshipped us.”
“There!” cried Mrs. Tumble Bug, literally tumbling into their
midst. “I couldn’t come at a better time.”
Ruth gave a little scream of delight when she saw her, and Mrs.
Tumble Bug nodded with the air of an old friend.
As usual, her black dress looked neat and clean, though she and
her husband had rolled and tumbled all over the road in their effort
to get their ball to what they considered the best place for it. They
had succeeded, and Mrs. Tumble Bug’s shovel-shaped face wore a
broad smile in consequence.
“I knew about this meeting,” she said, “but my husband and I
agreed that duty should come before pleasure.”
“She heard me say that,” whispered the little peach weevil to her
nearest neighbour.
“I didn’t,” answered Mrs. Tumble Bug. “I have just come. We only
found a safe place for our ball a little while ago.”
“That ball!” said Mrs. Sawyer in disgusted tones. “I should think
you would be tired of it.”
“Tired of our ball?” repeated Mrs. Tumble Bug. “Why, our ball is
the most important thing in the world. This was a big one, too. We
made it in Farmer Brown’s barnyard, and then I laid my eggs in it,
and we rolled it all the way here. Of course it grew on the road, and I
couldn’t have moved it alone, but my mate helped me. He always
helps. Indeed it seems to me tumble bugs are the only husbands in
the insect world who care about their children’s future.”
“Now I know,” said Ruth, who had been thinking very hard. “You
think so much of your balls because they hold your eggs. I’ve often
wondered about them.”
“Of course that is the reason,” answered Mrs. Tumble Bug; “and
when our eggs hatch the babies will have a feast all around them.”
“Ugh!” said Ruth, and some flower beetles shook their little heads,
and added:
“It would be better to starve than eat the stuff in that ball.”
“Tastes differ,” said Mrs. Tumble Bug, amiably; “but, speaking of
sacred beetles, it was our family the Egyptians worshipped. They
could not understand why we were always rolling our ball, so they
looked upon us as divine in some way, and made pictures of us in
stone and precious gems. They can be seen to-day, I am told, but I do
not care about that. I must make another ball,” and, nodding to her
mate, they left the meeting together.
“Now we’ll adjourn for dinner,” announced the elater, much to the
disgust of Mrs. Potato Bug, who was just getting ready to speak.
“Dinner is well enough,” she said, “but how is one to enjoy it when
one must stop in a little while?”
“You needn’t stop,” answered the elater. “Stay with your dinner.
We are not so anxious to hear you talk.”
“But I mean to talk, and I will,” and Mrs. Potato Bug was off to the
potato field, intending, as she said, to take a light lunch, and be back
when the meeting opened.
But potato bugs propose, and farmers dispose, and——
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
testbankfan.com

More Related Content

PDF
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
PDF
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
PPTX
CHAPTER 5
PPTX
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
PPT
Data Structure In C#
PPTX
Advanced VB: Review of the basics
PPTX
Advanced VB: Review of the basics
PDF
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis S...
CHAPTER 5
Chapter 5 Loops by z al saeddddddddddddddddddddddddddddddddddd
Data Structure In C#
Advanced VB: Review of the basics
Advanced VB: Review of the basics

Similar to Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual (20)

PPTX
130706266060138191
PPTX
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
PPTX
130707833146508191
PPTX
Ruby Basics
PPTX
Lecture 7
PPT
One dimensional 2
PDF
5 structured programming
PDF
CP Handout#7
DOCX
Array assignment
PDF
[ITP - Lecture 15] Arrays & its Types
PPTX
Array ppt you can learn in very few slides.
PDF
1-Intoduction ------------- Array in C++
PPT
js sdfsdfsdfsdfsdfsdfasdfsdfsdfsdaaray.ppt
PPTX
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
PDF
PDF
KeyJavaConcepts to EnhanceYour AutomationTesting Skills
DOCX
Space Complexity in Data Structure.docx
PDF
Acm aleppo cpc training second session
PPTX
Array.pptx Array.pptxArray.pptx Array.pptxArray.pptxArray.pptx
PPTX
Software fundamentals
130706266060138191
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
130707833146508191
Ruby Basics
Lecture 7
One dimensional 2
5 structured programming
CP Handout#7
Array assignment
[ITP - Lecture 15] Arrays & its Types
Array ppt you can learn in very few slides.
1-Intoduction ------------- Array in C++
js sdfsdfsdfsdfsdfsdfasdfsdfsdfsdaaray.ppt
module 3 BTECH FIRST YEAR ATP APJ KTU PYTHON
KeyJavaConcepts to EnhanceYour AutomationTesting Skills
Space Complexity in Data Structure.docx
Acm aleppo cpc training second session
Array.pptx Array.pptxArray.pptx Array.pptxArray.pptxArray.pptx
Software fundamentals
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Computing-Curriculum for Schools in Ghana
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Presentation on HIE in infants and its manifestations
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Institutional Correction lecture only . . .
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Pharma ospi slides which help in ospi learning
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Final Presentation General Medicine 03-08-2024.pptx
Supply Chain Operations Speaking Notes -ICLT Program
Final Presentation General Medicine 03-08-2024.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Computing-Curriculum for Schools in Ghana
2.FourierTransform-ShortQuestionswithAnswers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Presentation on HIE in infants and its manifestations
Chinmaya Tiranga quiz Grand Finale.pdf
RMMM.pdf make it easy to upload and study
A systematic review of self-coping strategies used by university students to ...
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
O5-L3 Freight Transport Ops (International) V1.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Institutional Correction lecture only . . .
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
102 student loan defaulters named and shamed – Is someone you know on the list?
Pharma ospi slides which help in ospi learning
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Ad

Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual

  • 1. Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Solutions Manual download pdf https://testbankfan.com/product/starting-out-with-c-from-control- structures-to-objects-8th-edition-gaddis-solutions-manual/ Visit testbankfan.com to explore and download the complete collection of test banks or solution manuals!
  • 2. We have selected some products that you may be interested in Click the link to download now or visit testbankfan.com for more options!. Starting Out with C++ from Control Structures to Objects 8th Edition Gaddis Test Bank https://testbankfan.com/product/starting-out-with-c-from-control- structures-to-objects-8th-edition-gaddis-test-bank/ Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis Solutions Manual https://testbankfan.com/product/starting-out-with-c-from-control- structures-to-objects-9th-edition-gaddis-solutions-manual/ Starting Out With C++ From Control Structures To Objects 7th Edition Gaddis Solutions Manual https://testbankfan.com/product/starting-out-with-c-from-control- structures-to-objects-7th-edition-gaddis-solutions-manual/ Americas History Concise Edition Volume 2 9th Edition Edwards Test Bank https://testbankfan.com/product/americas-history-concise-edition- volume-2-9th-edition-edwards-test-bank/
  • 3. Chemistry 7th Edition McMurry Test Bank https://testbankfan.com/product/chemistry-7th-edition-mcmurry-test- bank/ Microeconomics 9th Edition Parkin Test Bank https://testbankfan.com/product/microeconomics-9th-edition-parkin- test-bank/ Business Ethics Ethical Decision Making and Cases 12th Edition Ferrell Test Bank https://testbankfan.com/product/business-ethics-ethical-decision- making-and-cases-12th-edition-ferrell-test-bank/ Managerial Accounting 3rd Edition Braun Test Bank https://testbankfan.com/product/managerial-accounting-3rd-edition- braun-test-bank/ Principles of Microeconomics 8th Edition Mankiw Test Bank https://testbankfan.com/product/principles-of-microeconomics-8th- edition-mankiw-test-bank/
  • 4. Environment The Science Behind the Stories 6th Edition Withgott Test Bank https://testbankfan.com/product/environment-the-science-behind-the- stories-6th-edition-withgott-test-bank/
  • 5. PURPOSE 1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays PROCEDURE 1. Students should read the Pre-lab Reading Assignment before coming to lab. 2. Students should complete the Pre-lab Writing Assignment before coming to lab. 3. In the lab, students should complete labs assigned to them by the instructor. L E S S O N S E T 7 Arrays Contents Pre-requisites Approximate completion time Page number Check when done Pre-lab Reading Assignment 20 min. 114 Pre-lab Writing Assignment Pre-lab reading 10 min. 122 LESSON 7A Lab 7.1 Working with One- Basic understanding of 30 min. 123 Dimensional Arrays one-dimensional arrays Lab 7.2 Strings as Arrays of Basic understanding of 20 min. 126 Characters arrays of characters LESSON 7B Lab 7.3 Working with Two- Understanding of multi- 30 min. 129 Dimensional Arrays dimensional arrays Lab 7.4 Student Generated Code Basic understanding 30 min. 134 Assignments of arrays 113
  • 6. 114 LESSON SET 7 Arrays PRE-LAB READING ASSIGNMENT One-Dimensional Arrays So far we have talked about a variable as a single location in the computer’s memory. It is possible to have a collection of memory locations, all of which have the same data type, grouped together under one name. Such a collection is called an array. Like every variable, an array must be defined so that the com- puter can “reserve” the appropriate amount of memory. This amount is based upon the type of data to be stored and the number of locations, i.e., size of the array, each of which is given in the definition. Example: Given a list of ages (from a file or input from the keyboard), find and display the number of people for each age. The programmer does not know the ages to be read but needs a space for the total number of occurrences of each “legitimate age.” Assuming that ages 1, 2, . . . , 100 are possible, the following array definition can be used. const int TOTALYEARS = 100; int main() { int ageFrequency[TOTALYEARS]; //reserves memory for 100 ints : return 0; } Following the rules of variable definition, the data type (integer in this case) is given first, followed by the name of the array (ageFrequency), and then the total number of memory locations enclosed in brackets. The number of memory loca- tions must be an integer expression greater than zero and can be given either as a named constant (as shown in the above example) or as a literal constant (an actual number such as 100). Each element of an array, consisting of a particular memory location within the group, is accessed by giving the name of the array and a position with the array (subscript). In C++ the subscript, sometimes referred to as index, is enclosed in square brackets. The numbering of the subscripts always begins at 0 and ends with one less than the total number of locations. Thus the elements in the ageFrequency array defined above are referenced as ageFrequency[0] through ageFrequency[99]. 0 1 2 3 4 5 . . . . . . 97 98 99 If in our example we want ages from 1 to 100, the number of occurrences of age 4 will be placed in subscript 3 since it is the “fourth” location in the array. This odd way of numbering is often confusing to new programmers; however, it quickly becomes routine.1 1 Some students actually add one more location and then ignore location 0, letting 1 be the first location. In the above example such a process would use the following definition: int agefrequency[101]; and use only the subscripts 1 through 100. Our examples will use location 0. Your instructor will tell you which method to use.
  • 7. Pre-lab Reading Assignment 115 Array Initialization In our example, ageFrequency[0] keeps a count of how many 1s we read in, ageFrequency[1] keeps count of how many 2s we read in, etc. Thus, keeping track of how many people of a particular age exist in the data read in requires reading each age and then adding one to the location holding the count for that age. Of course it is important that all the counters start at 0. The following shows the initialization of all the elements of our sample array to 0. for (int pos = 0; pos < TOTALYEARS; pos++) // pos acts as the array subscript { ageFrequency[pos] = 0; } A simple for loop will process the entire array, adding one to the subscript each time through the loop. Notice that the subscript (pos) starts with 0. Why is the con- dition pos < TOTALYEARS used instead of pos <= TOTALYEARS? Remember that the last subscript is one less than the total number of elements in the array. Hence the subscripts of this array go from 0 to 99. Array Processing Arrays are generally processed inside loops so that the input/output processing of each element of the array can be performed with minimal statements. Our age frequency program first needs to read in the ages from a file or from the key- board. For each age read in, the “appropriate” element of the array (the one cor- responding to that age) needs to be incremented by one. The following examples show how this can be accomplished: from a file using infile as a logical name from a keyboard with –99 as sentinel data cout << "Please input an age from one" << "to 100. input -99 to stop" << endl; infile >> currentAge; cin >> currentAge; while (infile) while (currentAge != -99) { { ageFrequency[currentAge-1] = ageFrequency[currentAge-1] = ageFrequency[currentAge-1] + 1; ageFrequency[currentAge-1] + 1; infile >> currentAge; cout << "Please input an age from " << "one to 100. input -99 to stop" << endl; cin >> currentAge; } } The while(infile) statement means that while there is more data in the file infile, the loop will continue to process. To read from a file or from the keyboard we prime the read,2 which means the first value is read in before the test condition is checked to see if the loop 2 Priming the read for a while loop means having an input just before the loop condition (just before the while) and having another one as the last statement in the loop.
  • 8. 4 0 14 5 0 6 1 0 116 LESSON SET 7 Arrays should be executed. When we read an age, we increment the location in the array that keeps track of the amount of people in the corresponding age group. Since C++ array indices always start with 0, that location will be at the subscript one value less than the age we read in. 0 1 2 3 4 5 . . . . . . 98 99 1 year 2 years 3 years 4 years 5 years 6 years 99 years 100 years Each element of the array contains the number of people of a given age. The data shown here is from a random sample run. In writing the information stored in the array, we want to make sure that only those array elements that have values greater than 0 are output. The following code will do this. for (int ageCounter = 0; ageCounter < TOTALYEARS; ageCounter++) if (ageFrequency[ageCounter] > 0) cout << "The number of people " << ageCounter + 1 <<" years old is " << ageFrequency[ageCounter] << endl; The for loop goes from 0 to one less than TOTALYEARS (0 to 99). This will test every element of the array. If a given element has a value greater than 0, it will be output. What does outputting ageCounter + 1 do? It gives the age we are deal- ing with at any given time, while the value of ageFrequency[ageCounter] gives the number of people in that age group. The complete age frequency program will be given as one of the lab assign- ments in Lab 7.4. Arrays as Arguments Arrays can be passed as arguments (parameters) to functions. Although variables can be passed by value or reference, arrays are always passed by pointer, which is similar to pass by reference, since it is not efficient to make a “copy” of all ele- ments of the array. Pass by pointer is discussed further in Lesson Set 9. This means that arrays, like pass by reference parameters, can be altered by the call- ing function. However, they NEVER have the & symbol between the data type and name, as pass by reference parameters do. Sample Program 7.1 illustrates how arrays are passed as arguments to functions. Sample Program 7.1: // The grade average program // This program illustrates how one-dimensional arrays are used and how // they are passed as arguments to functions. It contains two functions. // The first function is called to allow the user to input a set of grades and // store them in an array. The second function is called to find the average // grade. #include <iostream> using namespace std;
  • 9. Pre-lab Reading Assignment 117 const int TOTALGRADES = 50; // TOTALGRADES is the maximum size of the array // function prototypes void getData(int array[], int& sizeOfArray); // the procedure that will read values into the array float findAverage(const int array[], int sizeOfArray); // the procedure that will find the average of values // stored in an array. The word const in front of the // data type of the array prevents the function from // altering the array int main() { int grades[TOTALGRADES]; // defines an array that holds up to 50 ints int numberOfGrades = 0; // the number of grades read in float average; // the average of all grades read in getData(grades, numberOfGrades); // getData is called to read the grades into // the array and store how many grades there // are in numberOfGrades average = findAverage(grades, numberOfGrades); cout << endl << "The average of the " << numberOfGrades << " grades read in is " << average << "." << endl << endl; return 0; } //*********************************************************************** // getData // // task: This function inputs and stores data in the grades array. // data in: none (the parameters contain no information needed by the // getData function) // data out: an array containing grades and the number of grades //*********************************************************************** void getData(int array[], int& sizeOfArray) { int pos = 0; // array index which starts at 0 int grade; // holds each individual grade read in cout << "Please input a grade or type -99 to stop: " << endl; cin >> grade; continues
  • 10. 118 LESSON SET 7 Arrays while (grade != -99) { array[pos] = grade; // store grade read in to next array location pos ++; // increment array index cout << "Please input a grade or type -99 to stop: " << endl; cin >> grade; } sizeOfArray = pos; // upon exiting the loop, pos holds the // number of grades read in, which is sent // back to the calling function } //**************************************************************************** // findAverage // // task: This function finds and returns the average of the values // // data in: the array containing grades and the array size // data returned: the average of the grades contained in that array //**************************************************************************** float findAverage (const int array[], int sizeOfArray) { int sum = 0; // holds the sum of all grades in the array for (int pos = 0; pos < sizeOfArray; pos++) { sum = sum + array[pos]; // add grade in array position pos to sum } return float(sum)/sizeOfArray; } Notice that a set of empty brackets [ ] follows the parameter of an array which indicates that the data type of this parameter is in fact an array. Notice also that no brackets appear in the call to the functions that receive the array. Since arrays in C++ are passed by pointer, which is similar to pass by reference, it allows the original array to be altered, even though no & is used to designate this. The getData function is thus able to store new values into the array. There may be times when we do not want the function to alter the values of the array. Inserting the word const before the data type on the formal parameter list pre- vents the function from altering the array even though it is passed by pointer. This is why in the preceding sample program the findAverage function and header had the word const in front of the data type of the array. float findAverage (const int array[], int sizeOfArray); // prototype float findAverage (const int array[], int sizeOfArray) // function header
  • 11. Pre-lab Reading Assignment 119 The variable numberOfGrades contains the number of elements in the array to be processed. In most cases not every element of the array is used, which means the size of the array given in its definition and the number of actual elements used are rarely the same. For that reason we often pass the actual number of ele- ments used in the array as a parameter to a procedure that uses the array. The variable numberOfGrades is explicitly passed by reference (by using &) to the getData function where its corresponding formal parameter is called sizeOfArray. Prototypes can be written without named parameters. Function headers must include named parameters. float findAverage (const int [], int); // prototype without named parameters The use of brackets in function prototypes and headings can be avoided by declaring a programmer defined data type. This is done in the global section with a typedef statement. Example: typedef int GradeType[50]; This declares a data type, called GradeType, that is an array containing 50 inte- ger memory locations. Since GradeType is a data type, it can be used in defining variables. The following defines grades as an integer array with 50 elements. GradeType grades; It has become a standard practice (although not a requirement) to use an upper- case letter to begin the name of a data type. It is also helpful to include the word “type” in the name to indicate that it is a data type and not a variable. Sample Program 7.2 shows the revised code (in bold) of Sample Program 7.1 using typedef. Sample Program 7.2: // Grade average program // This program illustrates how one-dimensional arrays are used and how // they are passed as arguments to functions. It contains two functions. // The first function is called to input a set of grades and store them // in an array. The second function is called to find the average grade. #include <iostream> using namespace std; const int TOTALGRADES = 50; // maximum size of the array // function prototypes typedef int GradeType[TOTALGRADES]; // declaration of an integer array data type // called GradeType continues
  • 12. 120 LESSON SET 7 Arrays void getData(GradeType array, int& sizeOfArray); // the procedure that will read values into the array float findAverage(const GradeType array, int sizeOfArray); // the procedure that will find the average of values // stored in an array. The word const in front of the // data type of the array prevents the function from // altering the array int main() { GradeType grades; // defines an array that holds up to 50 ints int numberOfGrades = 0; // the number of grades read in float average; // the average of all grades read in getData(grades, numberOfGrades);// getData is called to read the grades into // the array and store how many grades there // are in numberOfGrades average = findAverage(grades, numberOfGrades); cout << endl << "The average of the " << numberOfGrade << " grades read in is " << average << "." << endl << endl; return 0; } //*********************************************************************** // getData // // task: This function inputs and stores data in the grades array. // data in: none // data out: an array containing grades and the number of grades //*********************************************************************** void getData(GradeType array, int& sizeOfArray) { int pos = 0; // array index which starts at 0 int grade; // holds each individual grade read in cout << "Please input a grade or type -99 to stop: " << endl; cin >> grade; while (grade != -99) { array[pos] = grade; // store grade read in to next array location pos ++; // increment array index cout << "Please input a grade or type -99 to stop: " << endl; cin >> grade; }
  • 13. Pre-lab Reading Assignment 121 sizeOfArray = pos; // upon exiting the loop, pos holds the // number of grades read in, which is sent // back to the calling function } //**************************************************************************** // findAverage // // task: This function finds and returns the average of the values // // data in: the array containing grades and the array size // data returned: the average of the grades contained in that array //**************************************************************************** float findAverage (const GradeType array, int sizeOfArray) { int sum = 0; // holds the sum of all grades in the array for (int pos = 0; pos < sizeOfArray; pos++) { sum = sum + array[pos]; // add grade in array position pos to sum } return float(sum)/sizeOfArray; } This method of using typedef to eliminate brackets in function prototypes and headings is especially useful for multi-dimensional arrays such as those intro- duced in the next section. Two-Dimensional Arrays Data is often contained in a table of rows and columns that can be implement- ed with a two-dimensional array. Suppose we want to read data representing profits (in thousands) for a particular year and quarter. Quarter 1 Quarter 2 Quarter 3 Quarter 4 72 80 10 100 82 90 43 42 10 87 48 53 This can be done using a two-dimensional array. Example: const NO_OF_ROWS = 3; const NO_OF_COLS = 4; typedef float ProfitType[NO_OF_ROWS][NO_OF_COLS]; //declares a new data type //which is a 2 dimensional //array of floats continues
  • 14. 122 LESSON SET 7 Arrays int main() { ProfitType profit; // defines profit as a 2 dimensional array for (int row_pos = 0; row_pos < NO_OF_ROWS; row_pos++) for (int col_pos = 0; col_pos < NO_OF_COLS; col_pos++) { cout << "Please input a profit" << endl; cin >> profit[row_pos][col_pos]; } return 0; } A two dimensional array normally uses two loops (one nested inside the other) to read, process, or output data. How many times will the code above ask for a profit? It processes the inner loop NO_OF_ROWS * NO_OF_COLS times, which is 12 times in this case. Multi-Dimensional Arrays C++ arrays can have any number of dimensions (although more than three is rarely used). To input, process or output every item in an n-dimensional array, you need n nested loops. Arrays of Strings Any variable defined as char holds only one character. To hold more than one character in a single variable, that variable needs to be an array of characters. A string (a group of characters that usually form meaningful names or words) is really just an array of characters. A complete lesson on characters and strings is given in Lesson Set 10. PRE-LAB WRITING ASSIGNMENT Fill-in-the-Blank Questions 1. The first subscript of every array in C++ is and the last is less than the total number of locations in the array. 2. The amount of memory allocated to an array is based on the and the of locations or size of the array. 3. Array initialization and processing is usually done inside a . 4. The statement can be used to declare an array type and is often used for multidimensional array declarations so that when passing arrays as parameters, brackets do not have to be used. 5. Multi-dimensional arrays are usually processed within loops. 6. Arrays used as arguments are always passed by .
  • 15. Lesson 7A 123 7. In passing an array as a parameter to a function that processes it, it is often necessary to pass a parameter that holds the of used in the array. 8. A string is an array of . 9. Upon exiting a loop that reads values into an array, the variable used as a(n) to the array will contain the size of that array. 10. An n-dimensional array will be processed within nested loops when accessing all members of the array. LESSON 7A LAB 7.1 Working with One-Dimensional Arrays Retrieve program testscore.cpp from the Lab 7 folder. The code is as follows: // This program will read in a group of test scores (positive integers from 1 to 100) // from the keyboard and then calculate and output the average score // as well as the highest and lowest score. There will be a maximum of 100 scores. // PLACE YOUR NAME HERE #include <iostream> using namespace std; typedef int GradeType[100]; // declares a new data type: // an integer array of 100 elements float findAverage (const GradeType, int); // finds average of all grades int findHighest (const GradeType, int); // finds highest of all grades int findLowest (const GradeType, int); // finds lowest of all grades int main() { GradeType grades; // the array holding the grades. int numberOfGrades; // the number of grades read. int pos; // index to the array. float avgOfGrades; // contains the average of the grades. int highestGrade; // contains the highest grade. int lowestGrade; // contains the lowest grade. // Read in the values into the array pos = 0; cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl; continues
  • 16. 124 LESSON SET 7 Arrays cin >> grades[pos]; while (grades[pos] != -99) { // Fill in the code to read the grades } numberOfGrades = ; // Fill blank with appropriate identifier // call to the function to find average avgOfGrades = findAverage(grades, numberOfGrades); cout << endl << "The average of all the grades is " << avgOfGrades << endl; // Fill in the call to the function that calculates highest grade cout << endl << "The highest grade is " << highestGrade << endl; // Fill in the call to the function that calculates lowest grade // Fill in code to write the lowest to the screen return 0; } //******************************************************************************** // findAverage // // task: This function receives an array of integers and its size. // It finds and returns the average of the numbers in the array // data in: array of floating point numbers // data returned: average of the numbers in the array // //******************************************************************************** float findAverage (const GradeType array, int size) { float sum = 0; // holds the sum of all the numbers for (int pos = 0; pos < size; pos++) sum = sum + array[pos]; return (sum / size); //returns the average }
  • 17. Lesson 7A 125 //**************************************************************************** // findHighest // // task: This function receives an array of integers and its size. // It finds and returns the highest value of the numbers in the array // data in: array of floating point numbers // data returned: highest value of the numbers in the array // //**************************************************************************** int findHighest (const GradeType array, int size) { / Fill in the code for this function } //**************************************************************************** // findLowest // // task: This function receives an array of integers and its size. // It finds and returns the lowest value of the numbers in the array // data in: array of floating point numbers // data returned: lowest value of the numbers in the array // //**************************************************************************** int findLowest (const GradeType array, int size) { // Fill in the code for this function } Exercise 1: Complete this program as directed. Exercise 2: Run the program with the following data: 90 45 73 62 -99 and record the output here: Exercise 3: Modify your program from Exercise 1 so that it reads the informa- tion from the gradfile.txt file, reading until the end of file is encoun- tered. You will need to first retrieve this file from the Lab 7 folder and place it in the same folder as your C++ source code. Run the program.
  • 18. 126 LESSON SET 7 Arrays Lab 7.2 Strings as Arrays of Characters Retrieve program student.cpp from the Lab 7 folder. // This program will input an undetermined number of student names // and a number of grades for each student. The number of grades is // given by the user. The grades are stored in an array. // Two functions are called for each student. // One function will give the numeric average of their grades. // The other function will give a letter grade to that average. // Grades are assigned on a 10 point spread. // 90-100 A 80-89 B 70-79 C 60-69 D Below 60 F // PLACE YOUR NAME HERE #include <iostream> #include <iomanip> using namespace std; const int MAXGRADE = 25; // maximum number of grades per student const int MAXCHAR = 30; // maximum characters used in a name typedef char StringType30[MAXCHAR + 1];// character array data type for names // having 30 characters or less. typedef float GradeType[MAXGRADE]; // one dimensional integer array data type float findGradeAvg(GradeType, int); // finds grade average by taking array of // grades and number of grades as parameters char findLetterGrade(float); // finds letter grade from average given // to it as a parameter int main() { StringType30 firstname, lastname;// two arrays of characters defined int numOfGrades; // holds the number of grades GradeType grades; // grades defined as a one dimensional array float average; // holds the average of a student's grade char moreInput; // determines if there is more input cout << setprecision(2) << fixed << showpoint; // Input the number of grades for each student cout << "Please input the number of grades each student will receive." << endl << "This must be a number between 1 and " << MAXGRADE << " inclusive” << endl; cin >> numOfGrades;
  • 19. Lesson 7A 127 while (numOfGrades > MAXGRADE || numOfGrades < 1) { cout << "Please input the number of grades for each student." << endl << "This must be a number between 1 and " << MAXGRADE << " inclusiven"; cin >> numOfGrades; } // Input names and grades for each student cout << "Please input a y if you want to input more students" << " any other character will stop the input" << endl; cin >> moreInput; while (moreInput == 'y' || moreInput == 'Y') { cout << "Please input the first name of the student" << endl; cin >> firstname; cout << endl << "Please input the last name of the student" << endl; cin >> lastname; for (int count = 0; count < numOfGrades; count++) { cout << endl << "Please input a grade" << endl; // Fill in the input statement to place grade in the array } cout << firstname << " " << lastname << " has an average of "; // Fill in code to get and print average of student to screen // Fill in call to get and print letter grade of student to screen cout << endl << endl << endl; cout << "Please input a y if you want to input more students" << " any other character will stop the input" << endl; cin >> moreInput; } return 0; } continues
  • 20. 128 LESSON SET 7 Arrays //*********************************************************************** // findGradeAvg // // task: This function finds the average of the // numbers stored in an array. // // data in: an array of integer numbers // data returned: the average of all numbers in the array // //*********************************************************************** float findGradeAvg(GradeType array, int numGrades) { // Fill in the code for this function } //*********************************************************************** // findLetterGrade // // task: This function finds the letter grade for the number // passed to it by the calling function // // data in: a floating point number // data returned: the grade (based on a 10 point spread) based on the number // passed to the function // //*********************************************************************** char findLetterGrade(float numGrade) { // Fill in the code for this function } Exercise 1: Complete the program by filling in the code. (Areas in bold) Run the program with 3 grades per student using the sample data below. Mary Brown 100 90 90 George Smith 90 30 50 Dale Barnes 80 78 82 Sally Dolittle 70 65 80 Conrad Bailer 60 58 71 You should get the following results: Mary Brown has an average of 93.33 which gives the letter grade of A George Smith has an average of 56.67 which gives the letter grade of F Dale Barnes has an average of 80.00 which gives the letter grade of B Sally Dolittle has an average of 71.67 which gives the letter grade of C Conrad Bailer has an average of 63.00 which gives the letter grade of D
  • 21. Lesson 7B 129 LESSON 7B LAB 7.3 Working with Two-Dimensional Arrays Look at the following table containing prices of certain items: 12.78 23.78 45.67 12.67 7.83 4.89 5.99 56.84 13.67 34.84 16.71 50.89 These numbers can be read into a two-dimensional array. Retrieve price.cpp from the Lab 7 folder. The code is as follows: // This program will read in prices and store them into a two-dimensional array. // It will print those prices in a table form. // PLACE YOUR NAME HERE #include <iostream> #include <iomanip> using namespace std; const MAXROWS = 10; const MAXCOLS = 10; typedef float PriceType[MAXROWS][MAXCOLS]; // creates a new data type // of a 2D array of floats void getPrices(PriceType, int&, int&); // gets the prices into the array void printPrices(PriceType, int, int); // prints data as a table int main() { int rowsUsed; // holds the number of rows used int colsUsed; // holds the number of columns used PriceType priceTable; // a 2D array holding the prices getPrices(priceTable, rowsUsed, colsUsed); // calls getPrices to fill the array printPrices(priceTable, rowsUsed, colsUsed);// calls printPrices to display array return 0; } continues
  • 22. 130 LESSON SET 7 Arrays //******************************************************************************* // getPrices // // task: This procedure asks the user to input the number of rows and // columns. It then asks the user to input (rows * columns) number of // prices. The data is placed in the array. // data in: none // data out: an array filled with numbers and the number of rows // and columns used. // //******************************************************************************* void getPrices(PriceType table, int& numOfRows, int& numOfCols) { cout << "Please input the number of rows from 1 to "<< MAXROWS << endl; cin >> numOfRows; cout << "Please input the number of columns from 1 to "<< MAXCOLS << endl; cin >> numOfCols; for (int row = 0; row < numOfRows; row++) { for (int col = 0; col < numOfCols; col++) // Fill in the code to read and store the next value in the array } } //*************************************************************************** // printPrices // // task: This procedure prints the table of prices // data in: an array of floating point numbers and the number of rows // and columns used. // data out: none // //**************************************************************************** void printPrices(PriceType table, int numOfRows, int numOfCols) { cout << fixed << showpoint << setprecision(2); for (int row = 0; row < numOfRows; row++) { for (int col = 0; col < numOfCols; col++) // Fill in the code to print the table } }
  • 23. Lesson 7B 131 Exercise 1: Fill in the code to complete both functions getPrices and printPrices, then run the program with the following data: Exercise 2: Why does getPrices have the parameters numOfRows and numOfCols passed by reference whereas printPrices has those parameters passed by value? Exercise 3: The following code is a function that returns the highest price in the array. After studying it very carefully, place the function in the above program and have the program print out the highest value. float findHighestPrice(PriceType table, int numOfRows, int numOfCols) // This function returns the highest price in the array { float highestPrice; highestPrice = table[0][0]; // make first element the highest price for (int row = 0; row < numOfRows; row++) for (int col = 0; col < numOfCols; col++) if ( highestPrice < table[row][col] ) highestPrice = table[row][col]; return highestPrice; } continues
  • 24. 132 LESSON SET 7 Arrays NOTE: This is a value returning function. Be sure to include its prototype in the global section. Exercise 4: Create another value returning function that finds the lowest price in the array and have the program print that value. Exercise 5: After completing all the exercises above, run the program again with the values from Exercise 1 and record your results. Exercise 6: (Optional) Look at the following table that contains quarterly sales transactions for three years of a small company. Each of the quarterly transactions are integers (number of sales) and the year is also an integer. YEAR Quarter 1 Quarter 2 Quarter 3 Quarter 4 2000 72 80 60 100 2001 82 90 43 98 2002 64 78 58 84 We could use a two-dimensional array consisting of 3 rows and 5 columns. Even though there are only four quarters we need 5 columns (the first column holds the year). Retrieve quartsal.cpp from the Lab 7 folder. The code is as follows: // This program will read in the quarterly sales transactions for a given number // of years. It will print the year and transactions in a table format. // It will calculate year and quarter total transactions. // PLACE YOUR NAME HERE #include <iostream> #include <iomanip> using namespace std; const MAXYEAR = 10; const MAXCOL = 5; typedef int SalesType[MAXYEAR][MAXCOL]; // creates a new 2D integer data type void getSales(SalesType, int&); // places sales figures into the array void printSales(SalesType, int); // prints data as a table void printTableHeading(); // prints table heading int main() { int yearsUsed; // holds the number of years used SalesType sales; // 2D array holding // the sales transactions getSales(sales, yearsUsed); // calls getSales to put data in array
  • 25. Lesson 7B 133 printTableHeading(); // calls procedure to print the heading printSales(sales, yearsUsed); // calls printSales to display table return 0; } //***************************************************************************** // printTableHeading // task: This procedure prints the table heading // data in: none // data out: none // //***************************************************************************** void printTableHeading() { cout << setw(30) << "YEARLY QUARTERLY SALES" << endl << endl << endl; cout << setw(10) << "YEAR" << setw(10) << "Quarter 1" << setw(10) << "Quarter 2" << setw(10) << "Quarter 3" << setw(10) << "Quarter 4" << endl; } //***************************************************************************** // getSales // // task: This procedure asks the user to input the number of years. // For each of those years it asks the user to input the year // (e.g. 2004), followed by the sales figures for each of the // 4 quarters of that year. That data is placed in a 2D array // data in: a 2D array of integers // data out: the total number of years // //***************************************************************************** void getSales(SalesType table, int& numOfYears) { cout << "Please input the number of years (1-" << MAXYEAR << ')' << endl; cin >> numOfYears; // Fill in the code to read and store the next value continues
  • 26. 134 LESSON SET 7 Arrays } //***************************************************************************** // printSales // // task: This procedure prints out the information in the array // data in: an array containing sales information // data out: none // //***************************************************************************** void printSales(SalesType table, int numOfYears) { // Fill in the code to print the table } Fill in the code for both getSales and printSales. This is similar to the price.cpp program in Exercise 1; however, the code will be different. This is a table that contains something other than sales in column one. Exercise 7: Run the program so that the chart from Exercise 6 is printed. LAB 7.4 Student Generated Code Assignments Option 1: Write the complete age population program given in the Pre-lab Reading Assignment. Statement of the problem: Given a list of ages (1 to 100) from the keyboard, the program will tally how many people are in each age group. Sample Run:
  • 27. Lesson 7B 135 Option 2: Write a program that will input temperatures for consecutive days. The program will store these values into an array and call a function that will return the average of the temperatures. It will also call a function that will return the highest temperature and a function that will return the lowest temperature. The user will input the number of temperatures to be read. There will be no more than 50 temperatures. Use typedef to declare the array type. The average should be displayed to two decimal places. Sample Run: Option 3: Write a program that will input letter grades (A, B, C, D, F), the number of which is input by the user (a maximum of 50 grades). The grades will be read into an array. A function will be called five times (once for each letter grade) and will return the total number of grades in that category. The input to the function will include the array, number of elements in the array and the letter category (A, B, C, D or F). The pro- gram will print the number of grades that are A, B, etc.
  • 28. 136 LESSON SET 7 Arrays Sample Run:
  • 29. Exploring the Variety of Random Documents with Different Content
  • 30. dragon fly, I can tell you. I had six tiny spider-like legs, but not a sign of wings, and when I breathed it was not as I do now, like all perfect insects, through openings on each side of my body. I had gills, and a tube at the end of my body brought fresh water to them. This tube was a funny affair. It really helped me along, for when I spurted water through it I was pushed forward. Then I had a wonderful mouth, with a long under lip, that I could dart out and catch anything within reach, while I did not need to move my body at all.” “Just like frogs and toads!” cried Ruth. “Not at all,” answered the dragon fly. “They only send out their tongues. I send out my whole under lip. If you could only keep quiet you would not show your ignorance so plainly.” Once more Ruth was snubbed, and the dragon fly continued: “In time I became a pupa.” Ruth looked the question she dared not ask. “I’ll explain,” said the dragon fly, amiably. “Larva—that’s what I was at first—means mask, or something that hides you. You will find out in time, if you do not know now, that the larva of an insect is really a mask which hides its true form. The plural of the word is larvæ. Now pupa, plural pupæ, means baby. It is usually the state of sleep in which the larva lies after spinning its cocoon or cradle, but in my case it didn’t suit at all. Dragon flies, far from sleeping in the pupa state, seem to grow more active, and their appetites are larger. Indeed, I will say right here, everything that came my way, and was not too big, went into my mouth. In fact, I finally reached my limit and burst.” “Gracious!” cried Ruth in a shocked tone. “How did you get yourself together again?” “Well, you see, the whole of me didn’t burst. I simply grew too big for my skin, or my pupa case, as the wise men call it, and it cracked right open. I was climbing on a water plant when this happened, for all at once I had felt a longing to leave the water and get to the open air. My first effort was to get rid of the useless old shell which still clung to me, but I had quite a tussle before I could do so, and afterward I was very weak and tired. But the result was worth all my labour, for I found myself with these four wings, and the rest of my beautiful body, and I needed only to dry myself before sailing away
  • 31. on the wind, the swiftest thing on wings, and the most renowned mosquito killer on record. Of course, my legs aren’t arranged for walking. Why should they be? All six of them go forward, as if they were reaching for something, and so they are, reaching for something to eat. Woe betide any insect I start after. I catch him every time. I ought to, for I have thousands of eyes, and I can fly forward, backward, or any old way. I never stop to eat my dinner either. I hold it, and eat it as I go. Now if I had time, I would tell you how the children of Japan make a holiday, and go out to catch us for pets, and how they sing pretty songs to us and——” “It is about time you stopped,” interrupted Mrs. Ant Lion. “You have tried our patience long enough, and I mean to speak this very minute. I’ve been told I am much like the dragon flies,” she added to the company, “but my babies are not at all like theirs. They do not belong to the water, and I am glad of it. I’m tired of water babies. I’ve heard so much of them to-day. My mother had the good sense to lay her eggs in sand, and I shall do the same. I was hungry from the minute I was hatched, and I would have run after something to eat right away, only I found I couldn’t. My legs were fixed in such a way I had to walk backward.” “Backward?” echoed Ruth. “Yes, backward. So there was nothing to do but to dig a trap for my dinner, and I set about it pretty quick. No one showed me how, either. I simply used my shovel-shaped head, and before long I had made quite a pit, broad and rounded at the top, and sloping to a point like a funnel at the bottom. You have seen them, of course?” “I think I have,” answered Ruth. “They are not hard to find if you keep your eyes open,” went on the ant lion. “Well, as I said, I made one of these pits, and in the funnel end I lay in wait for ants. Soon one came along, slipped over the edge, as I expected, and tumbled right into my open mouth. Nor was she the only one. Some were strong enough to turn, even while they were slipping, and start to crawl up again, but I just heaped some sand on my head and threw it at them, and down they would come. My aim was always good, so were the ants, though I only sucked their juice. Of course I did not leave their skins around to frighten away other
  • 32. ants. I piled them on my head, and gave them a toss, which sent them some distance away. After a time I stopped eating, and made a cocoon. Then I went to sleep!—for many days—during which I changed wonderfully, as any one must know who has seen ant lion babies and now sees me. This is all of my story, and I suppose we will hear about another tiresome water baby.” “‘I MADE ONE OF THESE PITS AND IN THE FUNNEL END I LAY IN WAIT FOR ANTS’” “You shall hear about a water baby,” replied Mrs. Caddice Fly, waving her antennæ by way of salute, “but tiresome will do for your own homely children. I will begin by saying that, with the accidents of life, it is a wonder that any of us are here. When we caddice flies were hatched we were soft, white, six-footed babies. We were called worms, though we were not worms. Think of it! Soft bodied, with not very strong legs, white, and living at the bottom of the pond. Could anything be worse? No wonder we seemed to do nothing at first but try to get away from things that wanted to eat us. I tell you, pond life is most exciting. After a while the front part of our bodies and our heads began to turn brown, and, as the rest of us was white, and seemed likely to stay so, we all decided to make a case or house to cover our white part. So we set to work and of bits of sticks, tiny stones, and broken shells, glued together with silk from our own bodies, we made these cases. True, many of us went down the throat of Belostoma, the giant water bug, before we had finished, but those
  • 33. of us who didn’t crawled into our little houses, locking ourselves in by two strong hooks which grew at the end of our bodies. We could move about, but of course we carried our houses with us and——” “How ridiculous!” said Mrs. Ant Lion. “Why didn’t you stay still?” “Because we didn’t wish to,” answered the caddice fly. “We had to eat, and we had to get away from those who wished to eat us. At last we went to sleep, after first spinning a veil of silk over our front and back doors. I can’t answer for the others, but when I awoke I tore open my silken door, threw aside my pupa skin, and found I had wings. Since then I have had a new life, but even that has its enemies, and one never knows what will happen.” With which doleful saying Mrs. Caddice Fly sailed away to the pond to lay some eggs among the water plants. “Dear me,” said Mrs. Lacewing, “we seem to need something cheerful after that. I am glad I never lived in the water, if it makes one so blue. Now I shall tell you what my babies will do, not what I have done. Of course it is the same thing, but it is looking forward rather than to the past. After this meeting is over I shall lay some eggs, on just what plant I haven’t yet decided, but it will be in the midst of a herd of aphides. Be sure of that. Aphides are plant lice,” she explained, seeing the question in Ruth’s eyes. “You will learn more of them later. Now as to the way I shall lay my eggs: First, from the tip of my body I shall drop a thick gummy fluid, and draw it out into a long, stiff, upright thread, and upon the end of this thread I shall fasten an egg. I shall lay a number of eggs in this way, each on its own pole, so to speak. Some people may think my way odd, but it is very wise. A lacewing knows her children. They are not beautiful. Such short-legged, spindle-shaped things couldn’t be pretty, but they are sturdy, and they have an endless appetite.” “I should think they would feel lonely on those ridiculous poles,” said Mrs. Ant Lion. “Not at all. They are not there long enough to feel lonely. They are in too great a hurry for dinner. They are hungry, with a big H. Now just suppose I should lay my eggs as the rest of you do, ever so many together, what do you think would happen? I will tell you in a few words. The dear child who came out first would eat all his unhatched brothers and sisters. He doesn’t, only because he can’t reach them.”
  • 34. “It’s a wonder he doesn’t eat his pole,” said Ruth, her face showing what she thought of such babies. “Yes, it is,” agreed Mrs. Lacewing, “but, strange to say, he doesn’t seem to care for it. Indeed, he leaves it as quickly as he can, and goes hunting. Of course he needn’t hunt far, for he is in the midst of aphides. Every mother looks out for that, and really it is quite a pleasure to see him suck the juice from aphid after aphid, holding each one high in the air in his own funny way. So you can see why lacewing babies are friends to the farmer and the fruit grower, for aphides kill plants and trees, and young lacewings kill aphides. They can eat and eat and eat, and never grow tired of aphides. Indeed, they really deserve their name—aphislion. When they do stop eating it is to fall into their long sleep, but first they weave a cocoon as beautiful as a seed pearl, in which they change into a most lovely creature—one like me. Now our meeting is adjourned, and I hope a certain person has learned a few things.” “Oh, ever and ever so many, thank you,” answered Ruth gratefully.
  • 36. R CHAPTER VI RUTH GOES TO A CONCERT Oh, sweet and tiny cousins that belong, One to the fields, the other to the hearth, Both have your sunshine. —Leigh Hunt. uth and Belinda were crossing the meadow, when a big grasshopper made a flying leap, and landed on Belinda’s head. “Do excuse me,” he said; “I missed my aim. No one hurt, I hope, or frightened?” “Oh, no,” answered Ruth. “Belinda is real sensible; she isn’t afraid of anything, and I am just as glad—as glad—to see you. Maybe you will——” Ruth hesitated, hoping he would know what she meant to say. She was sure he could tell her a great many things, if only he would. He was so polite and nice; besides, he looked very wise. “I suppose you’re going to the concert,” said Mr. Grasshopper, after waiting a second for Ruth to finish her sentence. “Concert?” she repeated, opening her eyes wide. “What concert?” “Why the Straightwings’ Concert. They give one every sunny day in Summer. Didn’t you know that? Dear me, where were you hatched and where have you been living since? Well, why do you stare at me so? Don’t you like my looks?” “Oh, yes,” Ruth hastened to answer. “You look very nice— something like a little old man.” “I’ve heard that before, and there’s a story about it. Shall I tell it?” “Yes, please; I just love stories.”
  • 37. “Very well. Once upon a time, long, long ago, there lived in Greece a beautiful young man named Tithonus. Now it chanced that Tithonus loved Aurora, the Goddess of the Dawn.” “Greece?” said Ruth. “Why, that’s where Arachna lived, the one who turned into a spider, you know?” “Do you want to hear my story or don’t you?” asked Mr. Grasshopper, sharply. “I do want to hear it. I really do.” “Very well, then, don’t interrupt me again. As I was saying, Tithonus loved Aurora, and every morning he would lie in the meadow and wait for her coming. Then the fair goddess would give him her sweetest smiles. But one day Tithonus grew pale and ill, and all the love of Aurora could not make him well again. ‘Alas!’ he cried, ‘I am mortal, and I must die.’ ‘Nay,’ answered Aurora, ‘you shall not die, for I will win for you the gift of the gods.’ And, speeding to the mighty Jupiter, she begged that Tithonus might be as a god, and live forever. So for a while they were happy together, but as the years passed Tithonus grew old and bent, for Aurora had forgotten to ask that he might always be young. Grieving much, Tithonus lay under the shadow of the trees and sighed through the long days.” “‘Ah, my Tithonus,’ whispered Aurora, ‘I love you too well to see you thus unhappy. No more shall you be sad or bend beneath an old man’s weakness, but, as a child of the meadow, happy and free, you shall sing and dance through the golden hours.’ In that moment Tithonus became a grasshopper, and ever since then his descendants have danced and sung in the sunshine. That’s the end of the story. I might have made it twice as long, but Summer is so short, and I want to dance.” “It was a very nice story,” said Ruth, “but do you really dance?” “Of course, our kind of dancing.” “But don’t you do lots of other things too?” “Yes; we give concerts, and we eat. We are hatched with big appetites, and a strong pair of jaws, and we start right in to use them on the tender grasses around us. We only follow our instincts, though men call it doing damage. You eat, don’t you?” “Why, yes, but I don’t eat grass, you know.”
  • 38. “Because it isn’t your food. You see it’s this way: In the kingdom of nature all creatures have a certain work to do, and each is exactly fitted for its place, for all are governed by laws more wonderful than any man has made. Not that I wish to speak lightly of man, he is good enough in his place, but he is apt to think himself the whole thing, and he isn’t. Maybe he doesn’t know that for every human creature on earth there are millions of plants and animals.” “Oh,” said Ruth, “really and truly?” “Really and truly. You couldn’t begin to count them, and do you know, if the earth was to grow quite bare, with only one living plant left on it, the seeds from that one plant could make it green again in a very few years. But if certain insects were left without other creatures to eat and keep them down, the poor old earth would soon be bare once more. So you see there must be laws to fix all these things. Nature balances one set of creatures against the other, so there will not be too many of any kind.” Ruth had listened in open-eyed astonishment. Surely this was a very wise grasshopper. “You know a great deal,” she managed to say at last. “Yes, I do,” was the answer. “I heard two men say the things I’ve just told you. They were walking across this meadow, and I listened and remembered. You see, I believe in learning even from men. But do listen to the concert—we are right in the middle of it.” THE WISE GRASSHOPPE R They certainly were in the middle of it. The zip, zip, zip, zee-e-ee-e of the meadow grasshoppers seemed to come from every part of the
  • 39. sunny field, while the shorthorns, or flying locusts, were gently fiddling under the grass blades, their wing covers serving for strings, and their thighs as fiddle bows, and the field crickets, not to be outdone, were scraping away with the finely notched veins of the fore wings upon their hind wings. The longhorns were also there, some in green, others in brown or gray, all drumming away on the drum heads set in their fore wings. “You would hear katydid too,” said Mr. Grasshopper, “only he refuses to sing in the day. He hides under the leaves of the trees while it is light, and comes out at night. If you think me wise, I don’t know what you would say of him. He is such a solemn-looking chap, always dressed in green, and his wing covers are like leaves. You might think him afraid if you saw him wave his long antennæ, but he isn’t. He is curious, that’s all. It is a high sort of curiosity, too, like mine—a wish to learn. I suppose you know we don’t make our music with our mouths?” he asked suddenly. “Well, that is something,” he added, as Ruth nodded “Yes.” “I sing with the upper part of my wing covers, but my cousins, the shorthorns, sing with their hind legs. Why do you laugh? Aren’t legs as good to sing with as anything else?” “I—I suppose so,” said Ruth. “It sounds funny, because I am not used to that kind of singing.” “Just it. Now I shall tell you a few more facts about us. We belong to the order of the Straightwings, or the Orthoptera, as the wise men call it.” “Will you please tell me what that means?” asked Ruth. “Do all insects belong to something ending in tera? Most everything I have talked to does except toads and spiders.” “And they are not insects,” said Mr. Grasshopper. “Not even the spiders. The word insect means cut into parts, and all insects have three parts, a head, and behind that the thorax or chest, and the abdomen. Then, too, they always have six jointed legs. Now maybe you have noticed that spiders are not built on this plan? There are only two parts of them. The head and thorax are in one. It is called the cephalothorax. I’d feel dreadfully carrying such a thing around with me, but the spiders do not seem to mind it. Their other part is their abdomen. I heard a little boy say it was like a squashy bag; and
  • 40. between ourselves that is about what it is. Of course you know that spiders have eight legs and that alone would settle the question. True insects never have but six. Now as to the orders: All insects are divided into groups, and it is something about the wings which gives them their names. That is why they all end in ptera, because ptera comes from pteron, a word which means wing. It isn’t an English word, you know, but is taken from a language called Greek.” Ruth listened very patiently. If she had heard all this in school it would have seemed very dry, but when a grasshopper is telling you things it is of course quite different. “But I am sure I can never remember it all,” she said. “Ah, yes, you can. Remembering is easy if you only practise it.” “Why, that’s like the White Queen,” cried Ruth. “She practised believing things till she could believe six impossible things at once, before breakfast.” “I don’t know the person,” said the grasshopper. “She lived in the Looking Glass Country,” began Ruth, but Mr. Grasshopper was not listening. “You have met the Diptera, or Two Wings,” he said. “That’s easy. Then you’ve met the Neuroptera, or Nerve Wings. That’s easy too. And now you have met the Orthoptera, or Straightwings, meaning me, and if I’m not easy, I should like to know who is. You see our wings are——” “Wings?” said Ruth in surprise. “Of course. Look here,” and opening his straight wing covers, Mr. Grasshopper showed as nice a pair of wings as one could wish to possess. “Not all of us have wings,” he added, folding his own away, “but those of us who have not live under stones. Our order includes graspers, walkers, runners, and jumpers. Not all are musicians. The graspers live only in hot countries. Maybe you have seen the picture of one of them—the praying mantis he is called, just because he holds up his front legs as if he were praying. But it isn’t prayers he is saying. He is waiting for some insect to come near enough so he may grab and eat it. That will do for him. Next come the walkers. The walking stick is one, and he isn’t a good walker either, but the stick part of the name fits him. He is dreadfully thin. There is one on that
  • 41. twig now, and he looks so much like the twig you can scarcely tell which is which.” “Why, so he does,” said Ruth, poking her finger at the twig Mr. Grasshopper pointed out. “Isn’t he funny?” “Indeed,” grumbled the walking stick. “Maybe you think it polite to come staring at a fellow, and sticking your finger at him, and then call him funny, but I don’t. I want to look like a twig. That’s why I am holding myself so stiff. I have a cousin in the Tropics who has wings just like leaves.” “Yes,” added the grasshopper, “and his wife is so careless she just drops her eggs from the tree to the ground and never cares how they fall.” “Well, if that suits her no one else need object,” snapped the walking stick. “I believe in each one minding his own business.” “An excellent idea,” said Mr. Grasshopper. “Now let me see, where was I? Oh! the runners; but you’ll excuse me, I will not speak of them at all. They include croton bugs and cock roaches, and it is quite enough to mention their names. With the jumpers it is different. They are the most important members of the order. I’m a jumper, I am also a true grasshopper. You can tell that by my long slender antennæ, longer than my body. For that reason I am called a longhorn, but my antennæ are really not horns.” “I don’t see how any one could call them horns,” said Ruth. “No more do I, but some people have queer ideas about things. Well, I don’t care much. There is my mate over there. Do you notice the sword-shaped ovipositor at the end of her body? She uses it to make holes in the ground and also to lay her eggs in the hole after it is finished. Yes, she is very careful. Her eggs stay there all Winter, and hatch in the Spring, not into grubs or caterpillars, or anything of that sort. They will be grasshoppers, small, it is true, and without wings, but true grasshoppers, which need only to grow and change their skins to be just like us. And I’m sure we have nothing to be ashamed of. We have plenty of eyes, six legs, and ears on our forelegs, not like you people who have queer things on the sides of your heads. Such a place for hearing! but every one to his taste. Well, to go on, we have wing covers, and lovely wings under them, a head
  • 42. full of lips and jaws, and a jump that is a jump. What more could one wish? Do you know what our family name is?” Ruth didn’t know they had a family name, so of course she could not say what it was. “It is Locustidae,” said Mr. Grasshopper, answering his own question. “Funny too, for there isn’t a locust among us. Locusts are the shorthorned grasshoppers—that is, their antennæ are shorter than ours. They are cousins, but we are not proud of them. They are not very good.” “No one is asking you to be proud,” said a grasshopper, jumping from a nearby grass blade. She had a plump gray and green body, red legs, and brown wings, with a broad lemon-yellow band. “What’s the matter with me?” she demanded. “I guess you don’t know what you are talking about. It’s the Western fellow that is so bad. We Eastern locusts are different.” “Well, I suppose you are,” agreed the longhorn. “I know the Western locusts travel in swarms and eat every green thing in sight. They are called the hateful grasshoppers.” “No one can say that our family has ever been called hateful or anything like it,” said a little cricket with a merry chirp. “We are considered very cheery company, and one of the sweetest stories ever written was about our English cousin, the house cricket.” “I am sure you mean ‘The Cricket on the Hearth,’” said Ruth. “It is a lovely story, and I think crickets are just dear. Are you a house cricket too?” “No, I belong to the fields, and I sing all day. Sometimes I go into the house when Winter comes and sing by the fire at night, but my real home is in the earth. I dig a hole in a sunny spot and Mrs. Cricket lays her eggs at the bottom, and fastens them to the ground with a kind of glue. Sometimes there are three hundred of them, and you can imagine what a lively family they are when they hatch.” “I should like to see them,” said Ruth, for it was quite impossible for her to imagine so many baby crickets together. “Well, it is a sight, I assure you,” answered the little cricket. “Did you ever come across my cousin the mole cricket? She is very large and quite clever. She makes a wonderful home with many halls around her nest. She is always on guard too so that no one may touch
  • 43. her precious eggs. Then I have another cousin, who doesn’t dress in brown like me, but is all white. He lives on trees and shrubs and doesn’t eat leaves and grass as we do. He prefers aphides. You can hear him making music on Summer evenings. We crickets seldom fly. We——” The sentence was not finished, for just then a long droning note grew on the air, increasing in volume, until it rose above the meadow chorus. “Oh!” cried Ruth, spying a creature with great bulging eyes and beautiful, transparent wings, glittering with rainbow tints, “There’s a locust! Isn’t he beautiful, Belinda? Maybe he will tell us some things. Oh, Belinda, aren’t we in luck?”
  • 45. “A CHAPTER VII RUTH MEETS MANY SORTS AND CONDITIONS The shrill cicadas, people of the pine, Make their summer lives one ceaseless song. —Byron. locust, indeed,” said the newcomer, and Ruth could see plainly that he was not pleased. “It does seem to me you should know better than that. Can’t you see I have a sucking beak and not a biting one, like the grasshopper tribe? Besides, my music isn’t made like theirs. No faint, fiddly squeak for me, but a fine sound of drums.” “I think I’ll move on,” said Mr. Grasshopper, and Ruth could see that he was quite angry. She turned to look at the cricket, but he was far across the field, fiddling to his mate. “I wish you wouldn’t go,” she said to the grasshopper. “You have been so nice to me and I have learned ever so much from you.” “Oh, I dare say,” was the answer. “More than you will learn from some people I could mention, but I really must leave you. My mate wants me.” And a flying leap carried him quite away. “There, we are rid of the old grandfather,” said the cicada, “and now what can I do for you?” “Tell me your real name if it is not locust,” answered Ruth. “It certainly is not locust. I’ve been called a harvest fly, though I am not a fly either. I’m a cicada, and nothing else, and I belong to the order of bugs.” “And what kind of tera is it?”
  • 46. “Tera?” repeated the cicada, looking at her with his big eyes. “Oh, yes, yes, I understand. You mean our scientific name. It is Hemiptera, meaning half-wings. I know we have some objectionable members, but I don’t have to associate with them, and I rarely mention their names. I have a cousin who lives in the ground seventeen years. Think of it! Of course he is only a grub and doesn’t care for air and sun. I lived there two years myself, but I was a grub also then. You see my mother put her eggs in the twig of a tree, and when I came out of one of them I wanted to get to the ground more than I wanted anything else, so I just crawled out to the end of the branch and let go. Down I went, over and over, to the ground, where I soon bored my way in, and began to suck the juices of the roots about me. I liked it then, but I couldn’t stand it now. Of course the moles were trying. They were always hungry and we were one of the things they liked for dinner. One day something seemed to call me to the world of light, and I came out a changed being—in fact, the beautiful creature you see before you now. Perhaps you do not know how much attention we have attracted? In all ages poets have sung of us, even from the days of Homer. Maybe you will not believe me, but the early Greeks thought us almost divine, and when Homer wished to say the nicest things about his orators he compared them to cicadas. A while ago I told you we were sometimes called harvest flies. We have also been given the name Lyremen. Shall I tell you why?” “A story!” cried Ruth, clapping her hands. “Oh, yes, please tell it!” “Very well. Once upon a time, ages ago, a young Grecian player was competing for a prize, and so sweet was the music he drew from his lyre that all who heard it felt he must surely win. But alas! when he was nearly finished one of his strings snapped, and, with a sad heart, he thought that all his hope was gone. Not so, however, for a cicada, drawn from the woods by the sweet sounds, had perched upon the lyre and when the musician’s trembling fingers touched the broken string it gave forth a note that was clear and true. Thus again and again the cicada answered in tones that were sweet and full. When the happy player realized that the cicada had won the prize for him, he was so filled with gratitude that he caused a full figure of himself to be carved in marble, and in his hand a lyre with a cicada
  • 47. perched upon it. Now wouldn’t you be proud if your family had such a nice story about them?” “I’m sure it is very nice,” agreed Ruth. “Yet I’m not one to brag,” added the cicada, “and I am never ashamed to say I’m a bug. Now if you will come with me to the pond I will show you some of my cousins. They are very interesting.” And with a whiz the gauzy-winged fellow darted up into the sunshine, and Ruth, following him across the meadow, could only hug Belinda in a rapture of expectation, and whisper in a low voice: “Aren’t we in luck, Belinda—just the best kind of luck?” They had gone only a little way, however, when a mole pushed his strong little snout above the ground. “Gracious! what a noise,” he said. “If I had had a chance when you were a baby you wouldn’t be here now to disturb quiet-minded people.” Ruth jumped. She thought the mole meant he would have eaten her. Then she laughed. “Of course it was the cicada he was talking to,” but the cicada didn’t mind. “I know that very well,” he answered, cheerfully, “but you didn’t get me. That makes all the difference, and now you can’t.” “Well, nobody wants you now. You would be mighty dry eating, but when you were a grub, oh, my! so fat and juicy, like all the other grubs and slugs and worms. I eat you all. Yet what thanks do I get from man for doing away with so many of his enemies? Complaints, nothing but complaints, and just because I raise a few ridges in the ground. I can’t help that. When I move underground I push the earth before me, and, as it has to go somewhere, it rises up.” “What do you push with?” asked Ruth, sitting down in front of the mole. “With my snout and forepaws,” he answered, “what else? The muscle which moves my head is very powerful, and you can see how broad my forepaws are, and, also, that they turn outward. They help to throw back the earth as I make my way forward. I have ever so many sharp little teeth, too, and my fur lies smooth in all directions, so it never rumples and——”
  • 48. “Do come on,” interrupted the cicada; “that fellow isn’t interesting.” “That’s so,” said a thin little voice, as an earthworm cautiously lifted his head from the ground. “Has he gone?” he asked anxiously. “He’d eat me sooner than wink if he saw me. It is warm and damp this morning, that is why I am so near the surface. I don’t like dry or cold weather. My house——” “Have you a house?” Ruth had turned upon him in a second, full of questions as usual. “Certainly I have a house. It is a row of halls, lined with glue from my own body. The walls are so firm they can’t fall in. Underground is really a delightful place to live, snug and soft, cool in Summer, warm in Winter. Lots to see, too. All the creeping, twining roots and stems reaching out for food, storing it away, or sending it up as sap to the leaves. The seeds waking up in the Spring, and hosts of meadow and wood people wrapped in egg and cocoon, who spend their baby days there. Quite a little world, I assure you. Of course I can’t see any of these things. I have no eyes.” “Oh!” said Ruth, “how dreadful!” “No, it is just as well. If I had eyes I might get earth in them. I go through the ground so much.” “But isn’t that awful hard work?” asked Ruth, shutting her eyes to realize what having no eyes might mean. “It isn’t hard when one has a nice set of bristles, as I have to help me along.” The earthworm was one who saw the best side of everything. “I am made up of more than a hundred rings,” he went on, “and on each are small stiff hair-like bristles so, though I have neither eyes, ears, hands, nor feet, I am quite independent. I can move very fast, and the slime that covers me keeps the earth from sticking to me. Do you know I am the only jointed animal that has red blood? It is so. I do no harm, either, to growing things, and I help to build the world. My tunnels let air into the ground and help to keep it loose. I also bring up rich soil from below, and lay it on the surface. I also——” “Well, that’s enough,” interrupted the cicada, moving his wings impatiently. “I thought you wanted to see my relations?” he added to Ruth.
  • 49. “So I do,” answered Ruth. “Where are they?” “There are a number of them right in this meadow, though you would never think it, to look at them. They are not at all like me. See that white froth clinging to those grass stems? A cousin made that. Of the sap of the plant too. If you look, you will find her in the midst of it. She is green and speckled and very small. Then there are the tree hoppers, as funny in shape as brownies, and the leaf hoppers. They are all my cousins. The aphides too. Of course you know the aphides?” “I believe they were the things Mrs. Lacewing told me I should learn about later,” said Ruth, with sudden remembrance. “Very likely. Mrs. Lacewing’s children should know about them. The aphides are very bad, though they are so very tiny. But what they lack in size they make up in numbers. Really there are millions of them. They are not travellers, either, but stay just where they are hatched, and suck, suck, suck. In that way they kill many plants, for it is the sap of the plant, its life juice, which serves them for food. They eat so much of this that their bodies can’t hold it all, and what they don’t need is given off as honey dew. The ants like this honey so well that to get it they take good care of the aphides. But there are some aphides which do not give off honey dew. Do you see this white stuff on the alder bushes?” “Yes. I’ve often seen it before, too. It looks like soft white fringe.” “Well, it isn’t. It is a lot of aphides, each with a tuft of wool on its body, and a beak fast stuck in the alder stem.” They had now reached the pond, which lay smiling in the sunshine. “It would be so pretty,” said Ruth, throwing herself down on the grass, “if it wasn’t for the horrid, green, oozy stuff all over it.” “Horrid, green, oozy stuff?” repeated the cicada. “Child, you don’t know what you are talking about. That green stuff is made up of tiny green plants more than you could count. Each has a rootlet hanging down like a silver thread and leaves almost too small to be called so. They are green though and they do the mighty work of all green leaves, for, besides shading the pond world from the hot rays of the sun, they make for the many inhabitants the life-giving oxygen without which they would die. And I want to tell you something
  • 50. more: In that duckweed—for what you call green, oozy stuff is duckweed—there are millions of tiny living things too small to be seen by the eye except with the aid of a microscope.” Ruth looked quite as astonished as the cicada meant she should be. “You have a great deal to learn, I assure you. Maybe you haven’t thought of the pond as a world, but just see what a busy place it is.” Ruth looked and agreed with the cicada. Dragon flies were darting here, there, and everywhere; frogs, with their heads out of the water, seemed to be admiring the scenery when they were not swallowing air or whatever else came in their way; glancing minnows and bright- eyed tadpoles played amongst the swaying water weeds; even the wrigglers were there, standing on their heads in their own funny way; and the water striders, skating after their own queer fashion. Yes, it was a busy place. A party of whirligig beetles came dashing by, circling, curving, spinning, and making such a disturbance that a backswimmer lost his patience and told them to be quiet. They didn’t like that at all, so they threw about him a very disagreeable milky fluid which made the backswimmer dive for the bottom in a hurry. “That settled him,” said one of the whirligigs. “Hello! friend Skipper Jack,” he called to a water strider, “what are you doing?” “Skating, of course,” answered the water strider. “There, they are gone,” he added, to the cicada, “and I am glad of it. They are nuisances.” “You are right,” agreed the cicada. “I am glad they don’t belong to our order.” “Don’t they?” asked Ruth. “I think they are awfully funny.” “Funny or not, they are beetles,” answered the water strider. “You had better use your eyes. Do you know why I can skate and not get my feet wet? No, of course you don’t, and yet it is as plain as the nose on your face. I have a coat of hairs on the under side of my body. That’s why. I spend my time on the surface of the water, for my dinner is right here. Plenty of gnats, insect eggs, and other eatables. Then if I wish I can spring up in the air for the things that fly. My
  • 51. Winters I spend under water, but for other seasons give me the surface.” “And I like the bottom best,” said a water boatman, showing himself quite suddenly, his air-covered body glittering like silver armour. “Another cousin,” whispered the cicada in Ruth’s ear. “He is called the water cicada, as well as water boatman.” “He looks more like a boat than he does like you,” said Ruth. “My body is boat-shaped,” spoke up the boatman; “and see my hind legs; they really are like oars, aren’t they?” “I am wondering what brought you to the surface,” said the cicada. “Why, I let go my hold on that old water weed, and you know the air that covers my body makes it lighter than the water and unless I cling to something I naturally rise. It is inconvenient, for I do not need to come to the surface for air. I can breathe the same air over and over, because I know how to purify it.” “How do you do it?” asked Ruth. Surely these insects were wonderfully clever. “Oh, I simply hang to something with my front legs, while I move my back ones just as I do in swimming, and that makes a current of water pass over my coat of air and purify it. That fellow swimming on his back over there is obliged to come to the surface every little while. He carries air down in a bubble under his wings.” “Do you mean me?” asked the backswimmer, making a sudden leap in the air, and flying away. “Gracious!” cried Ruth in surprise. “I didn’t know he could fly.” “There’s a good deal you don’t know,” replied the water boatman, a remark Ruth had heard before. “I can fly too,” and he also spread his wings and was off. “Well,” said the cicada, “I guess we might as well be off too. There seems to be no one in sight to interest us.” “What about cousin Belostoma?” asked a sort of muffled voice, as a great pair of bulging eyes showed themselves above the water, and out came the giant water bug as big as life. “I’ve just had my dinner,” he said. “It really is funny to see how everything hides when Belostoma shows his face. My wife is the only
  • 52. one who doesn’t seem to be afraid of me and she—well, she’s a terror and no mistake.” “Why, what’s the matter now?” asked the cicada. “And what has happened to your back?” added Ruth, with eager curiosity. “My wife’s happened, that’s what,” answered Belostoma in a doleful tone. “She laid her eggs a while ago and glued every blessed one to my back. It is nothing to laugh at either. There’s no joke in being a walking incubator. Well, I must be going now. It is dinner time.” “I thought you just had your dinner,” said Ruth. “Yes, but it’s time again. It is always time. How silly you are.” “I must go too,” said the cicada, “but it isn’t dinner that calls me. I feel sure my mate is longing for some music and I’m off to give her a bit. See you later.” And, spreading his wings, the cicada flew away, beating his drums as he went.
  • 54. S CHAPTER VIII MRS. TUMBLE BUG AND OTHERS Their wings with azure green And purple glossed. —Anna L. Barbauld. omething exciting was going on. Ruth could not tell just what it was at first. She could only watch and wonder. Then her eyes grew large and bright. Surely some fairy’s wand had touched the old orchard, for suddenly it seemed alive with beetles—big beetles and little beetles; beetles in sober colourings, and beetles gleaming with all the tints of the rainbow. Ruth had never dreamed that there could be so many of them or that they were so beautiful. The gorgeously coloured, graceful tigers attracted her first, though she didn’t know their name. “Oh,” she cried, “how lovely!” “And how strange,” added a voice just above her head, “how very strange, their children should be so homely.” “What’s that?” asked one of the tigers, a metallic green fellow, with purple lights, and two pale yellow dots on the edge of each wing cover. “Our children not so beautiful as we are, did you say? Of course, they are not; a fat grub couldn’t be, you know. But let me tell you, there are few things as smart as a tiger beetle baby. I say,” he added, looking full at Ruth, “have you ever seen the hole he digs? It is often a foot deep, while he is less than an inch long. He has only his jaws and fore legs to work with too. Yet he piles the earth on his flat head as if it were the easiest thing in the world, and then, climbing to the top, he throws it off, and is ready for another load.”
  • 55. “I suppose he digs a hole to catch things,” said Ruth, “like the ant lion, and does he stay at the bottom and——” “No, he doesn’t stay at the bottom. He watches near the top of his hole for his dinner, hanging on by a pair of hooks which grow out of a hump on his back. He always goes to the bottom to eat his dinner, though; he seems to like privacy. Yes, we are a fierce family from the beginning, for we grown tigers can catch our prey either running or flying, and we usually manage to get it, too. But, then, farmers need not complain of us, for we never eat plants, and that is more than can be said of many here.” “Such taste,” said a cloaked, knotty horn, holding herself in a position that showed off her changeable blue and green dress, and her short yellow cape. But the tiger did not answer. He was off after his dinner. Several tree borers, however, nodded their heads in agreement. “I believe in a vegetable diet myself,” said Mrs. Sawyer, who wore as usual her dress of brown and gray. “It is just such people as the tigers who make things like that necessary in a respectable meeting,” and as she spoke she waved her very long antennæ toward a big sign which read: “THE AUDIENCE ARE REQUESTED NOT TO EAT EACH OTHER DURING THE MEETING” “I am glad to say I am not one of that kind. I wonder if any one of you know why the members of our family are called sawyers. Perhaps I had better tell you: It is because our children saw into the trunks of evergreen trees, and sometimes they make holes large enough to kill the trees. Smart, isn’t it, for a baby?” “But it doesn’t seem to be very nice,” began Ruth. Then she stopped, for Mrs. Sawyer was looking at her and the borers were nodding their heads again. “Our children do not saw,” said the borers, “but they do bore, and it is pretty much the same thing for the tree.” “My friends,” broke in a very solemn voice. Every beetle stopped talking, and Ruth jumped to her feet, then flopped down on the grass again, waiting for what was coming.
  • 56. The speaker, a large, clean-looking beetle, had just flown to a twig in the very middle of the meeting. He was black in colour, well sprinkled above and below with pale straw yellow in dots and points, but the queer thing about him was the two oval velvety black spots, each with a narrow line of straw colour around it, on his thorax. They were like great eyes, and made him look very wise. “He is the eyed-elater,” whispered Mrs. Sawyer to Ruth. “There he is speaking again.” “My friends,” the big beetle was saying in tones as solemn, as before, “the important thing in any meeting is to keep to the main issue.” “The main issue?” said the goldsmith beetle, a beautiful little creature with wing covers of golden yellow, and a body of metallic green covered with white, woolly fuzz. “What is the main issue?” “Dinner,” replied the tiger beetle, returning to his old place. “If it isn’t breakfast or supper.” “No, my friend,” said the eyed-elater, with a grave glance, “the main issue is——” Then he stopped and fixed his two real eyes and the two spots which looked like eyes on some small beetles which were leaping in the air, turning somersaults, and making quite a noise. “Will you be still?” he said in his sternest voice. “How foolish,” said Mrs. Sawyer, “to expect click beetles to be still!” But Ruth was all curiosity. “I’ve seen you before,” she said, going closer and touching one of the funny little fellows. Suddenly it curled up its legs, dropped as if shot, then lay like one dead. “Here, here!” called the elater. “No more of that! We know all about your tricks!” “All right,” said the would-be dead one, and he gave a click, popped into the air several inches, and came down on his back. “That won’t do at all,” he said, and, clicking and popping once more, he came down on his feet.
  • 57. “There,” he added, “you need to have patience with click beetles. You ought to know that, friend elater, for you are one of us.” “Well, I’m bigger, and not so foolish, and my children are not so harmful as yours. Think of being a parent of those dreadful wire worms! That is what you click beetles are, and you know the farmer hasn’t a worse enemy. Now we must get back to the main issue.” “Back?” said Mrs. Sawyer. “Were we ever there to begin with? You can’t scare me,” she added, “no matter how hard you stare. You haven’t any more eyes than the rest of us. Those two spots are not real eyes, and you know it.” “The main issue,” repeated the elater in a very loud voice, “is, What makes us beetles?” “That’s something I’d like to know,” said a handsome little beetle in a striped coat. “I’m a beetle, if there ever was one, yet I have a world-wide reputation as a bug.” “Pray don’t get excited, Mrs. Potato Bug. It isn’t your time to talk yet. We are on the main issue, and I will answer my own question.” Ruth was glad some one would answer it, for at this rate it seemed they would never get anywhere. “We are beetles for several reasons,” went on the elater. “In the first place, we belong to the order Coleoptera.” Another tera, thought Ruth. “That name is taken from a language called Greek, and means sheath wing. It is given to us because we have handsome outside wings which we use to cover our real flying wings. All beetles have them, though those of our cousin, Mr. Rove Beetle, are quite short.” “That’s a fact,” said a rove beetle, “and no one need think we have outgrown our coats. It is simply a fashion in our family to wear our sheath wings short. We can always fold our true wings under them, and I’d like to see the fellow who says we can’t.” “Well, you needn’t get so mad about it,” answered the elater in mild tones. “And don’t curl your body up as if you were a wasp,” added Mrs. Sawyer. “Everybody knows you can’t sting.” “I don’t care,” said the rove beetle. “I hate to be misunderstood. We are useful too. I heard a man call us scavengers. I don’t know
  • 58. what it means, but something good, I am sure, from the way he said it. I must be going soon. It is so dry here. You know my home is in damp places under stones or leaves.” “You may go when you wish,” answered the elater. “We are still on the main issue. As I said before, we are beetles, and there is no reason to take us for bugs. Calm yourself, Mrs. Potato Bug. We have no sucking beak as the bugs have, but we have two sets of horny jaws, which move sideways, and not up and down. These are to bite roots, stems, and leaves of plants, so most of our order live on vegetable food and are enemies to the farmer, but some of us are his friends, for we eat the insects that injure his crops. Our children are called grubs. Some of them make a sort of glue, with which they stick together earth or bits of wood for a cocoon; others make tunnels in tree trunks or wood and transform in them. We may well be proud, for we belong to a large and beautiful order, and we are found in all parts of the world. We are divided into two sub-orders—true beetles and snout beetles. I hope our cousins, the snout beetles, will not be offended. They are real in a way.” “The farmer and fruit grower think so anyway,” said a little weevil. “We have been called bugs just because we have a snout, but any one can see at a glance that it isn’t a bug’s snout. It is not a tube at all, but has tiny jaws at the tip.” “I don’t believe I could see all that,” said Ruth rather timidly, for these clever little people had a way of making her feel she knew very little. “Maybe you can’t,” was the short answer, “and I dare say you can’t tell how we use our snouts either. We punch holes with them in plums, peaches, cherries, and other fruits, not to mention nuts and the bark of trees. I am a peach curculio, but that is not important. We all work in the same way—that is, drop an egg in the hole made by our snout, then use the snout again to push the egg down. Mrs. Plum Weevil is busy now in the plum orchard back of us; so of course she couldn’t come to this meeting. ‘Duty before pleasure,’ she said. She will lay eggs in quite a number of plums, and the plums will drop from the trees before they are ripe.” “And there’ll be a lump of gum on them!” cried Ruth, clapping her hands.
  • 59. The weevil looked at her with approval. “You do notice some things,” she said. “The gum oozes out of the hole made by our snouts. Of course our egg hatches inside the fruit, and the baby has its dinner all around it. As it hasn’t a leg to walk on——” “Dear! dear!” sighed the elater. “You seem to forget that we are trying to keep to the main issue. As I said before——” “You are always saying what you said before,” snapped Mrs. Sawyer. “Now, they are beginning again,” thought Ruth, but the elater paid no attention to Mrs. Sawyer. “As I said before,” he repeated, “we have reason to be proud, for though we build no cities, like ants, wasps, and bees, and make no honey or wax, or have, in fact, any special trades, yet we are interesting and beautiful. The ancient Egyptians thought some of us sacred and worshipped us.” “There!” cried Mrs. Tumble Bug, literally tumbling into their midst. “I couldn’t come at a better time.” Ruth gave a little scream of delight when she saw her, and Mrs. Tumble Bug nodded with the air of an old friend. As usual, her black dress looked neat and clean, though she and her husband had rolled and tumbled all over the road in their effort to get their ball to what they considered the best place for it. They had succeeded, and Mrs. Tumble Bug’s shovel-shaped face wore a broad smile in consequence. “I knew about this meeting,” she said, “but my husband and I agreed that duty should come before pleasure.” “She heard me say that,” whispered the little peach weevil to her nearest neighbour. “I didn’t,” answered Mrs. Tumble Bug. “I have just come. We only found a safe place for our ball a little while ago.” “That ball!” said Mrs. Sawyer in disgusted tones. “I should think you would be tired of it.” “Tired of our ball?” repeated Mrs. Tumble Bug. “Why, our ball is the most important thing in the world. This was a big one, too. We made it in Farmer Brown’s barnyard, and then I laid my eggs in it,
  • 60. and we rolled it all the way here. Of course it grew on the road, and I couldn’t have moved it alone, but my mate helped me. He always helps. Indeed it seems to me tumble bugs are the only husbands in the insect world who care about their children’s future.” “Now I know,” said Ruth, who had been thinking very hard. “You think so much of your balls because they hold your eggs. I’ve often wondered about them.” “Of course that is the reason,” answered Mrs. Tumble Bug; “and when our eggs hatch the babies will have a feast all around them.” “Ugh!” said Ruth, and some flower beetles shook their little heads, and added: “It would be better to starve than eat the stuff in that ball.” “Tastes differ,” said Mrs. Tumble Bug, amiably; “but, speaking of sacred beetles, it was our family the Egyptians worshipped. They could not understand why we were always rolling our ball, so they looked upon us as divine in some way, and made pictures of us in stone and precious gems. They can be seen to-day, I am told, but I do not care about that. I must make another ball,” and, nodding to her mate, they left the meeting together. “Now we’ll adjourn for dinner,” announced the elater, much to the disgust of Mrs. Potato Bug, who was just getting ready to speak. “Dinner is well enough,” she said, “but how is one to enjoy it when one must stop in a little while?” “You needn’t stop,” answered the elater. “Stay with your dinner. We are not so anxious to hear you talk.” “But I mean to talk, and I will,” and Mrs. Potato Bug was off to the potato field, intending, as she said, to take a light lunch, and be back when the meeting opened. But potato bugs propose, and farmers dispose, and——
  • 63. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! testbankfan.com