0% found this document useful (0 votes)
41 views

Arrays: Datatype Array Name Size of The Array

Arrays allow storing multiple values of the same type in adjacent memory locations. Elements in an array are accessed via integer subscripts starting from 0. Key aspects of arrays include initialization, accessing and modifying elements, passing arrays to functions, parallel arrays, and multi-dimensional arrays. Arrays must be carefully used to avoid off-by-one errors and accessing out of bounds elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Arrays: Datatype Array Name Size of The Array

Arrays allow storing multiple values of the same type in adjacent memory locations. Elements in an array are accessed via integer subscripts starting from 0. Key aspects of arrays include initialization, accessing and modifying elements, passing arrays to functions, parallel arrays, and multi-dimensional arrays. Arrays must be carefully used to avoid off-by-one errors and accessing out of bounds elements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Arrays

Variables that can store multiple values of the SAME type


-the elements could be all integers, double, char, or strings.

Values stored in adjacent memory locations


Array declaration uses [ ] operator (also called subscript operator)

Datatype Array name


Size of the array

int tests[5];
allocates the following memory capable of holding five int values that are
assigned default subscript values starting at 0

Accessing Array Elements

Each element in an array is assigned a unique subscript.


Subscripts start at 0
The last element’s subscript is n-1 where n is the number of elements in
the array.

The array called tests is defined to hold 5 integer datatypes.


Since each int is 4 bytes, array can hold a total of 20 bytes

subscripts

0 1 2 3 4

First element Second element Third element Fourth element Fifth element

tests[0] tests[1] tests[2] tests[3] tests[4]

1
Array elements can be used as regular variables:
tests[0] = 79;
cout << tests[0];
cin >> tests[1];
tests[4] = tests[0] + tests[1];

Arrays must be accessed via individual elements:


cout << tests; // not legal

Can access element with a constant or literal subscript:


cout << tests[3] << endl;

Can use integer expression as subscript:


int i = 5;
cout << tests[i] << endl;

Size Declarators

Named constants are commonly used as size declarators.


const int SIZE = 5;
int tests[SIZE};
The assignment statement tests[3] = 40; //stores 40 into 4th slot

Array Initialization

Global array à all elements initialized to 0 by default


Local array à all elements uninitialized by default
Arrays can be initialized with an initialization list

const int SIZE = 4;


char val [SIZE] ={‘A’, ‘Z’, ‘&’, ‘*’};

datatype array name containing 4 characters

Here val [0] =’A’ , val [1] = ‘Z’ , val [2] = ’&’ , and val [3] = ‘*’

2
Values are stored in the order in which they appear.
Initialization list cannot exceed the size of the array.

Off-By-One Errors
An off-by-one error happens when you use array subscripts that are off by
one.

This can happen when you start subscripts at 1 rather than 0:

Partial Array Initialization

If array is initialized with fewer initial values than the size declarator, the
remaining elements will be set to 0:

Implicit Array Sizing


Can determine array size by the size of the initialization list:
int quizzes[]={12,17,15,11};

12 17 15 11

Must use either array size declarator or initialization list at array definition

3
Using a Loop to Step Through an Array

Via a for loop


To input values in to the array val from keyboard :

for (int i = 0; i < 4; i++)


cin >> val[i]; //Input from keyboard

Implicit array sizing


Can determine array size by the size of the initialization list:

String names[ ] = {“Ana”, “Caleb”, “ Frank”, ”Justin”, ”Mary”, “Henry”};


0 1 2 3 4 5
Ana Caleb Frank Justin Mary Henry

cout << names[0]; // would display the name Ana


cout << names[3]; // would display the name Justin
cout << names[5]; // would display the name Henry
cout << names[6]; // ERROR- INVALID index

Input/Output
Inputting, outputting, initializing, processing an array is done through for loop –
which effectively means you can’t display the entire array at once by just it’s
variable name.
All the elements need to be processed one at a time

To display values stored in the array val :


for ( int i = 0; i < 4; i++)
cout << val[i];

Array Assignment
Arrays DON’T support aggregate operations (like array assignment, display)
Data Elements inside an array need to be accessed via their subscript
operator.

4
An entire array cannot be assigned to another array (tests and val are
two arrays)
val = tests // does not work
for ( int i = 0; i < ARRAY_SIZE; i++)
val[i]= tests[i]= ;

No Bounds Checking in C++

When you use a value as an array subscript, C++ does not check it to make
sure it is a valid subscript.

In other words, you can use subscripts that are beyond the bounds of the
array

Invalid subscripts can corrupt other memory locations, crash program, or


lock up computer, and cause elusive bugs

NOTE:

Arrays are in static mode when their size is declared; dynamic arrays without
predefined size are known as vectors.

Unlike arrays, vectors can grow or shrink in size dynamically via some specialized
functions.

You have to be careful so that the last index position does not exceed the
declared size of the array. C++ does NOT do any bounds checking – you will end
up getting a runtime error for accessing unallocated memory.

Example: const int SIZE = 4;

cout << val[4] ;

Invalid index position that DOES NOT exist


As array val is declared to contain ONLY four
elements indexed 0 through 3.

5
Summing and Averaging Array Elements
Use a simple loop to add together array elements:
int tnum;
double average, sum = 0;
for(tnum = 0; tnum < SIZE; tnum++)
sum += tests[tnum];

Once summed, can compute average:


average = sum / SIZE;

Finding the Highest Value in an Array

int count;
int highest;
highest = numbers[0];

for (count = 1; count < SIZE; count++)


{
if (numbers[count] > highest)
highest = numbers[count];
}

When this code is finished, the highest variable will contains the highest
value in the numbers array.

Comparing Arrays

To compare two arrays, you must compare element-by-element:

const int SIZE = 5;


int firstArray[SIZE] = { 5, 10, 15, 20, 25 };
int secondArray[SIZE] = { 5, 10, 15, 20, 25 };
bool arraysEqual = true; // Flag variable
int count = 0; // Loop counter variable

6
// Compare the two arrays.
while (arraysEqual && count < SIZE)
{
if (firstArray[count] != secondArray[count])
arraysEqual = false;
count++;
}
if (arraysEqual)
cout << "The arrays are equal.\n";
else
cout << "The arrays are not equal.\n";

Using Parallel Arrays

Parallel arrays: two or more arrays that contain related data


A subscript is used to relate arrays: elements at same subscript are related
Arrays may be of different types

//Prog 1 Logic

7
//Prog 1 – Uses two parallel arrays: one for hours and one for pay rate

8
Arrays as Function Arguments

To pass an array to a function, just use the array name:


showScores(tests);

To define a function that takes an array parameter, use empty [] for array
argument:
void showScores(int []); // function prototype
void showScores(int tests[]) // function header
When passing an array to a function, it is common to pass array size so that
function knows how many elements to process:
showScores(tests, ARRAY_SIZE);

Array size must also be reflected in prototype, header:

9
void showScores(int [], int); // function prototype

void showScores(int tests[],int size)// function header

//Prog 2- Demonstrates an array being passed to a function

10
Modifying Arrays in Functions

• Array names in functions are like reference variables – changes made to


array in a function are reflected in actual array in calling function.

• Need to exercise caution that array is not inadvertently changed by a


function

Two-Dimensional Arrays
Can define one array for multiple sets of data

Use two size declarators in definition:


const int ROWS = 4, COLS = 3;
int exams[ROWS][COLS];

First declarator is number of rows; second is number of columns


Use two subscripts to access element: exams[2][2] = 86;
columns

r exams[0][0] exams[0][1] exams[0][2]


o
w exams[1][0] exams[1][1] exams[1][2]
s
exams[2][0] exams[2][1] exams[2][2]
exams[3][0] exams[3][1] exams[3][2]

11
2D Array Initialization
Two-dimensional arrays are initialized row-by-row

Can omit inner { }, some initial values in a row – array elements without
initial values will be set to 0 or NULL

const int ROWS = 2, COLS = 2;


int exams[ROWS][COLS] = { {84, 78},
{92, 97} };

84 78

92 97

Files and arrays

Input File

12
Prog 3: Program reads data from a file into an array

13

You might also like