Schedule‎ > ‎

Lesson 6: More Strings and Arrays



Continuations

Questions from last class?

  • What will be printed after the following C++ statements have executed?
    int count = 1;
    while (count <= 3) {
        cout << count << " ";
        count++;
    }
    
    1. 1 2
    2. 1 2 3
    3. 2 3
    4. 1 2 3 4


6.1: More About Strings and Characters

Learner Outcomes

At the end of the lesson the student will be able to:

  • Iterate through a string and extract each character
  • Convert characters to digits
  • Use string functions


6.1.1: Strings Versus Characters

  • Remember that a string is a series of characters enclosed in double quotes such as:
    "Hello"  "b"  "3.14159"  "$3.95"  "My name is Ed"
  • We can store text in a variable of type string, like:
    string firstName;             // declaration
    firstName = "Edward";         // assignment
    string lastName = "Parrish";  // declaration + assignment
    cout << firstName << " " << lastName << endl;
    
  • On the other hand, a character is a single letter, number or special symbol
  • We enclose characters in a single quote, rather than a double quote, like:
    'a'   'b'   'Z'   '3'   'q'   '$'   '*'
  • Also, we store a a single character using a variable of type char, such as:
    char letterA = 'A';
    char letterB = 'B';
    
  • Each character is stored as a number, using its ASCII Table value
  • By declaring a char variable or using single quotes, C++ knows to treat the number as a character
  • Thus, when we print a character, we see a letter rather than a number:
    char letter = 'A';
    cout << letter << 'B' << endl;
    
  • As we can see, a string is made up of characters and characters are numerical codes
  • We can use this information to work with characters and strings

String Concatenation and Functions

  • Recall that we can join (concatenate) two strings or a string with a character
    string str = "abc";
    str = str + "1"; // allowed
    str = str + '1'; // allowed
    str = str + 1;   // NO
    str = str + 1.2; // NO
    
  • However, we cannot concatenate a string with a number
  • Because strings are objects, they have member functions
  • Two useful member functions we have studied are length() and substr()
  • length(): Returns the number of characters in a string
    string str = "Hello";
    cout << "The number of characters is " << str.length()
         << ".\n";
    
  • substr(in): Returns a substring of length n starting at index i
    string greeting = "Hello, World!\n";
    string sub = greeting.substr(0, 4);
    cout << sub << endl;
    
  • The position numbers in a string start at 0. The last character is always one less than the length of the string
    Hello,World!
    0123456789101112
  • string w = greeting.substr(7, 5);
    Hello,World!
    0123456789101112

Check Yourself

  1. True or false: strings are a sequence of characters.
  2. True or false: "A" and 'A' are the same.
  3. The following code is wrong because ________.
    cout << "3.14159" * 2;
    
    1. you cannot double PI
    2. 3.14159 is not exact enough to represent PI
    3. string may be added but not multiplied
    4. "3.14159" is not a number
  4. After the following code executes, it displays ________.
    char ch;
    ch = 'd' - 'a' + 'A';
    cout << ch << endl;
    
    1. 'D'
    2. D
    3. 68
    4. d


6.1.2: Indexing a String

  • Strings are stored in a character sequence starting at 0 (zero)

    String character positions

  • We can access any individual character of a string variable using square brackets [ ]
  • The general syntax is:
    stringVariable[index];
    
  • Where:
    • stringVariable: the name of your string variable
    • index: the number of the character position
  • For example:
    string str = "abcdef";
    char firstLetter = str[0];
    cout << firstLetter << str[1] << endl;
    
  • The above code displays:
    ab
  • Notice that the square bracket notation returns a char data type

Check Yourself

For the following string declaration, answer the questions below:

string str = "C++ Rules!";
  1. The value of str[0] is: ________
  2. The value of str[2] is: ________
  3. The value of str[4] is: ________
  4. The value of str[str.length() - 1] is: ________


6.1.3: Iterating Strings

  • Recall that member function length() returns the number of characters in a string variable:
    string s = "abcdef";
    unsigned n = s.length();
    
  • Since a string's length is always 0 or a positive number, the length() function returns an unsigned int type
  • After we know the length, it is easy to iterate through the individual characters of a string using a counting loop:
    cout << "Enter a word: ";
    string msg;
    cin >> msg;
    for (unsigned i = 0; i < msg.length(); i++) {
        cout << "Char[" << i << "]: " << msg[i] << endl;
    }
    

Using unsigned

  • Note the use of unsigned i in the for loop
  • Specifying unsigned assumes int by default
  • So rather than unsigned int we may just code unsigned as the data type
  • Recall from lesson 3.1.3 that unsigned ranges from 0 to 4294967295 rather than -2147483647 to 2147483647 for int
  • The length() function returns an unsigned number because the length of a string is never less than zero
  • If you compare a signed number with an unsigned number, the compiler may issue a warning:

    warning: comparison between signed and unsigned integer expressions

  • By using unsigned as the counting variable type in the for loop you avoid the warning

Try It: iterating Strings (4m)

  1. Copy the following program into a text editor, save it as test.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;
    }
    
  2. Add the code to prompt for and read a messages from the user:
    cout << "Enter a word: ";
    string msg;
    cin >> msg;
    
  3. Next add the following for-loop code to the main() function.
    for (unsigned int i = 0; i < msg.length(); i++) {
        cout << i << ": " << msg[i] << endl;
    }
    
  4. Compile and run your code. What do you see when you compile?
  5. Be prepared to answer the following Check Yourself questions when called upon.

Check Yourself

  1. True or false: the length() function of a string returns an unsigned integer.
  2. For the following code, the output the second time through the loop is ________
    string msg = "aeiou";
    for (unsigned i = 0; i < msg.length(); i++) {
        cout << "Char[" << i << "]: " << msg[i] << endl;
    }
  3. True or false: the compiler may give a warning if you compare an unsigned int with a signed int.
  4. Each character in the above loop is printed on it own line because of the ________.


6.1.4: String Input With Spaces

  • We have been using the >> operator to enter data into a string variable:
    string something;
    cout << "Enter something: ";
    cin >> something;
    cout << "You entered: " << something << "END OF OUTPUT\n";
    
  • However, there are some complications
  • >> skips whitespace and stops on encountering more whitespace
  • Thus, we only get a single word for each input variable
  • If a user types in "Hello Mom!", we would only read "Hello" and not " Mom!"
  • This is because cin >> s1 works as follows:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found

Input Using getline()

  • To read an entire line we use function getline()
  • Syntax:
    getline(cin, stringVariable);
    
  • Where:
    • stringVariable: the name of the string variable
  • For example:
    string line;
    cout << "Enter a line of input:\n";
    getline(cin, line);
    cout << line << "END OF OUTPUT\n";
    
  • Note that getline() stops reading when it encounters a '\n'

The Problem with Newlines

  • When you press the Enter key, a newline character ('\n') is inserted as part of the input
  • The newline character can cause problems when you mix cin >> with getline()
  • Recall that cin >> s1:
    1. Skips whitespace
    2. Reads non-whitespace characters into the variable
    3. Stops reading when whitespace is found
  • Since whitespace includes newline characters, using cin >> will leave a newline character in the input stream
  • However, getline() just stops reading when it first finds a newline character
  • This can lead to mysterious results in code like the following:
    cout << "Enter your age: ";
    int age;
    cin >> age;
    cout << "Enter your full name: ";
    string name;
    getline(cin, name);
    cout << "Your age: " << age << endl
         << "Your full name: " << name << endl;
    
  • To correct this problem we use cin >> ws just before getline()
    cin >> ws; // clear whitespace from input stream
    
  • We can see how to use this fix in the following example

Example Using cin >> ws

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

int main() {
    cout << "Enter your age: ";
    int age;
    cin >> age;
    cout << "Enter your full name: ";
    string name;
    cin >> ws; // clear whitespace from buffer
    getline(cin, name);
    cout << "Your age: " << age << endl
         << "Your full name: " << name << endl;
}

Check Yourself

  1. True or false: Using the >> operator with string variables only reads one word at a time.
  2. To read strings containing multiple words use the ________ function.
  3. True or false: before you switch from using the >> operator to using getline(), you must clear the next newline character from the input buffer.
  4. To clear whitespace from the input buffer use: ________.


6.1.5: Processing Text Input

  • Sometimes we need to read input as words and sometimes as lines
  • To input a sequence of words, use the loop:
    string word;
    while (cin >> word) {
       // process word
       cout << word << endl;
    }
    
  • cin >> word is the same test as cin.good() (see lesson 6.1.7)
  • To process input one line at a time, use the getline() function
    string line;
    while (getline(cin, line)) {
       // process line
       cout << line << endl;
    }
    
  • getline(cin, line) returns true as long as there is input remaining
  • The following example processes text input by counting words
  • When reading input in the while test, you need to close the stream using:
    • Ctrl + Z in Windows
    • Ctrl + D in Linux or OS X
  • Closing the stream acts as a sentinel value for the loop
  • When the stream fails the loop exits

Example Program that Reverses a Sentence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "Enter a phrase followed by the Enter"
         << " key and Ctrl-Z/D.\n";
    string word;
    int count = 0;
    while (cin >> word) {
        count++;
    }
    cout << "Number of words: " << count << endl;

    return 0;
}

Redirection of Input and Output

  • We could use the above program by typing words at the command line
  • However, that quickly gets tedious
  • A better way is to use redirection of input (see textbook page 154)
  • The command line interfaces of most operating systems have a way to link a file to the input of a program
  • The content of the file gets fed into the program as if all the characters had been typed by a user
  • For example, after compiling the above program we type something like the following at the command line:
    ./words < input.txt
    
  • Where input.txt is the text file on which we want to count words
  • You can redirect program output to a file as well using something like:
    ./words > output.txt
    
  • You can combine input and output redirection in one command:
    ./words < input.txt > output.txt
    

Check Yourself

  1. True or false: the following code reads input one word at a time.
    string str;
    while (cin >> str) {
       cout << str << endl;
    }
    
  2. True or false: the following code reads input one line at a time.
    string str;
    while (getline(cin, str)) {
       cout << str << endl;
    }
    
  3. To close the cin input stream use the Ctrl key plus the ________ key.
  4. True or false: most operating systems let you redirect input and output at the command line.


Exercise 6.1: Finding Words (5m)

In this exercise we write code to find words in a text file. Compile and test after each step to verify your work.

Specifications

  1. Copy the following program into a text editor, save it to the home folder of Cygwin or your Terminal window as findword.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;
    }
    
  2. Inside main(), declare both a string variable named word and an integer variable named count, like:
    string word;
    int count = 0;
    
  3. Add a while loop to read one word at a time from cin, like:
    while (cin >> word) {
        // Add if statements here
    }
    
  4. Inside the while loop write code to add one to the count variable.
  5. Add two if-statements, one to test for the word "Shazam" and one to test for the word "bogus", reporting the word count where the word was found. For example:
    if (word == "Shazam") {
        cout << "Shazam is word " << count << endl;
    }
    
  6. Test your program by copying the following into a txt file (use Notepad++) and saving it to your cygwin home folder.

    words.txt

  7. Run the program from the command line using input redirection:
    ./findword < words.txt
    
  8. Save your findword.cpp and submit it to Canvas Exercise 6.1.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 6.2.6: Summary.


6.1.6: Summary

  • A string is a series of characters enclosed in double quotes
  • We can store text in a variable of type string, like:
    string s1 = "Hello Mom!";
  • A character is a single letter, number or special symbol
  • We can store a a single character using a variable of type char, such as:
    char letterA = 'A';
    char letterB = 'B';
    
  • Each character is stored as a number, using its ASCII code
  • Strings are stored in a character sequence starting at 0 (zero)

    String character position

  • We can access individual characters of a string using []
  • Strings are a special type of variable called objects, just like a Turtle
  • Because a string is an object, it has member functions
  • We can iterate through a string using a loop and the length() member function:
    string s = "abcdef";
    for (unsigned i = 0; i < s.length(); i++) {
        cout << "Char[" << i << "]: " << s[i] << endl;
    }
    
  • To read an entire line, you need to use the getline() function:
    getline(cin, line);
  • Sometimes cin >> can leave a '\n' character in the input stream
  • To get around this problem you can use cin >> ws before getline()
    cin >> ws; // clear whitespace from buffer
    

Check Yourself

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. String are enclosed in double quotes. What type of quote marks enclose characters? (6.1.1)
  2. The characters of a string variable can be accessed using what brackets? (6.1.2)
  3. The leftmost character of a string is accessed using which index number? (6.1.2)
  4. To print the following string vertically down the page, what code do you write? (6.1.3)
    string str = "Hi mom!";
  5. To convert the following char variable to a number, what code do you write? (6.1.4)
    char ch = '7';
  6. What is the value of the expression: 'd' - 'a' + 'A'? (6.1.4)
  7. To convert the following string variable to a number, what code do you write? (6.1.4)
    string str = "7";
  8. How many words can you enter with the following code? (6.1.5)
    string something;
    cout << "Enter something: ";
    cin >> something;
    cout << "You entered: " << something << endl;
    
  9. How can you change the previous code to read a string that includes spaces? (6.1.5)
  10. What code can you use to clear newlines and other whitespace from the input stream? (6.1.5)

6.2 Array Basics

Learner Outcomes

At the end of the lesson the student will be able to:

  • Declare and allocate memory for arrays
  • Generate code to initialize arrays
  • Access array elements
  • Use arrays with functions


6.2.1: Introduction to Arrays

  • Recall that a string is a series of characters enclosed in double quotes

    String character position

  • We can access individual characters of a string using []
    string s = "abcdef";
    char c = s[2]; // character 'c'
    
  • With the [] we can iterate through a string with a loop like:
    string s = "abcdef";
    for (unsigned i = 0; i < s.length(); i++) {
        cout << "Char[" << i << "]: " << s[i] << endl;
    }
    
  • It turns out we can make lists of numbers or other data that we can also access using []
  • These lists of data are called arrays

Array Definition

Array: an ordered arrangement of identically-typed data values

  • An array is used to process a collection of data of the same type
  • Often times we need to process a group of the same types of data, like:
    • Bank account transactions
    • Salaries for employees in a company
    • Prices for products
    • Temperature data over some period of time
    • Test scores for a group of students
  • 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

Array Example

  • For the above example, we can define an array like:
    int score[] = { 90, 95, 97, 89, 98, 96, 85, 79, 95, 100 };
    
  • An array is like single row or column of data in spreadsheet or table
  • In C++, the slots of arrays are numbered starting at 0, as shown below:
    scores = 
    90[0]
    95[1]
    87[2]
    89[3]
    98[4]
    96[5]
    85[6]
    79[7]
    95[8]
    100[9]
  • Our array holds 10 values and all the values are of the same type: int
  • Each of the items inside an array slot is known as an element
  • The number inside of the square brackets is known as an index
  • Notice that the first index is 0 (zero)

Check Yourself

  1. To store lists of data we can code a(n) ________.
  2. True or false: we use arrays because they are more convenient than strings.
  3. True or false: arrays values must all be of the same type.
  4. To access an element of an array we use an ________.


6.2.2: Arrays and Elements

  • One way to define an array is to declare an array variable and provide a list of values
    dataType variableName[] = { list };
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • list: the list of values separated by commas
  • From our previous example:
    int scores[] = { 90, 95, 97, 89, 98, 96, 85, 79, 95, 100 };
    
  • This definition is known as static initialization because the values are assigned by the compiler
  • C++ has other ways to declare lists of data which we will explore later in the course

Accessing an Element

  • Once we have the array in place, we can access the elements using the index
  • The index is the position number of the element
  • For example, the integer 95 is at position 0, 97 at position 1, and so on
  • We use the variable name with the index inside square brackets to access an element
  • As an example, we would access the element with the value 98 as follows:
    score[3]
  • Once we access an element, we use it like a regular variable such as
    cout << score[3] << endl; // prints element #3
    
  • We can assign a new value to an element as well, like:
    scores[4] = 98;
    
  • Note that we should not go beyond the last index as the value is undefined and may cause errors
    cout << score[10] << endl; // element not defined
    

Try It: Create an Array (3m)

  1. 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;
    }
    
  2. Inside main(), add a statement to define an array of double named temp along with a list of five (5) randomly chosen values.
  3. Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  4. Print element #0 like:
    cout << temp[0] << endl;
    
  5. Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  6. Verify your code agains the following example. Your array values will vary.  Keep your myarrays.cpp for later use today.

Example Array of Type double

array of type double

Creating Arrays with No Values

  • We can declare an array with no values in each element using the following syntax
    dataType variableName[size];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    const int SIZE = 10;
    int scores[SIZE];
    
  • Notice the use of the constant SIZE to record the number of elements
  • To make use of such an array, we would need to assign a value to each element like:
    scores[0] = 95;
    scores[1] = 97;
    // and so on
    

Check Yourself

  1. The number inside of the square brackets of an array is called an ________.
  2. Like a string, the first element in any array has an index value of ________.
    1. -1
    2. 0
    3. 1
    4. it depends on the declaration
  3. If you declare an array with 10 elements, the index number of the last element is ________.
  4. For the following array declaration, answer the questions below:

    double num = { 1.2, 2.3, 3.4, 4.5, 5.6 };

    1. The number of elements is ________
    2. The value of num[0] is: ________
    3. The value of num[2] is: ________
    4. The value of num[4] is: ________


6.2.3: Arrays and Loops

  • We can use a loop as a way to access each array element
  • Notice that the index of an array is an integer number
  • The index can be a counter variable, like those used in counter-controlled loops
  • Thus we can use arrays with a loop like:
    const int SIZE = 5;
    int nums[SIZE] = { 1, 2, 3, 4, 5 };
    int total = 0;
    for (int i = 0; i < SIZE; i++) {
        cout << nums[i] << endl;
        total = total + nums[i];
    }
    cout << total << endl;
    
  • The first time through the loop, when i = 0, the value of nums[i] is 1
  • The value of total starts at 0 but becomes 1 during the first iteration

Activity

  1. Take out a piece of paper and put your name on it.
  2. Create a table with columns for totali and nums[i] like:
    total | i | nums[i]
    -------------------
          |   |
          |   |
    
  3. Trace the values of totali and nums[i] for each iteration of the following loop: (3m)
    const int SIZE = 5;
    int nums[SIZE] = { 1, 2, 3, 4, 5 };
    int total = 0;
    for (int i = 0; i < SIZE; i++) {
        cout << nums[i] << endl;
        total = total + nums[i];
    }
    
  4. When finished, verify your array-and-loop trace with another classmate. (1m)

Check Yourself

For the following code:

const int SIZE = 5;
int nums[] = { 1, 2, 3, 4, 5 };
int total = 0;
for (int i = 0; i < SIZE; i++) {
    cout << nums[i] << endl;
    total = total + nums[i];
}
cout << total << endl;
  1. For the second time through the loop:
    1. The value of the index variable i is ________
    2. The value of nums[i] is ________
  2. After executing the above code snippet, the value stored in total is ________?
    1. 0
    2. 1
    3. 2
    4. 15


6.2.4: Finding Elements in an Array

  • Suppose you want to find a particular value in an array
  • This is known as searching a list
  • An easy and straightforward algorithm is linear search (a.k.a. sequential search)
  • In linear search you:
    • Start at the beginning of the list
    • Compare each value in the list looking for matches:
      • If the value is found, then return the position (index)
      • If you reach the end of the list, return "not found"
  • Since an index must be >= 0, then we can use -1 as the "not found" value

Group Activity: Finding an Element in a List

  1. Select one volunteer to be the finder.
  2. All other students line up and each choose a number between 1-20.
  3. The finder writes the number he or she is looking for on the board.
  4. The finder starts at one end of the line and asks each student if he or she has the number sought, keeping track of the current student index number.
  5. When a student with the sought after number is found, write the index number of the found student on the board, or -1 if the number is not found.

Solo Activity: Writing the Algorithm

  1. At the top of your myarrays.cpp file from the last exercise, add a block comment like
    /*
    Linear Search Algorithm
    ... write the algorithm here
    */
    
  2. In the block comment write the algorithm for finding an element in an array using psuedocode. (3m)
  3. Review your algorithm with another student. (2m)

Check Yourself 

Linear Search Algorithm:
Set found = -1;
For each item in the list and while found is -1
    If the item has the desired value,
        Set found = index
  1. True or false: to find a value in an array, start at one end and check each element until you find the value or reach the end.
  2. The above technique for searching an array is known as sequential or ________ search.
  3. True or false: when searching an array you must always start at index 0 and proceed to the end.


Exercise 6.2: Simple Arrays (5m)

In this exercise we explore processing arrays as lists.

Specifications

  1. If you have not already created the myarrays.cpp file, complete the exercise Try It: Create an Array.
  2. Declare a constant LENGTH and initialize it to the length of the array.
  3. Add a for-loop that accesses every index of the temp array and prints every value to the screen like:
    array loop

  4. Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  5. Declare a summing variable named total before the loop and initialize the variable to zero (0).
  6. Inside the loop, add the indexed temp[i] value to total every time the loop iterates.
  7. Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  8. After the loop completes, print the value of total.
  9. Compile your code to make sure it has correct syntax.

    If you have problems, ask a classmate or the instructor for help as needed.

  10. Submit your myarrays.cpp to Canvas Ex 6.2.

When finished, please help those around you.


6.2.5: Summary

  • In this section we looked at how to use arrays for lists of numbers
  • An array is a list of data elements each identified by an index

    array

  • Arrays are used to keep a list of data that is easily accessed
  • Any type of data may be stored in an array, but all elements must be of the same type
  • For example, we may have a list of student test scores to process:
    909587899896857995100
  • With this data, we can calculate statistics like:
    • Highest score
    • Lowest score
    • Average (mean) score
    • Difference (deviation) of each score from the average

Creating an Array

  • One way to define an array is to declare an array name and provide a list of values
    dataType variableName[] = { list };
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • list: the list of values separated by commas
  • For example:
    int scores[] = { 95, 97, 89, 98, 96, 85, 79, 95, 100 };
    
  • We can declare an array with no values using the following syntax:
    dataType variableName[size];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    const int SIZE = 10;
    int scores[SIZE];
    
  • Arrays like this can never change size and the array size must be set when the program is compiled
  • To make use of such an array, we would need to assign a value to each element like:
    scores[0] = 95;
    scores[1] = 97;
    // and so on
    

Accessing Array Elements

  • We specify which slot of an array to access with the [] operator:
    cout << score[3] << endl; // prints element #3
    
  • The indexes of arrays are numbered starting at index 0
  • We can assign a value to an array element any time after it is declared:
    const int SIZE = 10;
    int scores[SIZE];
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • In addition, we can read the value of an element using square brackets like:
    cout << scores[4] << endl;
    

Arrays and Loops

  • Because array indices are integers, we often use counting loops to access array elements like
    int scores[] = { 90, 95, 87, 89, 98, 96, 85, 79, 95, 100 };
    for (int i = 0; i < 10; i++) {
        cout << scores[i] << endl;
    }
    

Linear Search

  • One of the algorithms we discussed was linear search
  • We use linear search to find a specific element of an array
  • Linear search is easy to implement using a simple loop:
    int found = -1;
    for (unsigned i = 0; i < NUM_ELEMENTS and found == -1; i++) {
        if (item == arr[i]) {
            found = i;
        }
    }
    

Array Parameters

  • When writing a function with an array parameter, we place an empty [] after the parameter name:
    void print(int values[], int size);
    
  • We need to pass the size of the array into the function, because the function has no other way of knowing the size of the array
  • Sometimes we must pass both the capacity and size of an array to a function:
    void read(int data[], int capacity, int& size);
    
  • The capacity parameter tells the function the maximum array size
  • The size parameter records how many items the user entered into the array
  • Also note that functions cannot return arrays
Subpages (1): words.txt
Comments