Welcome guest! Click here to register or login.
logo

<< Tutorial 6
Tutorial 8 >>

Arrays

***Please register FREE to rate this tutorial***


Topics
1-D Array
2-D Array
Array's & Functions
Notations
Examples
Example 1
Example 2
Example 3
Example 4

1-Dimensional Arrays

By definition, an array is collection of data that is contiguous in memory. Like any variable, an array must be declared before it is used. There are also numerous types of arrays. The first type is the standard 1 dimensional array. A 1D array contains 1 long row of data.

Here is how to declare a 1D array:

     type name[ capacity ];

where type is the data type of the array (i.e int, char, bool), name is an appropriate name for the array and capacity is the amount of space in the array. A rule is that the capacity cannot be negative or zero and is always an integer.

Notice the syntax of the array declaration. There are square brackets indicating the capacity. The brackets are used to show there is an array declared.

Data in an array is accessed with the [] operator. What goes inside the brackets is the index. By definition, each individual cell in an array is called an index. Indicies of an array ALWAYS BEGIN AT 0 (zero) and end at capacity-1.

Here are some examples of declaring a 1D array:

//declares an array of 5 integers.
//Indicies are 0 thru 4:
int myarr[5];

//declares an array of 10 boolean values.
//Indicies are 0 thru 9:
bool arr[10];

//decalres an array of 1000 characters.
//indicies are 0 thru 999:
char ch[1000];

Example 1:
Random numbers and 1D arrays

Download source code here (Right click - Save Tagret As...)

Below is a short program demonstrating a one-dimensional array:

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(){

        //guarentees a new random each time:
	srand(time(0));

        //declare the array:
	int myarr[10];

        //loop to assign the values to the array:
	for(int i = 0; i < 10; i++)
		myarr[i] = rand()%10+1;

        //print out the values:
	for(int j = 0; j < 10; j++)
		cout << myarr[j] << " ";

return 0;
}

The program will randomly fill a one-dimensional integer array with numbers from 1 to 10 and then print them out. One possible output is this:

7 4 2 3 5 6 8 9 9 2

Run the program a few times and see the different outputs each time you run it.

Example 2:
Storing scores

Download source code here (Right click - Save Tagret As...)

This program will allow a uer to enter 5 quiz scores to calculate an average. It will then output the average on screen.

#include <iostream>
using namespace std;

int main() {
   int scores[5];
   int total = 0;

   cout << "Enter 5 scores to compute an average."
        << "One at a time when prompted: " << endl;

   for(int i = 0; i <= 4; i++){
      cout << "Enter score[" << i << "]: ";
      cin >> scores[i];
      cout << endl;
   }

   for (i = 0; i <= 4; i++)
      total += scores[i];

   cout << "The average was: " << total / 5.0 << endl;
   return 0;
}

The first thing the program does is calculate allow the user to input, via a for loop, the 5 quiz scores. Second, it will add the values up to the total variable. Finally, it will display the average on screen at the end.

The program is not a good one however. It doesn't handle any error checking for a negative number when a user enters a score. Try to write the error proof code snippet. To see the answer, click here.

2-Dimensional Arrays

A two dimensional array in C++ can be thought of as a table containing rows and columns. A 2 dimensional array is still contiguous in memory but now has a row and a column. It contains the other properties of an array in respect to the indicies, capacity and data type.

Here is how to declare a 2D array:

     type name[rows][columns];

Here are some examples of declaring a 2D array:

//declares an array of 35 integers.
//Indicies are rows 0 thru 4 && columns 0 thru 6:
int myarr[5][7];

//declares an array of 20 strings.
//Indicies are rows 0 thru 9 && columns 0 thru 1:
string arr[10][2];

//decalres an array of 64 double precision values.
//Indicies are rows 0 thru 7 && columns 0 thru 7:
double dbl[8][8];

Example 3:
Numbers and 2D arrays

Download source code here (Right click - Save Tagret As...)

This program will allow a uer to enter 5 quiz scores to calculate an average. It will then output the average on screen.

#include <iostream>
using namespace std;

int main() {

int myarr[2][3];

	for(int r = 0; r < 2; r++){
		for(int c = 0; c < 3; c++){
			myarr[r][c] = r*c+1;
		}
	}

	for(r = 0; r < 2; r++){
		for(int c = 0; c < 3; c++){
			cout << myarr[r][c] << " ";
		}
		cout << endl;
	}

return 0;

}

The program will initialize the array to the values of r*c+1 and then print out the values contained in those cells. This just demonstrates how to use a two dimensional array.

The output is:
1 1 1
1 2 3

Arrays and Functions

Arrays can be used as parameters in a function. Here is what they may look like:

One-Dimensional parameter:
	void something(double arr[]);

Two-Dimensional parameter:
	void something(double arr[][7]);

Notice that for a one-dimensional array, you do not have to declare the size of it in the function. However, for a two dimensional array, you must declare the second dimension.

When used in the function, all array parameters are passed by reference. Again, by the reference rules of functions, if you change anything in the array inside a function, you also change it elsewhere.

Example 4:
Minimum array entry (1D and 2D)

Download source code for 1D here (Right click - Save Tagret As...)

These programs will find the minimum entry in both a 1 and 2 dimensional array. The two programs are separate from each other.

1 DIMENSIONAL MINIMUM:

#include <iostream>
using namespace std;

int minArray(int arr[], int cap) {

   int m = arr[0];
   for (int c = 1; c < cap; c++)
      if (arr[c] < m) m = arr[c];

   return m;
}

int main() {
   int x[5] = {7,4,6,2,3};
   cout << minArray(x, 5) << endl;
   return 0;
}

The above program will initialize the array to the values shown by doing a shorthand notation (see below). It will then call the function minArray() and pass the entire array to the function. Notice that the function is an int type and will return an int as the minimum number.

With the function, it will take as parameters the array itself and the capactiy of the array. C++ does not know this so you must specify the capacity as a parameter. It will then search through each array entry and return the minimum value to the main() function.

Download source code for 2D here (Right click - Save Tagret As...)

2D MINIMUM ENTRY:

#include <iostream>
using namespace std;

int minArray(int arr[][5], int rowCap, int colCap) {
   int m = arr[0][0];

   for (int r = 0; r < rowCap; r++)
     for (int c = 0; c < colCap; c++)
       if (arr[r][c] < m) m = arr[r][c];

   return m;
}

int main() {
	int x[3][5] = { {13,4,35,22,3},
	                {32,3,7,3,2},
                        {3,4,4,4,2}};
   cout << minArray(x, 3, 5) << endl;
   return 0;
}

This program is essentiallythe same as the previous only it delas with a 2D array. The function will take an additional parameter for the column capacity as well as the columns for the array parameter. Trace through the code in the funtion to see what it is doing.

Array Notations

There are some shorthand notations when dealing with arrays. First, instead of using a for loop or nested loops to initialize an array to zeros, you can do a shorthand notation:

	int mayarr[5] = {0};

This will place, at index 0, the integer 0 (or whatever else you place inside it) and by default, set the rest of the cells to zero. If you had done this:

	int mayarr[5] = {1};

This will place, at index 0, the integer 1 and by default, set the rest of the cells to zero, NOT 1!

If you wanted to fill an entire array manually, you may do this:

	int mayarr[5] = {1,2,3,4,5};

Another way of using arrays is as follows:

	string arr[] = {"Jack", "Queen", "King", "Ace"};

This will declare a string array called arr and set the capacity to 4, since you initialized it to 4 different items.


<< Tutorial 6
Tutorial 8 >>