Docsity

Arrays in C++: Declaration, Initialization, and Manipulation, Schemes and Mind Maps of Computer science

Toggle sidebar
bg1
Software Design Lecture Notes
Arrays Prof. Stewart Weiss
Arrays
Motivation
Suppose that we want a program that can read in a list of numbers and sort that list, or ๎˜œnd the largest
value in that list. To be concrete about it, suppose we have 15 numbers to read in from a ๎˜œle and sort into
ascending order. We could declare 15 variables to store the numbers, but then how could we use a loop to
compare the variables to each other? The answer is that we cannot.
The problem is that we would like to have variables with subscripts or something like them, so that we could
write something like
max = 0;
for ( i = 0; i < 15 ; i++ ) {
if ( number_i > max )
max = number_i ;
}
where somehow the variable referred to by
number_i
would change as
i
changed.
You have seen something like this already with C++ strings: if we declare
string str;
then we can write a loop like
for ( int i = 0; i < str.size(); i++ )
cout <๎˜—< str[i] <๎˜—< ๎˜-๎˜‘ ;
in which each individual character in
str
is accessed using the subscript operator
[]
. The characters in
a string form what we call an
array
. An array is conceptually a linear collection of elements, indexed by
subscripts, all of the same type. If we could create an array named
number
with 15 elements, it would look
like this:
number:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Each element could be accessed using the subscript operator, as in
number[1]
or
number[7]
, and we could
write a loop like
max = 0;
for ( i = 0; i < 15 ; i++ ) {
if ( number_i > max )
max = number[i] ;
}
This would make it possible to manipulate large collections of
homogeneous
data, meaning data of the
same type, with a single subscripted variable. Such is possible in C and C++ and all modern programming
languages.
Arrays are of fundamental importance to algorithms and computer science.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Arrays in C++: Declaration, Initialization, and Manipulation and more Schemes and Mind Maps Computer science in PDF only on Docsity!

Arrays

Arrays

Motivation

Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from a le and sort into ascending order. We could declare 15 variables to store the numbers, but then how could we use a loop to compare the variables to each other? The answer is that we cannot.

The problem is that we would like to have variables with subscripts or something like them, so that we could write something like

max = 0; for ( i = 0; i < 15 ; i++ ) { if ( number_i > max ) max = number_i ; }

where somehow the variable referred to by number_i would change as i changed.

You have seen something like this already with C++ strings: if we declare

string str;

then we can write a loop like

for ( int i = 0; i < str.size(); i++ ) cout << str[i] << - ;

in which each individual character in str is accessed using the subscript operator []. The characters in a string form what we call an array. An array is conceptually a linear collection of elements, indexed by subscripts, all of the same type. If we could create an array named number with 15 elements, it would look like this:

number:

Each element could be accessed using the subscript operator, as in number[1] or number[7], and we could write a loop like

max = 0; for ( i = 0; i < 15 ; i++ ) { if ( number_i > max ) max = number[i] ; }

This would make it possible to manipulate large collections of homogeneous data, meaning data of the same type, with a single subscripted variable. Such is possible in C and C++ and all modern programming languages. Arrays are of fundamental importance to algorithms and computer science.

Arrays

Declaring a (one-Dimensional ) Array

Syntax:

elementtype arrayname [ size_expression ]

where

  • elementtype is any type that already exists
  • arrayname is the name of the array
  • size_expression is the number of elements in the array

This declares an array named arrayname whose elements will be of type elementtype , and that has size_expression many elements.

Examples

char fname[24]; // an array named fname with 24 chars int grade[35]; // an array named grade with 35 ints int pixel[1024768]; // an array named pixel with 1024768 ints

const int MAX_STUDENTS = 100; double average[MAX_STUDENTS]; // an array named average with 100 doubles

string fruit[5]; // an array of 5 C++ strings

The element type of an array is often called its base type. The rst example is an array with base type char, for example. One can say that fname is an array of char.

Things to remember about arrays:

  • The starting index of an array is 0, not 1.
  • The last index is one less than the size of the array.
  • If the array has size elements, the range is 0..size-1.
  • Arrays contain data of a single type.
  • An array is a sequence of consecutive elements in memory and the start of the array is the address of its rst element.
  • Because the starting address of the array in memory is the address of its rst element, and all elements are the same size and type, the compiler can calculate the locations of the remaining elements. If B is the starting address of the array array, and each element is 4 bytes long, the elements are at addresses B, B + 4, B + 8, B + 12, and so on, and in general, element array[k] is at address B + 12k.
  • Although C and C++ allow the size expression to be variable, you should not use a variable, for reasons having to do with concepts of dynamic allocation and the lifetime of variables.
  • Use constants such as macro denitions or const ints as the sizes of arrays.

Arrays

Examples

cout << fruit[0] ; // prints apple cout << powers[1] <<   << powers[2] ; // prints 1 2 fruit[3] = apricot; // replaces peach by apricot in fruit[3] counts[SIZE-10] = counts[SIZE-11] + 2; // sets counts[90] to counts[89] + 2 = 2 cout << score[power[4]]; // power[4] = 9, so this outputs scores[9]

Notice in the last two examples that the index expression can be arbitrary integer-valued expressions, even the value of an array of integers.

Loops and Arrays

Without loops it is very hard to use arrays. Conversely, with them they are easy to use. In general, a loop can be used to initialize an array, to modify all elements, to access all elements, or to search for elements within the array. An example follows.

Example 1. Finding a minimum element.

This example shows how an array can be initialized with values from an input stream using a for-loop. The for-loop guarantees that the array is not overlled because it runs only as many times as the array has elements. The example uses the preceding declarations.

// read v a l u e s i n t o a r r a y from s t a n d a r d i n p u t f o r ( i = 0 ; i < MAXSCORES; i++ ) c i n >> s c o r e [ i ] ;

// Let m i n s c o r e be t he f i r s t element as a s t a r t i n g g u e s s i n t m i n s c o r e = s c o r e [ 0 ] ;

// Compare r e m a i n i n g a r r a y a l e m e n t s t o c u r r e n t maxscore f o r ( i = 1 ; i < MAXSCORES; i++ ) { i f ( m i n s c o r e > s c o r e [ i ] ) // i f c u r r e n t element < m i n s c o r e m i n s c o r e = s c o r e [ i ] ; // make i t new m i n s c o r e // At t h i s p o i n t , maxscore >= s c o r e [ j ] , f o r a l l j = 0 , 1 , 2 ,... i }

cou t << The minimum s c o r e i s << m i n s c o r e << e n d l ;

In this example, the score array is lled from values entered on the standard input stream, cin. After the entire array has been lled, a variable named minscore is set to the value of score[0]. Then a second loop examines each element of score from score[1], to score[2], and so on up to score[MAXSCORE-1]. If an element is smaller than minscore, its value is copied into minscore. This implies that in each iteration of the second loop, minscore is the smallest of the elements seen so far. This is how one searches for the minimum value in an unsorted array.

Danger

If your program tries to access an element outside of the range of the array, bad things can happen. Typically the program will be aborted by the opeating system with an error message. As an example:

int score[10]; for ( int i = 0; i < 20; i++ ) cin >> score[i];

Arrays

When i eventually has the value 10, score[i] is a memory address outside of the score array (since it is 0-based and the last index is 9) and the program will be aborted.

Partially Filled Arrays

Although an array might be declared to have so many elements, that does not always mean that all of the cells in the array actually have meangingful data. Sometimes a program does not know how much data it will read in from a le or external source, so it declares an array much larger than it needs. Then after it reads the data, only part of the array has been lled. If a loop that is processing the array tries to process all array elements, errors will result.

This implies that when an array is lled and the number of data items is not known in advance, then the code needs to count how many values are written into the array, and stop if it exceeds the array size, or if it runs out of data rst. The while loop has two conditions to check in this case:

i n t l i s t [ 1 0 0 ] ; i n t temp ; l e n g t h = 0 ;

c i n >> temp ; // t r y t o read t o f o r c e e o f ( ) t o become t r u e i f t h e f i l e i s empty w h i l e ( l e n g t h < 100 &&! c i n. e o f ( ) ) { l i s t [ l e n g t h ] = temp ; // temp has a value , so copy i t i n t o t he l i s t l e n g t h ++; // i n c r e m e n t b e c a u s e we c o p i e d a v a l u e i n t o l i s t c i n >> temp ; // read a new v a l u e ; might make e o f ( ) t r u e }

The variable length keeps a count of what has been put into the array and when the loop ends, it is guaranteed to be at most 100. Either the loop ends because length became 100 or because the data stream ended. In either case, the array has been lled with length many values. Therefore, all future processing of this array must iterate only from 0 to length -1. The following code would nd the minimum element of list:

f o r ( i = 1 ; i < l e n g t h ; i++ ) { i f ( min > l i s t [ i ] ) min = l i s t [ i ] ; }

Arrays in Functions

Suppose that you want to write a function that can nd the minimum element of any array it is given. Can we write such a function? Let us rephrase a simpler question for now. Can we write a function that can nd the minimum integer in an array of integers? We can safely answer yes to this question, whether it is C or C++. The heart of the matter is how we can pass an entire array into a function.

How can you pass an entire array into a function?

An array parameter in a function is written as a name followed by empty square brackets:

result_type function_name ( ..., elementtype arrayname [ ] ,... ) ;

For example,

int max( int array[] ); void foo( int a[], int b[], double c[]);

Arrays

The function initSquares() puts into each element array[i] the value i*i. The remarkable thing about array parameters is that each element of the array parameter acts like a reference to the corresponding element of its argument, so the output of this code snippet

int squares[20];

initSquares( squares, 20); for ( int i = 1; i < 20; i++ ) cout << squares[i] << endl;

will be the squares 0, 1, 4, 9, ... 400, because the changes made to the array parameter array[] are actually changes made to the calling program's squares array. To emphasize this

There are three types of parameter passing:

  • call by value parameters
  • call by reference parameters
  • array parameters

Array parameters are like call by reference parameters  changes made to the array are changes made to the corresponding array argument.

Searching and Sorting

Two of the most common types of processing of array data are searching for specic values and sorting the elements.

Searching

The problem of searching for a particular value in an array or in a list of anything is called the search problem. The value being sought is called the search key , or just the key when the meaning is clear.

Suppose, for example, that want to know whether anyone had a score of 75, assuming that we already read a list of scores into our array scores. We can search through our array of scores for the number 75 as follows:

cou t << " Enter th e number t o l o o k f o r : " ; c i n >> s e a r c h k e y ;

b o o l found = f a l s e ; // f l a g t o c o n t r o l l o o p i n t i = 0 ; // i n d e x t o go through a r r a y

w h i l e (! found && ( i < l e n g t h ) ) { i f ( s e a r c h k e y == s c o r e [ i ] ) // found i t! found = t r u e ; e l s e i ++; // didn ' t f i n d i t yet , so advance t o next element }

// I f found == f a l s e then we d id not f i n d t h e item i f ( found ) cou t << s e a r c h k e y << " i s i n i n d e x " << i << e n d l ;

There are some very important concepts here.

Arrays

  • We do not want to use a for-loop because if we nd what we are looking for, we want to stop searching. So we use a while-loop that is re-entered if we have not found what we are looking for and our index variable is still within the range of the array. Therefore we set found to false initially and set it to true if we nd a matching value in the array.
  • If we do nd an element in the array whose value equals searchkey, then we set found to true. This causes the loop to be exited. Because i is declared outside of the loop body, it still has a valid value after the loop exits. It was not incremented since found became true, so it is the index at which score[i] == searchkey.
  • If we search through the entire array and do not nd searchkey, then found is false when the loop exits, because the condition (i < length) became false. By checking the value of found after the loop, we can tell whether it was found or not.

This is the rst example of a non-trivial algorithm. We can state its requirement more generally as,

Given an array A of N values, and a searchkey X, nd the position in A in which X occurs or report that it is not there.

The preceding solution searched through the array one element at a time, starting with the rst and ending with the last, until either it found it or it examined every element.

This is the best we can do when searching through a list of values that is not in sorted order. We have to look at every value in the array until we nd the key. If there are N items in the array, we need to check compare our search key to N values in the absolute worst case that either it is not there or it is in the last position.

If however, the array is sorted, then it is possible to search in a much faster way. In general it is better to sort the values in the array for faster searching later. Presumably we will search the data very often, so if sorting it costs us a bit of time, it is worth the savings we get from faster searching later.

Sorting

There are many dierent ways to sort an array, some much faster than others. Some are easy to understand and some are harder to understand. Some require additional memory to sort, others can be done in place, meaning by rearranging the elements of the array without using extra memory. The sorting problem can be stated as follows,

Given an array A of size N, rearrange the elements of A so that A[0] <= A[1] <= A[2] <= ... <= A[N-1].

Notice that the elements are rearranged. In other words, sorting is a permutation, a rearranegment of an array.

We will start with a very intuitive sorting algorithm that is called selection sort. You will see why it is called selection sort very soon. The idea is simple:

Find the minimum element of the array from 0 to N-1. Suppose it is in index K. Swap A[0] and A[K]. Now A[0] has the smallest element. Find the minimum element of the array from 1 to N-1. Suppose it is in index K. Swap A[1] and A[K]. Now A[1] has the second smallest element. Find the minimum element of the array from 2 to N-1. Suppose it is in index K. Swap A[2] and A[K]. Now A[2] has the third smallest element. Repeat this procedure until there are two elements remaining: A[N-2] and A[N-1}. Find the smaller of the two and swap it into A[N-2].

Arrays

Notes

  • This algorithm can be written symmetrically using maximums instead of minimums. That is a good exercise to try.
  • If the call to swap() were replaced by the three instructions that do the swap, this would compile with a C compiler.
  • This always takes the exact same amount of time, even if the array is already sorted. The call to indexofMin() always iterates its loop (N-first) times and the swap is always performed, even if the two indices are the same. It will swap a value with itself in this case. It is an example of an unnatural sort. A sorting algorithm is natural if arrays that are already in order require less swapping than arrays that are very out of order.

Once an array has been sorted, searching it is much faster. Later we will see a method of searching called binary search, in which the portion of the array being searched is cut roughly in half in each iteration.

Multidimensional Arrays

The arrays we have studied so far have a single dimension  they represent data items that can be arranged in a sequence, and therefore they are also called linear arrays. Arrays can have more than one dimension in C and C++.

Declaring a Multidimensional Array

You declare an array with multiple dimensions using a syntax that is similar to one-dimensional arrays.

Syntax:

elementtype arrayname [ size1 ] [ size2 ] ... [ sizeD ];

where

  • elementtype is any type that already exists
  • arrayname is the name of the array
  • size1 is the number of elements in the rst dimension, size2, the number in the second dimension, and so on, and D is the number of dimensions in the array.

Basically you tack on a pair of square brackets with a number in between for every dimension that you want the array to have.

Examples

char tictactoe [3][3]; // a 3 by 3 grid of chars string chessboard[8][8]; // an 8 by 8 grid of strings int pixel[1024][768]; // a 1024 by 768 grid of ints double cube [5][5][5]; // a 5 by 5 by 5 cubic grid of doubles

In two dimensions, we think of the rst dimension as the row, the next as the column. There is no rule for this and there is nothing in the language that associates the dimensions with rows or columns. It depends how you program it. In a three dimensional array, the rst subscript would be like the row, the second like the column, and the third, like the plane in which this row and column are located, i.e., the height. People usually refer to the rst dimension as the row, the second as the column, and the third, if it exists, as the plane.

Arrays

Accessing Elements of Multidimensional Arrays

Higher dimensional arrays are accessed just like one dimensional arrays. The subscripts match their dimen- sion:

tictactoe[0][2] = 'x'; // puts an 'x' in first row, last column. chessboard[7][7] = redqueen; // puts the string redqueen into the lower // right hand corner of the chessboard.

The following example shows how we could color the elements of a checkerboard. It demonstrates accessing two-dimensional array accesses.

c o n s t char RED = ' r ' ; c o n s t char BLACK = ' b ' ; char c h e c k e r b o a r d [ROWS] [ COLS ] ; i n t i , j ;

f o r ( i = 0 ; i < 8 ; i++ ) f o r ( j = 0 ; j < 8 ; j++ ) i f ( ( i + j ) % 2 == 0 ) c h e c k e r b o a r d [ i ] [ j ] = RED; e l s e c h e c k e r b o a r d [ i ] [ j ] = BLACK;

f o r ( i = 0 ; i < 8 ; i++ ) { f o r ( j = 0 ; j < 8 ; j++ ) cou t << c h e c k e r b o a r d [ i ] [ j ] << ' ' ; cout << "\n " ; }

Processing Higher Dimensional Arrays

The most commonly used higher dimensional arrays are two-dimensional. They can be used to represent a wide assortment of objects, such as graphical images, mathematical matrices, screen representations, two- dimensional surfaces in general, mazes and other 2D cellular arrangements (chess boards, game boards). Just as one dimensional arrays go hand in hand with for-loops, two-dimensional arrays are naturally paired with nested for-loops.

The following example shows a code snippet that creates a random grid of asterisks. Notice that the middle loop is not a nested loop. Sometimes two-dimensional data can be processed within a single loop.

c o n s t i n t COLS = 1 0 0 ; c o n s t i n t ROWS = 8 0 ; c o n s t i n t MAXSTARS = COLSโˆ—ROWS/ 1 0 ; char g r i d [ROWS] [ COLS ] ; i n t i , j , count = 0 ;

srand ( time ( 0 ) ) ;