Review Activity:1. Given the following lines of code, write a loop to read in the file word by word: string word; int count = 0;
fin.open("inputFile.txt"); while( ) { count++;
cout << "Word " << count << ": " << word << endl;
}
2. Given the following lines of code, write a loop to read in the file line by line:
string line; int count = 0;
fin.open("inputFile.txt"); while( ) { count++;
cout << "Line " << count << ": " << line << endl;
}
3. Write the following function which takes in a reference parameter:
void notString(string& str); //Given a string, return a new string where "not " has been added to the front. //However, if the string already begins with "not", return the string unchanged. //notString("candy") → "not candy" //notString("x") → "not x" //notString("not bad") → "not bad"
int main() {
string str = "candy"; notString(str); cout << "Should print /"not candy/": " << str << endl;
}
//write notString here
Introduction to Arrays
Using Lists for Data
- Often times we need to process a group of the same types of data
- For instance:
- Bank account transactions
- Salaries for employees in a company
- Test scores for a group of students
- Temperature data over some period of time
- Consider how we might process the following student test scores:
90 |
95 |
87 |
89 |
98 |
96 |
85 |
79 |
95 |
100 |
- With this data, we can calculate statistics like:
- Highest score
- Lowest score
- Average (mean) score
- Difference (deviation) of each score from the average
- We can write a program to read this data and make the calculations
- However, to calculate the difference from the mean, we need to first find the mean
- Thus, we have to process all the data twice: one to find the mean
and another to calculate the difference of each score from the mean
Storing Lists of Data
- If we know there are 10 inputs, we can use 10 separate variables.
int score1 = 90; int score2 = 95; int score3 = 87; int score4 = 89; int score5 = 98; int score6 = 96; int score7 = 85; int score8 = 79; int score9 = 95; int score10 = 100;
- However, declaring all of these variables and assigning them values is a very tedious process.
- Now, imagine there were 100 test scores... Or, an unknown number of test scores...
- We need another system!
- Fortunately, C++ has techniques we can use to organize lists of data
Defining Arrays
Initializing Array Items
- We specify which slot of an array to access with the
[] operator:
scores[4] = 98; - The indexes of arrays are numbered starting at 0
- We can assign a value to an array element any time after it is declared:
const int MAX_SCORES = 5;
int scores[MAX_SCORES];
scores[0] = 90;
scores[1] = 95;
scores[2] = 87;
scores[3] = 89;
scores[4] = 98;
- We can also initialize array elements in the declaration statement:
- Called static initialization
- We use a comma-separated list inside curly-braces
- For example:
int scores[] = { 90, 95, 87, 89, 98 };
- This produces the same array as in the previous example
- The compiler computes the size automatically by counting the items in the list
- If we want a larger array with only the first few elements initialized, we can use:
int scores[MAX_SCORES] = {90, 95, 87};
- Note that if we do not assign a value to an array element, its value is not known.
Accessing Array Items
- To access the slots in an array, we must specify which slot to use with the
[] operator - For instance:
scores[4] = 98; - The number inside the brackets is called an index or subscript
- In C++, the slots of an array are numbered starting at 0, as shown below:
scores = |
|
[0] |
[1] |
[2] |
[3] |
[4] |
[5] |
[6] |
[7] |
[8] |
[9] |
|
- Thus, assignment to the slot with an index of 4 is put into the fifth slot
Using Slots
Using Arrays to Collect Data Items
- Note that the index of an array can be any integer value
- Thus, we can use an integer variable for the index
- We can use an integer variable with a loop to read data into the array
- Also, we can display the contents of an array using a loop
- The following program shows an example of collecting and displaying data items
Example Program Using Arrays to Collect and Display Data Items
|
#include <iostream>
using namespace std;
int main() {
const int MAX_SCORES = 10;
int scores[MAX_SCORES];
cout << "Enter " << MAX_SCORES << " scores:\n";
for (int i = 0; i < MAX_SCORES; i++) {
cin >> scores[i];
}
cout << "You entered:\n";
for (int i = 0; i < MAX_SCORES; i++) {
cout << scores[i] << endl;
}
return 0;
}
|
Activity 20.1: My First Array (10pts)
- Copy the following program into a text editor, save it as
myarrays.cpp , and then compile and run the starter program to make sure you copied it correctly.
#include <iostream>
using namespace std;
int main() {
// Enter your code here
return 0;
}
- Inside
main() , add a statement to define an array named names that is suitable for holding a list of three (3) names. - Compile your code to make sure it has correct syntax.
If you have problems, ask a classmate or the instructor for help as needed.
- Assign values to each of the array elements like:
names[0] = "Abel Ableson";
- Add a for-loop to display all three array values.
- Compile your code to make sure it has correct syntax.
If you have problems, ask a classmate or the instructor for help as needed. - When you are finished, upload your source code to Catalyst.
Arrays as Function Parameters- When writing a function with an array parameter, we place an empty
[] after the parameter name:void print(int values[], int size);
- We pass the size of the array to the function so the function knows the size of the array
- There is no
size() member function for an array
- When we call the function, we do NOT include the
[] :print(data, size); // function call
- Instead, we pass in the name of the array.
- Unlike
other parameters, you can pass the array into the function and then
alter the array inside of the function without needing to return a new
array.
- For example, what do you think will be the result of running the following program?
#include <iostream>
using namespace std;
void fillArray(int data[], int size) {
for (int i = 0; i < size; i++) {
data[i] = i;
}
}
int main() { const int SIZE = 5; int data[SIZE]; fillArray(data, SIZE); for (int i = 0; i < SIZE; i++) { cout << data[i] << endl; } }- Note the use of
size parameter - The programmer must keep track of the size when working with arrays
- Note that arrays cannot be function return types
- Returning an array with a return statement is not necessary
Using the const ModifierActivity 20.2: Exploring Arrays (10 pts)- In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data.
- Create a source code file called
myarrays.cpp : - Add the following function to the code:
void print(const int values[], int size) {
for (int i = 0; i < size; i++) {
cout << values[i] << " ";
}
cout << endl;
}
- Compile your code to make sure it has correct syntax.
If you have problems, ask a classmate or the instructor for help as needed. - Declare and initialize an array for a list of 10 integer scores after the current arrays using the following code:
const int NUM_SCORES = 10;
int scores[NUM_SCORES] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};
- After declaring and initializing the array, call the
print() function using the code:cout << "Integer scores:\n";
print(scores, NUM_SCORES); - Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
Integer scores:
90 91 92 93 94 95 96 97 98 99
- Declare and initialize an array of
double values holding the the temperature values 25.7, 30.3, and 40.9
- Write another
print() function with two parameters: one for the array of double values and one for the size of the array. - After declaring and initializing the array, call the
print() function. - Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like:
Integer scores:
90 91 92 93 94 95 96 97 98 99
Double temperatures:
25.7 30.3 40.9
- Save your program source code and submit it to Catalyst when you are finished.
|