You are on page 1of 16

ENGR 1200U Introduction to Programming Lecture 19 Arrays and Vectors

Dr. Eyhab Al-Masri

1992-2012 by Pearson Education, Inc. & John Wiley & Sons Some portions are adopted from C++ for Everyone by Horstmann

What is the difference between an argument and a return value?

Anargument isanexpressionthatissenttoafunction asaninputtothatfunction(itappearsinthe parenthesesofafunctioncall) Areturnvalueisapieceofdatathatisoutputbya function,andsentbacktothecallingfunction.

ENGR 1200U Winter 2013 - UOIT

What is a local variable lifetime?

Alocalvariableexistsonlywhilethefunctionitis definedinisexecuting Thisisknownaslifetimeofalocalvariable

ENGR 1200U Winter 2013 - UOIT

Is it possible to use parameter variables to initialize local variables?

Yes. int sum(int num1,int num2) { int result=num1+num2; return result; }

ENGR 1200U Winter 2013 - UOIT

What are global constants?

Aglobalconstantisanamedconstantthatisavailable toeveryfunctioninaprogram Globalconstantsaretypicallyusedtorepresent unchangingvaluesthatareneededthroughoutaprogram

ENGR 1200U Winter 2013 - UOIT

Can you have two local variables with the same name?

No. int sum(int num1) { int num1=0; return num1; }

ENGR 1200U Winter 2013 - UOIT

Can you have a local and global variables with the same name?

Yes. int num1 ... int sum(int num1) { num1=0; return num1; }
ENGR 1200U Winter 2013 - UOIT

What is a static variable?

Sometimesitisdesirableforaprogramtoremember whatvalueisstoredinalocalvariablebetweenfunction calls. Thisisaccomplishedbymakingthevariablestatic Staticvariablesarenotdestroyedwhenafunction returns

ENGR 1200U Winter 2013 - UOIT

What does it mean to overload a function?

ATwoormorefunctions mayhavethesamename, aslongastheir parameterlistsare different

int square(int number) { return number*number; } double square(double number) { return number*number; }

ENGR 1200U Winter 2013 - UOIT

When working with a large number of values, it is important to be able to manage large collections of data

Example Suppose we would like to store a set of 100 temperature measurements to be used for perform several computations Solution - Create different names for the temperature measurements? - Use a method that can work with a group of values?

your best choice is to use a array

ENGR 1200U Winter 2013 - UOIT

By using a array, you


Can conveniently manage collections of data Do not have to worry about the details of how they are stored Do not worry about how many are in the vector
automatic resizing

so what is the difference between vector and an array?

ENGR 1200U Winter 2013 - UOIT

An array allows you to store and work with multiple values of the same data type

CONCEPT

The variables you worked with so far are designed to hold only one value at a time Each of the variable definitions (below) cause only enough memory to be reserved to hold one value of the specified data type
int count; Enoughmemoryfor1int 1234
56.5 double price; Enoughmemoryfor1double

char letter; Enoughmemoryfor1char A


ENGR 1200U Winter 2013 - UOIT

An array works like a variable that can store a group of values, all of the same data type. The values are stored together in consecutive memory locations.

How it works?

Example
string WeekyDays[7];//enoughmemorytoholdsevenstringvalues

Element 0

Element 1

Element 2

Element 3

Element 4

Element 5

Element 6

ENGR 1200U Winter 2013 - UOIT

An array size declarator must be a constant integer expression with a value greater than 0 It can be either a literal (as in the previous example) or a named constant, as shown here:

Example
const int SIZE=7; string WeekyDays[SIZE];

ENGR 1200U Winter 2013 - UOIT

A one-dimensional array can be visualized as a list of values arranged in either a row or a column Individual elements of the array are specified using the array name and an offset. In C++ the offset of the first element is always 0 (zero).

ENGR 1200U Winter 2013 - UOIT

Example
const int SIZE=7; string WeekyDays[SIZE];

WeekDays[0] WeekDays[1] WeekDays[2] WeekDays[3] WeekDays[4] WeekDays[5] WeekDays[6] WeekDays[0] WeekDays[1] WeekDays[2] WeekDays[3] WeekDays[4] WeekDays[5] WeekDays[6]
ENGR 1200U Winter 2013 - UOIT

We assign a type and an identifier to an array and then distinguish between elements, or values, in the array using offsets Offsets are also referred to as indices or subscripts

Definition Syntax
data_type identifier[array_size][=initialization_list];

Examples
floattemperature[100]; charletter[26]; doublesize[1200]; stringname[10]; //Arrayof100floats //Arrayof26characters //Arrayof1200doubles //Arrayof10stringobjects

ENGR 1200U Winter 2013 - UOIT

Initializing Arrays
Initializing array elements (initialization=>declaration)
char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; bool ansKey[] ={true, true, false, true, false, false};

vowels
'a' 'e' 'i' 'o' 'u'

ansKey
true true false true false false

ENGR 1200U Winter 2013 - UOIT

ENGR 1200U Winter 2013 - UOIT

Table 6..1: C++ for Everyone by Cay Horstman

CONCEPT
Individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements

Individual Variables
Although an entire array has only one name, elements may be accessed and used as individual variables
This is possible because each element is assigned a number (or subscript) A subscript is used as an index to pinpoint a specific element in an array

ENGR 1200U Winter 2013 - UOIT

10

Example
WeekDays[0] = Sunday;
Sunday

// pronounced WeekDays sub zero

WeekDays[0] WeekDays[1] WeekDays[2] WeekDays[3] WeekDays[4] WeekDays[5] WeekDays[6]

WeekDays[3] = Wednesday;
Sunday

Wednesday

WeekDays[0] WeekDays[1] WeekDays[2] WeekDays[3] WeekDays[4] WeekDays[5] WeekDays[6]

ENGR 1200U Winter 2013 - UOIT

Defining an Array

ENGR 1200U Winter 2013 - UOIT

11

Example

Given the array:


double values[] = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };

To access the element at index 4 using this notation: values[4] 4 is the index (or subscript)

32.0 54.0 67.5 29.0 35.0 80.0 115.0 44.5 100.0 65.0

ENGR 1200U Winter 2013 - UOIT

Example

Given the array:


double values[] = { 32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65 };

To access the element at index 4 using this notation: values[4] 4 is the index (or subscript) double values[10]; ... cout << values[4] << endl; The output will be 35.0
ENGR 1200U Winter 2013 - UOIT

32.0 54.0 67.5 29.0 35.0 80.0 115.0 44.5 100.0 65.0

12

Example (contd)

The same notation can be used to change the element values[4] = 17.7;
32.0 54.0 67.5 29.0 35.0 80.0 115.0 44.5 100.0 65.0
ENGR 1200U Winter 2013 - UOIT

Example (contd)

The same notation can be used to change the element values[4] = 17.7;
32.0 54.0 67.5 29.0 17.7 80.0 115.0 44.5 100.0 65.0
ENGR 1200U Winter 2013 - UOIT

13

Example (contd)

The same notation can be used to change the element values[4] = 17.7; ... cout << values[4] << endl; The output will be 17.7
32.0 54.0 67.5 29.0 17.7 80.0 115.0 44.5 100.0 65.0
ENGR 1200U Winter 2013 - UOIT

Example (contd)
You might have thought those last two slides were wrong: values[4] is getting the data from the fifth element.
32.0 54.0

cout << values[4] << endl;

67.5 29.0

In C++ and most computer languages, indexing starts with 0

17.7 80.0 115.0 44.5 100.0 65.0

ENGR 1200U Winter 2013 - UOIT

14

Example (contd)
That is, the legal elements for the values array are: values[0], values[1], values[2], values[3], values[4], ... values[9], the the the the the

first element second element third element fourth element fifth element

the tenth and last legal element recall: double values[10];

The index must be >= 0 and <= 9. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 is 10 numbers.


ENGR 1200U Winter 2013 - UOIT

NOTE
What is the difference between the array size declarator and a subscript?

The number inside the square brackets in an array definition is the size declarator (specifies how many elements the array holds) The number inside the square brackets in an assignment statement or any statement that works with the contents of an array is a subscript

ENGR 1200U Winter 2013 - UOIT

15

BUGS C++ does not enforce array bounds

Invalid references are NOT reported by the compiler May or may not result in run-time error Examples: segmentation fault, bus error Such errors are often difficult to identify Results in unpredictable program behavior

ENGR 1200U Winter 2013 - UOIT

16

You might also like