Download One-Dimensional Arrays

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
Transcript
One-Dimensional Arrays
•
Until now, all the data types we have been using have been atomic. That means that
individual data items cannot be subdivided into smaller units. A variable of type int,
for example, cannot be further broken down into individual digits.
•
We will now move on to explore compound data types, which are made up of
multiple atomic data types. Our first structured data type is the array (also sometimes
called a vector).
An array is a data structure that consists of multiple sub-units, each of which is of the
same type.
For example, an array of integers is a group of integers that are stored together in memory
and are referred to by a single name, the identifier of the array. I.e. a collection of ages
(each of them is an integer, can be stored in an array and referred to by the name age.)
Array Syntax
An array is declared as follows:
data-type array-name[ number-of-items ];
NOTE:
•
The number of elements in the array must be specified at compile time. In
other words, the number-of-items term in the declaration must be a specific
integer, not a variable.
•
It can be either a literal or a named constant (const variable). The reason for
this is that the elements of the array are stored contiguously in memory, and the
compiler needs to know how much memory to allocate for the array. It must
know both the number of elements and the data type (since different data types
require different amounts of storage);
1
Example of array declaration:
int Age [45]; // array Age consist of 45 integers
float Grade[3]; //array Grade consists of 3 floating point values
or
const int array_size = 50; // do you remember what const qualifier does?
int Num[array_size]; //array Num consists of 50 integers
•
Each sub-unit of the array is referred to as an element.
•
Since the entire array is referred to by a single identifier (name), each individual
element is accessed using its index or subscript. Each element in the array is numbered
consecutively, starting from 0. So the third element in the array Age could be accessed
using the code:
Age[2] = 21;
Remember the third element is number 2 counting from 0!!! It is really easy to be one
number “off” when dealing with arrays.
•
Each individual element of an array can be used in any manner a scalar (atomic)
variable of the same type could be used. For example, it could be used in an
assignment statement as follows:
int num;
int bunch_of_nums[10];
//just a number
//an array of 10 numbers, indexed from 0 to 9
bunch_of_nums[0] = 25;
num = bunch_of_nums[0];
//assign 25 to the first element of the array
//set num equal to the first element of the array
•
It is also possible to access individual elements in an array using a subscript
expression that evaluates to an integer, such as:
result = result + value[ i * 5];
cout << num[ i % array_size ];
To summarize: an array is a collection of variables, all of the same data type. The first
part of each variable name is the same, the last part is an index value enclosed in square
brackets. The index value starts at 0 and goes to array_size –1.
2
Array Initialization and Operations on Arrays
Initializing the arrays:
Initialization during declaration
int Age[5] = {23, 5, 2, 19, 31};
Age[0] is initialized to 23, Age[1] is initialized to 5, ...
When initializing during declaration:
•
there must be at least one initial value between the braces
•
too many values will cause a syntax error
•
too few - the remaining are initialized to zero
Initialization later on
int Age[5];
Age[0]=23;
Age[1]=5;
Age[2]= 2;
Age[3] = 19;
Age[4] = 31;
For loops are very handy for initializing large arrays:
int Age [1000];
for( int i = 0; i < 1000; i++)
{
cout<<”\nEnter “ << i <<”st/th/rd element of the array: ”
cin>> Age[i]; //initialize to user-provided values
}
1
or
int Age [1000];
for( int i = 0; i < 1000; i++)
Age[i]=5;
//initialize all elements to 5
or
int Age [1000];
for( int i = 0; i < 1000; i++)
Age[i]=i;
//initialize elements to 0,1,2, ….. 998, 999
Arrays can only be operated upon one element at a time.
Examples:
const int array_size =5;
int values[array_size] = {0,1,2,3,4};
int other_values[array_size] = {0};
// integer array of 5 elements
// another integer array with 5 elements,
//all initialized to 0
for ( i = 0; i < array_size; i++ )
values[i] = other_values[i]; // set elements of array values equal to corresponding
//element of array other_values. After this operation the
//arrays will be equal (all elements of values will be 0).
for ( i = 0; i < array_size; i++ )
cout << values[i];
// output elements of array values.
for ( i = 0; i < array_size; i++ )
if ( values[i] == other_values[i] )
//compare arrays to each other.
// has to be done element by element
...
2
Convention for indexing of array elements
We will use the following convention for this class:
When we declare an array
int Array[5] = { 12, 14, 17, -3, 45}
it is stored in memory the following way
|12 | 14| 17| -3| 45| … | ….
The first element of this array is
A[0] = 12
The second element of this array is A[1] = 14
The third element of this array is
A[2] = 17
The fourth element of this array is
A[3] = -3
The fifth element of this array is
A[4] = 45
In other words, there are 5 elements in this array (1-5), but the index of the array goes
from 0 to 4. When we refer to the i-th element of the array, we refer to the element with
index i-1.
C++ vs. Pseudocode
void main()
{
const int size = 20;
int Array[size]={2,3,4,5,6,-13,2,3, 14,22,9,3,0,-2,99,1,1,9,-2,30};
int sum =0, i=0;
while (i < size)
{
sum = sum + Array[i];
i++;
}
cout << " The sum is " << sum << endl;
}
**********************************************************************
SUM_ELEMENTS
initialize the elements of Array to 2,3,4,5,6,-13,2,3,14,22,9,3,0,-2,99,1,1,9,-2,30
set sum to 0 , i to 0, size to 20
WHILE i is less than size
sum = sum + Array( i )
increment i by 1
ENDWHILE
display the sum
END
Common mistakes with arrays
•
The most common mistake when dealing with arrays is out-of-bound errors.
C++ does not check for invalid (out-of-bounds) array indices either at compile time or at run time.
An out-of-bounds array index is an index that is either less than zero or grater than the
array size minus one.
Given the array
float alpha[200];
The valid array indices range from alpha[0] to alpha[199], any others, less than 0 or
greater than 199 will be out-of-bounds and C++ will not tell you.
•
Some things that are TEMPTING BUT NOT LEGAL in C++
C++ does not provide aggregate (manipulation of entire array as one unit)
operations on arrays.
!!!!!Some no-nos !!!!!
Given: int x[50], y[50];
•
NO aggregate assignment of y to x
• x = y;
// illegal
• NO aggregate comparison of arrays
• if (x = = y)
// illegal
• NO aggregate I/O on arrays
• cout << x;
// illegal
• NO aggregate arithmetic on arrays
• x = x + y;
//illegal
• NO returning an array as the value of a function
• return x;
// illegal
•
The only thing we can do to an array as a whole is pass it as a parameter to a function
(we'll do this later).
1
Arrays – simple code examples
// This program will initialize the elements in an array and then sum them
#include <iostream>
using namespace std;
void main()
{
const int size = 20;
int Array[size]={2,3,4,5,6,-13,2,3,14,22,9,3,0,-2,99,1,1,9,-2,30};
int sum, i;
sum = 0;
i = 0;
while (i < size)
{
sum = sum + Array[i];
i++;
}
cout << " The sum is " << sum << endl;
}
// This program fills an array with elements and displays the elements in reverse order .
// This program reads in the elements to process
#include <iostream>
using namespace std;
void main()
{
const int SIZE = 20; //max size
int MyArray[SIZE];
int sum =0, i=0, end_element;
cout << "Enter up to 20 numbers”<< “Enter -99 to stop before 20"<< endl;
cout << "Any in excess of 20 will be ignored"<<endl;
cin >> MyArray[i]; //read in the first element
while ((i < SIZE) && (MyArray[i] != -99))
{
i++;
cin>>MyArray[i];
}
end_element = i-1;
cout << "\nThe elements in reverse order are : "<< endl;
for (i = end_element; i >= 0; i--)
cout << MyArray[i] << " ";
cout << endl << endl;
}