| My Training Period: xx hours
Array is another important topic in C and C++. The source code for this module is:C/C++ array source codes. The lab worksheets practice are:C/C++ array part 1,C/C++ array part 2,C/C++ 2D array part 1 andC/C++ 2D array part 2.
The C and C++ programming skills:
2.1 Introduction And Definition
int mark1, mark2, mark3, ..., mark100;
int mark[100];
|
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;
char letter[70];
The first example declares two arrays named x and y of type int. Arrayx can store up to 20 integer numbers whiley 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 likeprice[10] in the second example together withyield.
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:
int id[7] = {1, 2, 3, 4, 5, 6, 7};
float x[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char vowel[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’ tovowel[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:
char array_name[size] = "string_lateral_constant";
For example, the array vowel in the above example could have been written more compactly as follows:
char vowel[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.
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; }
The following program example declares and initializes the array named y of typeint. 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;
}
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 usingget_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:
int get_total(int*, int)
Study the following source code and the output.
// a program to find the total values of an
// array y by passing an array to a function using pointer
#include <iostream>
using namespace std;
#define n 7
// function prototype
int get_total(int*, int);
int main()
{
int total, y[n]={6,9,2,4,5,23,12};
cout<<"\nCalling function get_total(y, n),";
cout<<"\nBy bringing along the value of y, an array";
cout<<"\nfirst address and n = 7, an array size.";
cout<<"\nAn array name, is the pointer to the";
cout<<"\n1st element of an array\n\n";
// a function call, pass along the pointer to the first
// array element and the array size, and the
// return result assign to variable total
total = get_total(y, n);
cout<<"\nSum of the 7 array elements is "<<total<<endl;
return 0;
}
// function definition
int get_total(int *ptr, int x)
{
int i, total = 0;
// do the looping for array elements...
for(i=0; i<x; i++)
{
// displays the array content, pointed by pointer...
cout<<*(ptr+i)<<" ";
// do the summing up of the array elements...
total += *(ptr+i); // total=total + *(ptr+i);
}
// return the result to the calling program...
return total;
}
---------------------------------------------------------------------------------------------------------------
The following is a C++ program example compiled using g++ (for more information refers toLinux gcc, g++ and gdb part 1).
// **********gccarray.C or gccarray.cpp************
// ************FeDoRa 3, g++ x.x.x**********
// a program to find the total values of an
// array y by passing an array to a function using pointer
#include <iostream>
#define n 7
using namespace std;
// a function prototype
int get_total(int*, int);
int main()
{
int total, y[n]={6,9,2,4,5,23,12};
cout<<"\nCalling function get_total(y, n),";
cout<<"\nBy bringing along the value of y, an array";
cout<<"\nfirst address and n = 7, an array size.";
cout<<"\nAn array name, is the pointer to the";
cout<<"\n1st element of an array\n\n";
// function call, pass along the pointer to the first
// array element and the array size, and the
// return result assign to variable total
total = get_total(y, n);
cout<<"\nSum of the 7 array elements is "<<total<<endl;
return 0;
}
// a function definition
int get_total(int *ptr, int x)
{
int i, total = 0;
// do the looping for array elements...
for(i=0; i<x; i++)
{
// displays the array content, pointed by pointer...
cout<<*(ptr+i)<<" ";
// do the summing up of the array elements...
total += *(ptr+i); //total=total + *(ptr+i);
}
// return the result to the calling program...
return total;
}
[bodo@bakawali ~]$ g++ gccarray.C -o gccarray
[bodo@bakawali ~]$ ./gccarray
Calling function get_total(y, n),
By bringing along the value of y, an array
first address and n = 7, an array size.
An array name, is the pointer to the
1st element of an array
6 9 2 4 5 23 12
Sum of the 7 array elements is 61
[bodo@bakawali ~]$
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.
// a program to find the smallest number in an array
// named balance, a very simple search function
#include <iostream>
using namespace std;
#define n 10
int main()
{
int i;
float small, balance[n]={100.00,40.00,-30.00,400.00,60.00,-25.00,-24.00,0.00,3.24,0.50};
small = balance[0];
// loop for displaying array content....
for(i=0; i<n; i++)
cout<<balance[i]<<" ";
// another loop do the array element comparing...
for(i=1; i<n; i++) // check until condition i = n
{
if(small > balance[i])
small = balance[i];
}
cout<<"\nSearching..."<<endl;
// display the result...
cout<<"The smallest value in the given array is = "<<small<<endl;
return 0;
}
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.
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.
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.
For more algorithms implemented using C++ Templates of STL, you can refer to theC++ Standard Template Library.
// a simple sorting program that sort a list of n
// integer numbers, entered by the user, ascendingly
#include <iostream>
using namespace std;
#define maxsize 100
int main()
{
int temp, i, j, n, list[maxsize];
cout<<"\n--You are prompted to enter your list size.--";
cout<<"\n--Then, for your list size, you are prompted to enter--";
cout<<"\n--the element of your list.--";
cout<<"\n--Finally your list will be sorted ascending!!!--\n";
// get the list size...
cout<<"\nEnter your list size: ";
cin>>n;
// prompting the data from user and store it in the list...
for(i=0; i<n; i++)
{
cout<<"Enter list's element #"<<i<<"-->";
cin>>list[i];
}
// do the sorting...
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(list[i] > list[j])
{
// these three lines swap the elements list[i] and list[j].
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
cout<<"\nSorted list, ascending: ";
for(i=0; i<n; i++)
cout<<" "<<list[i];
cout<<endl;
return 0;
}
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];
int x[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 mcolumns, 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"};
name[0] = "Sally" name[1] = "Joyce"
name[2] = "Lisa" name[3] = "Alice"
Note that the second subscript here is unnecessary and therefore omitted.