Able to understand, use and
create an array.

Able to understand and use
array and function.

Able to understand and use
array, function and a pointer.

Able to understand and use
array and string.

2.1 Introduction
And Definition

Up till
this Module we were introduced with simple data types that suit
to simple applications. For aggregated data, with
same type of element we can use Array.

An array
in C / C++ is a collection of related data elements of the same
type that are referenced by a common name. Generally, it is
just another data type, aggregate data type.

All
the elements of an array occupy a set of contiguous memory locations
and by using an index or subscript we can identify each element.

For
example, instead of declaring mark1,
mark2, ..., markN
to store and manipulate a set of marks obtained by the students
in certain courses, we could declare a single array variable named
mark and use an index, such as j, to
refer to each element in mark. This absolutely has simplified
our declaration of the variables.

Hence,
mark[ j ] would refer to the jth element
in the array mark. Thus by changing the value of
j, we could refer to any element in
the array, so it simplifies our declaration.

For
example, if we have 100 list of marks of integer type, we will declare
it as follows:

int mark1, mark2, mark3, ...,
mark100;

If we
have 100 marks to be stored, you can imagine how long we have to
write the declaration part by using normal variable declaration?

By using
an array, we just declare like this:

int mark[100];

This
will reserve 100 contiguous/sequential memory locations for storing
the integer data type.

Graphically
can be depicted as follows:

7.2 One Dimensional
Array: Declaration

Dimension refers
to the array size that is how big the array is. A single dimensional
array declaration has the following form:

array_element_data_type array_name[array_size];

Here,
array_element_data_type declares the base type
of the array, which is the type of each element in the array.
array_size defines how many elements the array
will hold. array_name is any valid C
/ C++ identifier name that obeys the same rule for the identifier naming.

For example,
to declare an array of 20 characters, named character, we could use:

char character[20];

Can be depicted
as follows:

In this statement,
the array character can store up to 20 characters with the first character
occupying location character[0] and the last character occupying character[19].
Note that the index runs from 0 to 19. In C / C++, an index always
starts from 0 and ends with (array size-1).
So, notice the difference between the array size and subscript/index terms.

Examples of
the one-dimensional array declarations:

int x[20],
y[50];

float price[10], yield;

charletter[70];

The first example
declares two arrays named x and y of type int. Array
x can store up to 20 integer numbers while
y can store up to 50 numbers. The second
line declares the array price of type float.
It can store up to 10 floating-point values.

The third one
declares the array letter of type char.
It can store a string up to 69 characters. (Why 69? Remember, a string has
a null terminated character (\0) at the end,
so we must reserve for it.)

Just like ordinary
variables, arrays of the same data type can be declared on the same line.
They can also be mixed with ordinary variables of the same data type like
price[10] in the second example together with
yield.

7.3 Array Initialization

An array may
be initialized at the time of its declaration, which means to give initial
values to an array. Initialization of an array may takes the following
form:

type
array_name[size] = {value_list};

For example:

intid[7] = {1, 2, 3, 4, 5, 6, 7};

floatx[5] = {5.6, 5.7, 5.8, 5.9, 6.1};

charvowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

The first line
declares an integer array id and it immediately
assigns the values 1, 2, 3, ..., 7 to id[0],
id[1], id[2],...,
id[6].

In the second
line assigns the values 5.6 to x[0],
5.7 to x[1], and so on.

Similarly the
third line assigns the characters ‘a’ to
vowel[0], ‘e’
to vowel[1], and so on. Note again, for
characters we must use the single apostrophe (’)
to enclose them. Also, the last character in the array vowel is the
NULL character (‘\0’).

Initialization
of an array of type char for holding strings may takes the following form:

chararray_name[size] = "string_lateral_constant";

For example,
the array vowel in the above example could have been written more compactly
as follows:

charvowel[6] = "aeiou";

When the value
assigned to a character array is a string (which must be enclosed in double
quotes), the compiler automatically supplies the NULL character but we still
have to reserve one extra place for the NULL.

1.1 Array And Function:
Passing One Dimensional Arrays To Function

A function can
receive the address of an array by using:

A pointer.

A sized
array (dimension is explicitly stated), e.g. s[20]
or

An unsized
array (dimension is not stated), e.g. p[ ].

For example,
to receive an array named x of type float in functions, we may declare any
one of the following:

// pointers,
will be explained in another Module

int myfunction(float *x)

// sized
array

char yourfunction(float x[5])

// unsized
array

void ourfunction(float x[ ])

But you will
see later, the second and third methods not used in practice.

The following
program segment illustrates the passing of an array address to a function
using a pointer.

Here, the memory
address of x is passed to the parameter pter, a pointer. Remember
this; an array name (without the size) is the pointer to the first array’s
element. We will discuss this in more detail in another Module.

// function prototype

void func(float *);

int main()

{

float x[5];

// an array name (without
the bracket) is

// the pointer to the
first array element

func(x);

return 0;

}

// function definition

void func(float *pter)

{ return; }

1.2 Array Manipulation:
How to use an array and what array can do?

1.2.1Accessing Array’s Element

The following
program example declares and initializes the array named y of type
int.
It uses a for loop with index i to access the successive elements in
y.
For each loop iteration, the value accessed is added to the variable
total,
which is finally displayed. Note that the loop index i run from 0
to 6, not 1 to 7. Also, note that the array size n is declared in
the #define statement.

//
a program to find the total of all the elements in array y

#include
<iostream>

using namespace std;

//
replace every n occurrences with 7

#define
n 7

int main()

{

int i, total = 0, y[n] = {6,9,2,4,5,23,12};

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

{

// display the array contents...

cout<<y[i]<<" ";

// do the summing up...

total = total + y[i];

}

// display the result...

cout<<"\nSum of 7 numbers in an array is = "<<total<<endl;

return 0;

}

Output:

You can see
that the for loop is very useful when you wish to loop or iterate through
every element of an array.

The next program
example, accomplishes the same task as the previous one. By using
get_total() function, the main() passes the
first memory address (pointed by the pointer) of an array, y and its size,
n to the function get_total() which then computes
and returns the total, total. Note the function prototype:

7.5.2 Searching
For A Value

To search an
array for a value, you can use a for loop within the if statement.
In other words, the program looks at each element in the array and checks
if it matches the given value in the if expression.

The following
example, finds the smallest element in the array named balance. First,
it assumes that the smallest value is in balance[0]
and assigns it to the variable small.

Then it compares
small with the rest of the values in balance, one at a time.

Output:

When an element
is smaller than the current value contained in small, it is assigned to
small. The process finally places the smallest array element in small.

Study the program
and the output.

1.1.1Exchanging Values of Variables

It is sometimes
necessary to shuffle the order of the elements of an array.

Sorting arrays
calls for the values of some elements to be exchanged. It would therefore
be helpful to first learn the technique of swapping variables.

How would you
swap the values of the variables, let say, num1 and
num2 (that is exchanging
the value of num1 in num2)?

You must use
a third variable as in the following example:

//
assign num1 to third_var

third_var = num1;

//
then assigns num2 to num1

num1 = num2;

//
finally assigns third_var to num2

num2 = third_var;

The process
can be illustrated as shown below.

1.1.2Sorting Variables

Sorting is defined
as arranging data in a certain order, is a very common activity in data
processing. Many algorithms (techniques) are available to perform
sorting.

One sorting
algorithm, which is quite simple to understand, but not necessarily the
best, is given in the following program example. It sorts a list of
integers in ascending order of magnitude by using an array.

Output:

1.2Two Dimensional/2D Arrays

Some data fit
better in a table with several rows and columns. This can be constructed
by using two-dimensional arrays.

A two dimensional
array has two subscripts/indexes. The first subscript refers to the
row, and the second, to the column. Its declaration has the following
form:

data_type array_name[1st dimension
size][2nd dimension size];

For examples:

intx[3][4];

float matrix[20][25];

The first line
declares x as an integer array with 3 rows and 4 columns and the second
line declares a matrix as a floating-point array with 20 rows and 25 columns.

Graphically,
int x[3][4] can be depicted as follows:

You can see
that for [3][4] 2D array size; the total array size (the total
array elements) is equal to 12. Hence:

For n
rows and m
columns, the total size equal to mn

The item list
is read starting from the first row from left to right, and then goes to
the next row and so on.

A set of string
s can be stored in a two-dimensional character array with the left index
specifying the number of strings and the right index specifying the maximum
length of each string.

For example,
to store a list of 3 names with a maximum length of 10 characters in each
name, we can declare:

// a 2D array that can store 4 names, each is 10 characters
long

char name[4][10];

Just like the
one-dimensional array, a two dimensional array can also be initialized.
For example, the previous first array declaration can be rewritten along
with initial assignments in any of the following ways:

int x[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

Or

The results
of the initial assignments in both cases are as follows:

x[0][0]=1 x[0][1]=2
x[0][2]=3 x[0][3]=4

x[1][0]=5 x[1][1]=6
x[1][2]=7 x[1][3]=8

x[2][0]=9 x[2][1]=10
x[2][2]=11 x[2][3]=12

Notice the same
subscript for the rows and columns; it is in the diagonal line.

You can show
how the rows are filled during its initialization. For example, the
array named x can be declared as follows:

int x[3][4] = {{1,2,3,4},

{5,6,7,8},

{9,10,11,12}

};

If the number
of values given is insufficient to fill in the whole array, an initial value
of zero will be assigned to all those locations, which are not given initial
values explicitly.

For example:

So, an initial
value of zero will be assigned to x[2][2] and x[2][3]. Similarly,
in declaration:

An initial value
of zero will be assigned to x[0][3],
x[1][3] and x[2][3]. You can
fill the whole array with zeroes by using:

// all array elements will be 0

int x[3][4]={0};

In memory, despite
their table-form arrangement, the elements of a two-dimensional array are
stored sequentially, that mean one after another contiguously.

An array of
string can also be initialized. For example, in the following declaration:

char name[4][10] = {"Sally", "Joyce",
"Lisa", "Alice"};

The values assigned are as follows:

name[0] = "Sally"
name[1] = "Joyce"

name[2] = "Lisa"
name[3] = "Alice"

Note that the
second subscript here is unnecessary and therefore omitted.