Arrays

 

CS 161: Introduction to Computer Science 1

 

 

 

Introduction to Arrays

• If we wanted to read in a string of characters, one way would be to read in a character at a time in a loop and print it out, for each iteration of the loop. 

 

      For example, to remove extra blanks from a sentence, our algorithm might be:

 

           While we have not reached End Of Line, loop thru the following:

                        a) Read in a character

                        b) If that character is a blank

                                    and If the last character was a blank,

                                                ignore this character and keep on going

                        c) If that character is a blank

                                    and If the last character was not a blank,

                                                print out the blank

                                                and set a flag to say we are NOT currently looking

                                                at a word

                        d) If that character is not a blank,

                                    Set a flag to say that we are currently looking at a word

                                    and print out the character

 

• Notice we read in one character at a time, process it, print it, and then go read in another character. We don't save the characters.

 

• What if we had wanted to change this program to read in a line of characters and then rearrange the words when we print. This would mean that we couldn't just print out each character after we have delt with it. Instead we would have to keep all of the characters around!

 

      The best way to do this is with arrays.

 

 

 

• An array is like a list of variables -- just written in a compact form. It looks like:

                        firstc would be the same as text[0]

                        secondc would be the same as text[1]

                        thirdc would be the same as text[2]

                        fourthc would be the same as text[3]

 

• Arrays are a data structure used for storing a collection of data items that are of all the same type. Arrays are defined by:

 

            char text[80];

 

• Arrays are called indexed variables, where you have a variable and an index and you can step thru from 0 to N-1 (the largest size of the array). They are treated the same as N variables, just there are square brackets with a number inside! text[0] may be used any place that an ordinary variable of type char is used.

 

            For example:

                        text[0] = 'a';

 

• You can also represent the number inside the square brackets by an expression (it is an index....so we call this an index expression).  For example, counter could have be declared as an integer, and can range from 0 to 79. This means that the array subscript does not need to be a constant or a literal!

 

• You can declare arrays of characters, floats, integers:

           

            char line[80];

            float emp_pay[250];

            int emp_id[4];

 

      Where, line has 80 (0-79) indexed character variables: line[0] holds the first character, line[1] holds the second character and line[79] holds the last character allowable.

 

      And, emp_pay has 250 (0-249) indexed real variables: emp_pay[0] holds the first real number, emp_pay[1] holds the second real number and emp_pay[249] holds the last real allowable.

 

      PLUS, emp_id has four (0-3) indexed integer variables: emp_id[0] holds the first integer, emp_id[1] holds the second integer, emp_id[2] holds the third integer, and emp_id[3] holds the last integer.

 

Array Index Out of Range

• You should not use an index to an array that is larger than the array size.

 

• It would have been safer  to write our program to read in characters:

                       

                        int counter, max_index;

                        char text[100];

 

                        max_index = 99;

                        counter = 0;

                       

                        //read in a character as long as the array index is

                        //within range and and end-of-file has not be encountered

                        while ((counter <= max_index) && cin >> text[counter] )

                                    counter++;

 

 

Arrays as a Structured Type

• An array is really just a list of variables, where each is easily accessible since we can use an index...and just step through the array by changing the value of the index.

 

• Defining array text  was just the same as defining 80 variables; using an array was a much more elegant approach. Each element of the array was able to hold one value of type char.

 

            Saying   char text[80];           means:

 

                        text[0] is an indexed variable,

                        text is an array variable,

                        and the index for array text may range from 0 to 79.

 

• Most operators can manipulate ONLY one array element at a time. That's why we use subscripts!

 

• Arrays must be declared in the same manner as we have learned about for other types of variables. Let's look at a few example declarations for arrays:

     

      int array1[4];       /* an array of 4 integers...starting at array1[0] */

 

• You can omit the length of the array as long as it is not needed to allocate storage. It is not needed when the variable being declared is a formal argument to a function.

 

• The size of an array must be fixed as a constant at compilation time.

 

 

 

Input and Output using Arrays

• We can read in characters in a loop:

                        counter = 0;

                        while (cin >> text[counter]) {        //terminates at EOF

                                    counter++;

                         }

 

• Or, the following reads in one word (i.e., one string of characters):

                        cin >>text;

 

    however, the character string read in would be terminated by a white space: this can be a blank, tab, newline, form feed, or carriage return.  

 

• Let's see another example...

                        char s[10];

                        if (cin >>s)                             //Reads in a string of chars

                                    cout <<s <<endl;      //only echo if it is not EOF

 

Results in:

> a.out

This is a string of characters & words...               <-- input

This 

 

(Notice, cin stops reading as soon as a white space character is reached...this is interpreted as a way to separate values in the input stream)

 

 

• Now, read in a number of strings of characters until end-of-file is encountered:

 

                        char s[20];

                        while (cin >>s)

                                    cout <<s <<endl;

 

Results in:

> a.out

This is a test     of strings!               <--this is the input

This

is

a

test

of

strings! 

 

• Note: The null terminating character is appended to the string during input, so your array size should be large enough to hold the string plus one additional character!

 

• You can also read in characters using cin.get:

 

    The cin.get(ch) capability can be used to read one character or a string of characters. There are actually three possible parameters!

 

    #1) The first one is the name of the variable, a string or a character.

 

    #2) The second parameter is the length of the character array, which represents the maximum number of characters that can be read minus one to leave room for the terminating null character; if you don't specify this parameter (i.e., if you leave it out), then you can only read in one character.

 

    #3) The third parameter is the termination character; if you don't specify this parameter (i.e., if you leave it out), then your stream will be terminated by a '\n'...which means if it is not specified input characters will be read up to the next newline.

 

    Let's look at some examples:

 

            cin.get(ch)                 //reads in one character including whitespace                                            //characters

            cin.get(s,40)   //reads in a string of at most 39 characters or                                   //terminated by a '\n'

            cin.get(s,10,'*')          //reads in a string of at most 9 characters or

                                                //terminated by an asterisk

 

• Now you are ready to look at  cin.get and the 2nd and 3rd parameters that may be specified. To make sure I don't read in more than 9 characters....

 

            #include <iostream.h>

            main() {

                        char s[10];

                        if (cin.get(s,10))

                                    cout <<s <<endl;

            }

 

Results in:

> a.out

AlongString!             <-- this is the input

AlongStri

 

(Side note: Another way to do this is with cin.getline(array, length(actually length-1 can be read), delimiter)....Appears to be the same thing, where the delimiter by default is the newline and is not placed within the array.)

 

The terminating character, if found, is still available in the input stream, so it will be encountered when the next item is read. If instead you want to read exactly 10 characters (bytes) irrespective of their values and store them in an array without appending the null character you can use read: cin.read(s,10);


 

Examples

• Using arrays, let's write a function to sum n numbers:

 

 

int sum(int size, int some_array[]);   

int main()

{

      int a[100];     

 

      int  i=0;          //array index

      int count;       //# of integers to add

 

      cout <<"How many numbers would you like to add together\n";

            cin >> count;

            cout <<"Please enter " <<count <<" numbers now..."  <<endl;

            while (i < count)

                         cin >> a[i++];

            cout <<"The total of " <<count;

            cout <<" numbers is " <<sum(count, a) <<endl;

 

            return 0;

      }

 

      int sum (int size, int some_array[])

      {

            int i, s = 0;

            for (i=0; i<size;i++)

                        s += some_array[i];

            return s;

      }

 

• In this case, we are sending all elements of array a to function sum; arrays are always treated as a VARIABLE ARGUMENTs. This means that if function sum changed some_array (eg., some_array[0] = 99;), then the array a in the main program would be changed accordingly (eg., a[0] would be 99).

 

      This means that you never use the reference operator (&) with arrays!


  INDEXED VARIABLES can also be used in function calls. Notice the difference:

 

 

int sum(int last_total, int add);          

int main()

{

      int a[100];     

 

      int  i=0;          //array index

      int count;       //# of integers to add

      int running_total=0;

 

      cout <<"How many numbers would you like to add together\n";

            cin >> count;

            while (i < count) {

                         cin >> a[i];

                        running_total = sum(running_total, a[i]);

                        i++;

            }

            cout <<"The total of " <<count;

            cout <<" numbers is " <<running_total <<endl;

 

            return 0;

      }

 

      int sum (int last_total, int add)

      {

            return last_total + add;

      }

 


• Let's read in a line of characters (until we reach end of line) and then write out the string backwards:

 

 

/* read in an array of characters and print them out backwards */

int main()

{

      const int MAX=80;

      int i,c;

      int count = 0; // this will keep a count of the # characters

                                          //  and we initialize the count to zero

      char nchar[MAX];    // here is our array declaration!

 

      // let's initialize the array to all blanks to start off with

      for (i=0; i< MAX; ++i)

                  nchar[i] = ' ';

 

      // Its time to read in from the keyboard

      cout <<"Please enter a string of characters & digits \n";

      c=cin.get();

      count = 0;

      while(count < MAX && (c != '\n' && !cin.eof())) {

                  nchar[count] = c;

                  c = cin.get();

                  count = count + 1;

            }

     

      cout <<"The string ... backwards is: \n";

      /* Now let's print it out backwards! */

      for (i=count-1; i>=0; --i)

                  cout <<nchar[i];

 

      cout <<endl;

 

      return 0;

 

}