0% found this document useful (0 votes)
12 views38 pages

4 - Arrays

The document provides an overview of arrays, including their definition, declaration, and usage in programming. It explains how to reference individual elements, the importance of subscripts, and the initialization of arrays. Additionally, it discusses common errors related to array indexing and provides examples of array operations.

Uploaded by

Omgt Hfuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views38 pages

4 - Arrays

The document provides an overview of arrays, including their definition, declaration, and usage in programming. It explains how to reference individual elements, the importance of subscripts, and the initialization of arrays. Additionally, it discusses common errors related to array indexing and provides examples of array operations.

Uploaded by

Omgt Hfuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

ARRAYS

The Array Data Type 2

• Array elements have a common name score


• The array as a whole is referenced score[0 95 0
through the common name ]
65
1
84 2
• Array elements are of the same type 67
3
— the base type
• Individual elements of the array are score[i
referenced by sub-scripting the group ]

name
• element’s relative position used,
beginning with 0
92
• Array stored in consecutive memory score[n-1] n-1
Introduction to Arrays Slide 7- 3

• An array is used to process a collection of data


of the same type
• Examples: A list of names
A list of temperatures
• Why do we need arrays?
• Imagine keeping track of 5 test scores, or 100, or 1000 in memory
• How would you name all the variables?
• How would you process each of the variables?
Array Declaration
4

element-type array-name [array-size];

Type of all Name of the Integer


the values entire expression
in the array collection of indicating
values number of
elements in
float x[50];
Int n=35; const int MAX_NUM= 100; the array
Int y[n] string student_name[MAX_NUM];

Int N int n;
cin>>N; cin>> n,
char for (int i=0 ; i<n, i++)
z[N]; cin>> student_name[i];
Array Declaration Syntax Slide 7- 5

• To declare an array, use the syntax:


Type_Name Array_Name[Declared_Size];
• Type_Name can be any type
• Declared_Size can be a constant to make your
program more versatile
• Once declared, the array consists of the indexed
variables:
Array_Name[0] to Array_Name[Declared_Size -1]
Using [ ] With Arrays Slide 7- 6

• In an array declaration, [ ]'s enclose the size


of the array such as this array of 5 integers:

int score [5];

• When referring to one of the elements,


the [ ]'s enclose a number identifying one of
the elements

• score[3] is one of the array elements

• The value in the [ ]'s can be any expression that evaluates to one of the
integers 0 to (size -1)
Declaring an Array Slide 7- 7

• An array, named score, containing five variables


of type int can be declared as
int score[ 5 ];
• This is like declaring 5 variables of type int:
score[0], score[1], … , score[4]
• The value in brackets is called
• A subscript
• An index
Array Subscripts 8

• Enclosed in brackets ([ ])
• Indicates which element is referenced by
position
• Array subscript value is different than array
element value
• Subscript can be an expression of any integral
type
• To be valid, subscript must be a value between
0 and one less than the array size
The Array Variables Slide 7- 9

• The variables making up the array are referred to


as
• Indexed variables
• Subscripted variables
• Elements of the array

• The number of indexed variables in an array is


the declared size, or size, of the array
• The largest index is one less than the size
• The first index value is zero
Array Variable Types Slide 7- 10

• An array can have ELEMENTS of any type

• All ELEMENTS in an array are of the same type

• This is the base type of the array

• Array element can be used anywhere an


ordinary variable of the base type is used
Assignment of values to array elements Slide 7- 11

• To assign a value to an indexed


variable, use the assignment
operator:

int n = 2;
score[n + 1] = 99;

• In this example, variable score[3] is


assigned 99
Loops And Arrays Slide 7- 12

• for-loops are commonly used to step through


arrays
First index
is 0 Last index is (size – 1)

• Example: for (int i = 0; i < 5; i++)


{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score and the
maximum score stored in an array

Display 7.1
Display 7.1
Back Next
Slide 7- 13
Constants and Arrays Slide 7- 14

• Use constants to declare the size of an array


• Using a constant allows your code to be
easily
altered for use on a smaller or larger set of
data
• Example: const int NUMBER_OF_STUDENTS =
50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i <
NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by "
<< (max – score[i]) << endl;
• Only the value of the constant must be changed
Computer Memory Slide 7- 15

• Computer memory consists of numbered


locations called bytes
• A byte's number is its address

• A simple variable is stored in consecutive bytes


• The number of bytes depends on the variable's type

• A variable's address is the address of its first byte


Array Declaration Syntax Slide 7- 16

• To declare an array, use the syntax:



Type_Name Array_Name[Declared_Size];

• Type_Name can be any type


• Declared_Size can be a constant to make your
program more versatile
• Once declared, the array consists of the indexed
variables:

Array_Name[0] to Array_Name[Declared_Size -1]
Arrays and Memory Slide 7- 17

• Declaring the array int a[6]


• Reserves memory for six variables of type int
• The variables are stored one after another
• The address of a[0] is remembered
• The addresses of the other indexed variables is not
remembered
• To determine the address of a[3]
• Start at a[0]
• Count past enough memory for three integers to find a[3]

Display 7.2
Display 7.2 Slide 7- 18
Array Index Out of Range Slide 7- 19

• A common error is using a nonexistent index


• Index values for int a[6] are the values 0 through 5
• An index value not allowed by the array declaration is out of range
• Using an out of range index value doe not produce an error
message!
Array Index Out of Range Slide 7- 20

• A common error is using a nonexistent index


• Index values for int a[6] are the values 0 through 5
• An index value not allowed by the array declaration is out of range
• Using an out of range index value do not produce an error message!
Array Initialization 21

• List of initial values enclosed in braces ({


}) following assignment operator (=)
• Values from initialization list are
assigned in order to array elements
• Length of initialization list cannot exceed
size of the array
• If too few values, value assigned is
system dependent
• Size of array can be automatically set to
number of initializing values using
empty brackets ([ ])
Example 1 22

element-type array-name [array-size] = {initialization-list};

float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5};
x[5]=4.5;

16.0 12.0 6.0 8.0 2.5 12.0 14.0 -54.5


Example 1 (con’t) 23

cout << x[0];


x[3] = 25.0;
sum = x[0] + x[1];
sum += x[2];
x[3] += 1.0;
x[2] = x[0] + x[1];
Example 2 24

const int NUM_EMP = 10;


bool onVacation[NUM_EMP];
int vacationDays[NUM_EMP];
enum day {sunday, monday, tuesday,
wednesday, thursday, friday, saturday};
day dayOff[NUM_EMP];
float plantHours[7];
Figure 9.3 Arrays onVacation, vacationDays, and
dayOff 25
9.2 Sequential Access to Array Elements 26

• Random Access
• Access elements is any order
• Sequential Access
• Process elements in sequential order starting with the first
Example of Sequential Access 27

int cube[10];
for (int i = 0; i < 10; i++)
cube[i] = i * i * i;
Strings and Arrays of Characters 28

• string object uses an array of char


• Can reference individual character of a string
object in different ways
• name[ i ]
• name.at( i )
• Other member functions of string class
• message.length( i )
Initializing Arrays Slide 7- 29

• To initialize an array when it is declared


• The values for the indexed variables are enclosed in braces and
separated by commas
• Example: int children[3] = { 2, 12, 1 };
Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;
Example 1 30

element-type array-name [array-size] = {initialization-list};

float x[8] = {16.0, 12.0, 6.0, 8.0, 2.5, 12.0, 14.0, -54.5};
Default Values Slide 7- 31

• If too few values are listed in an initialization


statement
• The listed values are used to initialize the first of the indexed
variables
• The remaining indexed variables are initialized to a zero of the base
type
• Example: int a[10] = {5, 5};
initializes a[0] and a[1] to 5 and
a[2] through a[9] to 0
Un-initialized Arrays Slide 7- 32

• If no values are listed in the array declaration,


some compilers will initialize each variable to a
zero of the base type

• DO NOT DEPEND ON THIS!


Reading Part of an Array 34

• Sometimes it is difficult to know how many


elements will be in an array
• 150 students in one section
• 200 students in another section
• Always allocate enough space for largest
possible amount needed
• Remember to start reading with index [0]
• Must keep track of how many elements used
Finding the Smallest Value 35

1. Assume the first element is smallest so far and


save its subscript

2. For each array element after the first one

2.1 If the current element < the smallest so far


2.1.1 Save the subscript of current element
(1)- Show the output of the following program segment:

Exersices on 1-D Arrays

(1)- Show the output of the following program segment:

int A [ 4 ] = {2, -1, 3, 2};


int B [ 4 ] = {1, -2, 2, 3};
int sum = 0;
for( int i = 0; i < 4; i++ )
sum += A [ i ] * B [ i ];

cout << "The sum is " << sum


<< endl;
2- Create a program segment that takes a 1-D array
and flips all its values.

A B
• Example
14 12

67 98
• 3 73
• 31 74
38 38

74 31
• 73 3
• 98 67
12 14
2- Create a program segment that takes a 1-D array and flips
all its variables.

A B
• Example
14 12
• int N=9;
67 98
• int A[N] = {14 , 67 , 3 , 31 , 38 , 74 , 73 , 98 , 12}; 3 73
31 74
• int B[N]; 38 38
74 31
• for (int i=0 ; i<N ; i++) 73 3
• B[i] = A[N-1-i]; 98 67

• 12 14

You might also like