View
219
Download
0
Category
Preview:
Citation preview
7/28/2019 Lectures 21 to 23
1/17
CHAPTER 7 ARRAYS
An array is a collection of consecutive storage locations which
has the same name and the same type. To refer to a location ora specific element from a certain array, we have to specify thename of the array together with its position (index or subscript).
An array has elements with subscripts starting with 0.
Simple Arrays (One Dimensional Arrays)
Array Declaration
data_type identifier[size_of_array];
Example
int marks[285];
This declaration tells the compiler to allocate 285 consecutive
storage locations, each of type int. The first element has
subscript 0 and the 285th element has the subscript 284.
Contents Subscriptor
index
Variable name
0 marks[0]
1 marks[1]
2 marks[2]
: : :
: : :: : :
: : :
283 marks[283]
284 marks[284]
An array may be declared in several ways
int marks[285];
or
7/28/2019 Lectures 21 to 23
2/17
const int size = 285;
int marks[size];
or
#define size 285
:
int marks[size];
You have to be careful when referring to elements in an arrayso that reference to elements which are out of bound does not
happen, e.g. element marks[285] does not exist. You must
always remember that an array starts with subscript/index 0,
i.e. marks[0]. The compiler does not have the facility tocheck the array bounds.
Subscripts may be constants, variables or expressions which
are ofinteger values. Example,
marks[35]
marks[j] (herej has beenassigned an integer value before this)
marks[3*k+2] (herek has been assigned an integer value beforethis)
Array Initialization
An array needs to be initialized after declaration to startcomputation. Example of array initialization,
Example 1
int result[5] = {3, 56, 39, 13, 52};
will produce
Array Value
result[0] 3
result[1] 56
7/28/2019 Lectures 21 to 23
3/17
result[2] 39
result[3] 13
result[4] 52
This is known as compile-time initialization.
Example 2
int result[] = {3, 56, 39, 13, 52};
will declare the array with variable name result and
size 5. The subscript will be in the order from 0 to 4. The
values produced in the array result are as follows,
Array Valueresult[0] 3
result[1] 56
result[2] 39
result[3] 13
result[4] 52
Example 3
If the dimension size is greater than the number of listedelements, the array elements not explicitly initialized are
set to 0.
int result[5] = {3, 56};
will produce
Array Value
result[0] 3
result[1] 56
result[2] 0
result[3] 0
result[4] 0
Warning
The following declaration/initialization
7/28/2019 Lectures 21 to 23
4/17
int result[5] = {3, 56, 39, 13, 52, 72};
is illegal because it allocates more values than what waspermitted.
Memory Allocation for Arrays
When an array is declared, the compiler allocates a series ofavailable memory spaces consecutively equivalent to the size
of the array. For example, when variable result is declared
as an integer array with 5 elements,
int a1[5];
The following memory spaces are allocated,00000000 00000004 00000008 00000009 0000000A
num int 5 avg float 1.2 char Y cost int 123
00000010 00000014 00000018 0000001C 00000020
a1[0] int a1[1] int a1[2] int a1[3] int 90 a1[4] int 8
00000020 00000024 00000026 00000028 0000002B
res int 2 4.5 38 1.2
00000030 00000034 00000036 0000003A 0000003C
4 8 2
Exercise
What is the memory allocation for declaration of int
marks[285] ?
Array processing with loopsUse loops to monitor the subscripts
:
float number[100];
:
for (int i = 0; i < 100; i++)
number[i] = 0.0;
:
7/28/2019 Lectures 21 to 23
5/17
Array Operations
The elements in an array can be manipulated the same wayas ordinary variables, in arithmetic operations, as input,
output, etc.
Duplicating Array
To copy one array into another, each element must be copied in turn.For example,
const int arraySize = 7;
void main()
{int ia1[] = {0, 1, 2, 3, 4, 5, 6};
int ia2[arraySize];
for (int ix = 0; ix < arraySize; ++ix)
ia2[ix] = ia1[ix];
// continue with array operations:
:
}
From the above program, arrays ia1 and ia2 are two different
arrays, i.e. changing of value in ia1 does not change the value
in ia2, after the duplication of array.
Consider the below program.
const int arraySize = 7;
void main()
{
int ia3[] = {0, 1, 2, 3, 4, 5, 6};
int ia4[arraySize];
ia3 = ia4; //different meaning}
7/28/2019 Lectures 21 to 23
6/17
The above program sets the memory address of array ia3 tothe same as memory address of array ia4, i.e. arrays ia3 and
ia4 are pointing to the same memory location.
In other words, arrays ia3 and ia4 are the same, changing ofvalue in ia3 will change the value in ia4.
Example
#include
#include
using namespace std;
const int SIZE = 5;
void main()
{
int number[SIZE], i;
// read in 5 numbers and assign to the array number[]
cout
7/28/2019 Lectures 21 to 23
7/17
IMPORTANT
If an array is referred using only the name without the subscripts,the address of the first element of the array is actually beingreferred, not the element. For example,
:
int marks[10];
:
cout
7/28/2019 Lectures 21 to 23
8/17
Similarly, each element in an array is also assigned uniquememory address.
For example, if an array integerarr has been declared with 5elements and initialized as below,
int arr[5] = { 2, 3, 5, 6, 8 };
The following figure shows the memory addresses and valuesassigned toarrwhenarris declared and initialized.
Con
tents
Index Variable
name
Memory address for each
element is denoted by
2 0 arr[0] (arr + 0) or &arr[0]
3 1 arr[1] (arr + 1) or &arr[1]
5 2 arr[2] (arr + 2) or &arr[2]
6 3 arr[3] (arr + 3) or &arr[3]
8 4 arr[4] (arr + 4) or &arr[4]
Example
The example below shows the values represented bya[i], &(a[i]) and a+i.
#include
using namespace std;
#define SIZE 5
void main()
{
int a[] = {0, 1, 2, 3, 4}, i;
// printing the value of a[i] -> integer valuefor (i = 0; i < SIZE; i++)
7/28/2019 Lectures 21 to 23
9/17
cout
7/28/2019 Lectures 21 to 23
10/17
&(a[4]) = 0xaea72418
a + 0 = 0xaea72408
a + 1 = 0xaea7240c
a + 2 = 0xaea72410
a + 3 = 0xaea72414
a + 4 = 0xaea72418
More Examples on Arrays
Example 1
The below program generates the Fibonacci numbers by
using an array.
#include #include // required for setw()
using namespace std;
//---- void main()
void main()
{
int i,n;
unsigned int fibonacci[26];
char next;
fibonacci[1]=0;
fibonacci[2]=1;
next = 'y';
while (next == 'y') {
cout
7/28/2019 Lectures 21 to 23
11/17
cout > n;
for (i = 3; i
7/28/2019 Lectures 21 to 23
12/17
const int size = 50;
int marks[size], i = 0, count = 0,
num_pass = 0;
float sum = 0.0, average,pass_percentage;
cout marks[i]) {
count++;
sum += marks[i];
if (marks[i] >= 40) num_pass++;
++i;
}
average = sum/count;pass_percentage = num_pass * 100 / count;
for (i = 0; i < count; i++)
cout
7/28/2019 Lectures 21 to 23
13/17
Arrays As Function Parameters
In order to use arrays as function parameters, the required changes are
pointed out in the below program segment.
:
void main()
{
void change1(int[]);
:
int x[10];
:change1(x);
:
}
:
void change1 (int a[])
{
:
}:
Example 1
The below example shows how to use array as functionparameters. Note the difference of parameters between voidchange1(int a[])andvoid change2(int b).
#include
using namespace std;
#define SIZE 5
//--------------------------------------------------------
// void main()
//--------------------------------------------------------
void main
The symbol [] should be used in
the parameter. Size of the array is
optional.
Declare the array in main program
Use only the name of array, i.e.
exclude symbol [], to pass in the
address of the array.
7/28/2019 Lectures 21 to 23
14/17
{ void change1(int[]); // function prototypevoid change2(int);
// variable declaration & initialization
int x[SIZE] = {0, 2, 4, 6, 8};int i;
// main function bodycout
7/28/2019 Lectures 21 to 23
15/17
{
int j;
for (j = 0; j < SIZE; j++)
a[j] *= 3;}
// end void change1(int[])
//--------------------------------------------------------
// void change2(int)
//--------------------------------------------------------void change2 (int b)
{
b = 2*b;
}
// end change2(int)
Sample output
main(): Values for array x before change1(x) functionexecuted:
0 2 4 6 8
main(): Values for array x after change1(x) functionexecuted:
0 6 12 18 24
main(): The value for array x after change2(x[i])function executed:
0 6 12 18 24
7/28/2019 Lectures 21 to 23
16/17
//Example of program with functions passing
//parameters using arrays modification of our//previous min-max program
#include
using namespace std;
#include#define size 10
void main()
{ void read_input(int []);
void max(int [], int &);
void min(int [], int &);void print_out(int [], int, int);
int x[size], Maximum, Minimum;
read_input(x);
max(x, Maximum);
min(x, Minimum);
print_out(x, Maximum, Minimum);
getch();}
//--------------------------------------------
void read_input(int a[])
{int i;
cout maximum)maximum = a[i];
7/28/2019 Lectures 21 to 23
17/17
}
//---------------------------------------------
void min(int a[], int &minimum){
int i;
minimum = a[0];
for (i = 1; i < size; i++)
if (a[i] < minimum)minimum = a[i];
}
//----------------------------------------------
void print_out(int a[], int Max, int Min)
{
int i;
cout
Recommended