arrays. related data items collection of the same types of data. static entity – same size...

46
Arrays

Upload: lisa-wilkinson

Post on 29-Jan-2016

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Arrays

Page 2: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Arrays• Related data items

• Collection of the same types of data.

• Static entity – Same size throughout program

Page 3: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Arrays• Simple data type => data element contains a

single value

• Array is a structured data-type (Collection of values):

1515 84.3584.35 ‘A’‘A’

85 79 92 57 68 80 85 79 92 57 68 80

Page 4: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Array Fundamentals

• Arrays can hold a few data items or tens of thousands.

• The data items grouped in an array can be simple types such as int or float, or they can be user-defined types such as structures and objects.

Page 5: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Array Fundamentals

• Arrays are like structures in that they both group a number of items into a larger unit.

• A structure usually group items of different types but an array group items of the same type.

• More importantly, the items in a structure are accessed by name, while those in an array are accessed by an index number.

• Using an index number to specify an item allows easy access to a large number of items.

Page 6: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

One Dimensional Array

31

34

38

36

30

29

26

int WeeklyTemp[7];

0

1

2

3

45

6

WeeklyTemp

4 bytes

cout<< WeeklyTemp[0];cout<< WeeklyTemp[2];cout<< WeeklyTemp[4];

Page 7: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaring Array Variables datatype arrayName[arraySize];

Example:

double myList[10];

Array Size: MUST BE constant - constant literal - constant identifier

int size = 4;double myList[size]; // Wrongconst int size = 4;double myList[size]; // Correctdouble myList[20]; // Correct

Page 8: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Array Elements

• The items in an array are called elements (in contrast to the items in a structure, which are called members).

• All the elements in an array are of the same type; only the values vary.

Page 9: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Input/Output of Array elements

int marks[3];

marks[0] = 76;

marks[1] = 65;

marks[2] = 27;

cout<<marks[2]<<marks[0]<<marks[1];

Page 10: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Input/Output of Array elements – Using Loops

int marks[5];

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

cin>>marks[i];

for(int j=0;j<5;j++)

cout<<marks[j];

Page 11: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Indexed Variables• Array elements are accessed through the index. • Array indices are 0-based; that is, they start from 0 to arraySize-1.

For example:

int marks[5];

Five int values: marks[0], marks[1], marks[2], marks[3], marks[4]

Page 12: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Using Indexed Variables

• An indexed variable can be used in the same way as a regular variable.

• For Example:

myList[2] = myList[0] + myList[1];

Page 13: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example Code

Page 14: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

OUTPUT

Page 15: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

No Bound Checking

• C++ does not check array’s boundary.

• So, accessing array elements using subscripts (index variable) beyond the boundary does not cause syntax errors,

• But the operating system might report a memory access violation (Compiler or System may crash!)

Page 16: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Arbitrary Initial Values

• When an array is created, its elements are assigned with arbitrary values.

int marks[5];

for(int i=0;i<5;i++)cout<<marks[i];

Page 17: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Initializing an Array

dataType arrayName[Size] = {value0, value1, ..., valuek};

• Example:

int myList[4] = {32, 11, -6, 65};

Page 18: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaring, creating, initializing Using the Shorthand Notation

int myList[4] = {32, 11, -6, 65};

This shorthand notation is equivalent to the following statements:

int myList[4];myList[0] = 32;myList[1] = 11;myList[2] = -6;myList[3] = 65;

Page 19: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Initializing Wrong way

int myList[4]; myList = {32, 11, -6, 65};

Page 20: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Implicit Size

• C++ allows you to omit the array size

• For example, the following declaration is fine/correct:int myList[ ] = {63, 9, 3, 13};

C++ automatically figures out how many elements are in the array.

int myList [ ]; // WRONG

Page 21: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Partial Initialization

• C++ allows you to initialize a part of the array. double myList[4] = {1.9, 4.65}; //correct

- The above example assigns values 1.9, 4.65 to the first two elements of the array.

- The other two elements will be set to zero.

- Note: If an array is declared, but not initialized, all its elements will contain “garbage”, like all

other local variables.

Page 22: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Copying Arrays • Can you copy array using a syntax like this?

int list[3]; int myList[3];list = myList; // WRONG

• This is not allowed in C++. You have to copy individual elements from one array to the other as follows:

for (int i = 0; i < 3; i++) {

list[i] = myList[i]; }

Page 23: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Arrays of Structures

Page 24: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program
Page 25: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program
Page 26: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

C-Strings or Character Arrays• The elements of an array can be just about

anything (any-datatype)

• Consider an array whose elements are all characters (char type)–Called a C-String

Page 27: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaration of C-Strings• Similar to declaration of any array:

char name[30]; // no initialization

char title[20] = “Hello World"; //initialized at declaration with a string

char chList[6] = {‘H', ‘e', ‘l', ‘l‘, ’o’};//initialized with list of char values

Page 28: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Initializing Character Arrays char city[ ] = "Dallas";

city[0]

city[1]

'D'

'a'

'l'

'l'

'a'

's'

'\0'

city[2]

city[3]

city[4]

city[5]

city[6]

Page 29: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Printing Character Array

• For a character array, it can be printed using one print statement.

• Character arrays are handled differently than other types of arrays

For example:

char city[ ] = "Dallas"; cout << city; // Correct

int marks [ ] = {20,65,30}; cout << marks; // Wrong

Page 30: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Character Array (string) Input• Declare strings 1 element bigger than planned size to

allow for ‘\0’ (null character)char city[10];

cin>> city; //User enters Islamabad

• When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

Page 31: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example-2: Reversing an Array

Write a program to create an array of 10 elements, assign each element value (1 to 50). Print the array values. Then, Reverse the values stored in array. Output the final array values.

Page 32: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Two Dimensional Arrays

Page 33: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Two Dimensional Arrays• A two dimensional array stores data as a logical

collection of rows and columns

• Each element of a two-dimensional array has a row position and a column position (indicated by two indexes)

• To access an element in a two-dimensional array, you must specify the name of the array followed by:– a row index– a column index

Page 34: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaration and Initialization• Declaration of a two-dimensional array requires a

row size and a column size

• A consecutive block of (row size)*(column size) memory locations are allocated.

• All array elements must be of the same type.

• Elements accessed by two offsets: a row offset and a column offset.

Page 35: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example//Declaration int data[2][3];

? ? ?? ? ?

row 0

row 1

col 0 col 1 col 2

Page 36: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaring Arrays

datatype arrayName[rowSize][coulmnSize];

Example:

double myList[2][4];

rowSize, and coulmnSize: MUST BE constant

- constant literal - constant identifier

Page 37: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Declaring and Initializing Arrays

int myList[3][2] = {{22,33}, {44,55}, {66,77}};

myList has 3 Rows and 2 coulmns in each row

In memory:

22 33

44 55

66 77

0

1

2

0 1

Coulmn Indexes

Row Indexes

Page 38: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Initialization Examples

int temp[4][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

int temp[][3] = {{50, 70, 60}, {48, 75, 62}, {51, 69, 60}, {52, 78, 63}};

Page 39: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example: Input Using cin• Nested for loops are often used when inputting

and assigning values to a two-dimensional array.

//Declaration double table[10][10];

for (int i=0; i<10; ++i) //every row for (int j=0; j<10; ++j ) //every col cin >> table[i][j];

Page 40: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example: Assignment//Declaration const int RSIZE=3;Const int CSIZE=2;double v[RSIZE][CSIZE];

for (int i=0; i<RSIZE; ++i) //every row for (int j=0; j<CSIZE; ++j )//every col v[i][j] = i+j;

0 1

1 2

2 3

V

Page 41: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Example: Computations• Compute the average value of an matrix with n

rows and m columns.

double sum=0; double average;

for (int i=0; i<n; i++) //every row for (int j=0; j<m; j++ )//every col sum += array[i][j];

average = sum / (n*m);

Page 42: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Passing Arrays to Functions

Page 43: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Higher-Dimensional Arrays- An array can be declared with multiple dimensions.

2 Dimensional 3 Dimensional

- Multiple dimensions get difficult to visualize graphically.

double Coord[100][100][100];

Single value

1D Array 2D Array 3D Array

Page 44: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Larger-Dimension Arrays• Arrays with more than two dimensions allowed in

C++ but not commonly used

Example: int response[4][10][6];

– First element is response[0][0][0]– Last element is response[3][9][5]

Page 45: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

Common Programming Errors• Forgetting to declare an array – Results in a compiler error message

• Using a subscript that references a nonexistent array element– For example, declaring array to be of size 20 and using

a subscript value of 25– Not detected by C++ compilers and will probably cause

a runtime error

Page 46: Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program

(Nested Loops) – Example Program- Write a program to that creates a matrix of size 5 by 5 (5

Columns, and 5 Rows). The program should ask the user to enter values in each matrix element. Then the program should display the left-diagonal elements of the matrix.

Example:

1 2 3 4

5 6 7 8

9 10 11 12

13 14 15 16

Output 1, 6, 11, 16,