17
Arrays

Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Embed Size (px)

Citation preview

Page 1: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Arrays

Page 2: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Why array?Lots of times we want to store a large number of data of same typeEx, 30 students’ midterm exam score

Page 3: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Why arrayArrays allow you to group individual elements

together into a single data structure, with a single name

It’s hard to do any serious programming without relying heavily on arrays

These elements are stored in contiguous memory locations, and are thus easy for the compiler to find if you tell it the index of the element you want – “give me the 4th element”

It is easy to sort themThe code are compact

Page 4: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Declaring ArrayCompiler need to know:

TypeNameSize

Example: int score[16]; const in size=16; double score[size];

char name[20];

Page 5: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Accessing arrayWe can access individual elements of the

array using brackets after the array nameExamples:

If homeScores is an array of int, an individual element of the array is of type int, and can be used anywhere an int is usedint currentScore = homeScores[3];

Note: this reads 4th element (indices start at 0)homeScores[0] = 0;total = inputNums[0] + inputNums[1];

The I/O functions know how to work with arrayscin >> inputNums[4];

If the inputNumber is double type, compiler knows that one element of inputNums is of type double, so it will go read a double

Page 6: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

CautionYou must be very careful with your array

accessesCauses some nasty bugs

When you run off the end of the array, you may change another variable, and the bug appears to be in the other variableint myArray[20];int myNum = 0;…myArray[20] = 5; // you probably just

changed the // value of myNum

Array index start from 0.

Page 7: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Initializing arrayInitializing arrays

We like to initialize all of our variables when we declare them

Likewise, it is good to initialize arraysGlobal scope:  Automatically initialized to zero (or

equivalent) Local scope:  Not automatically initialized

Methods of initializing arrays1.You can initialize when you declare them

int primes[5] = {3, 5, 7, 11, 13}; //full initializationYou can even leave off the array size

int nums[ ] = {0, 1, 2, 3, 4}; //implicit iniitalizationIf you provide less values than elements, it will pad

with zeros: int nums[8] = {0, 1, 2}; makes it {0,1,2,0,0,0,0,0} //partital intialization

2.You can use a loop to initialize the arrayfor (i = 0; i < arraySize; i++) {

myArray[i] = -1;}

Page 8: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Exercise you declare an array: int myArray[10] = {1, 2, 3,

4}What is the value of x after:

x = myArray[1]x = myArray[3]x = myArray[0]x = myArray[7]x = myArray[10]

Which of these are legal?myArray[4] = myArray[3];myArray[3] = 0;0 = myArray[0];int x = myArray;float f = myArray[9];

Page 9: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Example use of arrays int i= 0; int numValues; int values[100]; double total = 0.0; cout<<“please enter a number that is less than 100:”<<endl; cin>> numValues;

cout<<“please enter “<<numValues<< “integers”<<endl; cout<<“I can average them for you”<<endl;

for (i=0; i< numValues; i++) { cin >> values[i]; }

for (i=0; i< numValues; i++) { total += values[i]; } double average = total / numValues; cout << “ The average value of all the numbers you input is“ << average << endl;}

Page 10: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Constant arrays

const int studentID[3] = {1234, 4321, 2341};

The values of the array are constant and cannot be changedWhich of the following would be legal?

int x = studentID[2];studentID[1] = studentID[2];studentID[0]++;cout << studentID[2];

Page 11: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Character arrays char myName[10];

Character arrays work just like any other arrayThe type just happens to be char

Before the string class came along, character arrays were the only way to do string processing

You initialize a character array like a stringchar myProfession[9] = “engineer”Note that “engineer” only has 8 letters, but the array is size 9 – this is

because old C-style strings always are terminated with a special character - \0 (ascii value=0)

You can do I/O like it was a stringcout << myProfession; // will print “engineer”cin >> myProfession; // will read a string into the array

Demo of a C string without null

Page 12: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Character array example

Example:char color[6] = “red”;

char color[6] = “green”;

char color [6] = “tan”

r e d \0 \0 \0

g r e e n \0

t a n \0 \0 \0

Page 13: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

You can also treat character arrays just like any arrayint word[5] = “ball”;word[0] = ‘f’; // “ what you got ? ”word[1] = ‘i’; // “ what you got?”word[3] = ‘e’; // “ what you got?”

oDemo of program: arrayinit.cpp in puTTy

Exercise

Page 14: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Multi-Dimensional Arrays

C++ allows you to represent multi-dimensional data with multi-dimensional arraysTypically we don’t go beyond 3 dimensions, more

because of human understanding limitation than computer limitation

Declaring a multi-dimensional array int matrix [10][10];

Ten rows of ten elements eachActually the compiler just allocates 100

contiguous elements in memory, but computes proper offsets

Page 15: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Array[0] Array[1] Array [2] Array [3] Array [4]

Array[0][0] Array[0][1]

Array[1][0] Array[1][1]

Array[2][0] Array[2][1]

1 dimensional array: array[5]

2 dimensional array: array [3][2]

Page 16: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Multi-Dimensional Arrays

Using a multi-dimension arrayWe use it just like 1-dimensional, but must specify

both row and col int x = nums[2][5];nums[4][7] = 5;

Initializing a multi-dimensional array int nums[3][3] = {1,2,3,4,5,6,7,8,9};

First row is 1,2,3; second row is 4,5,6; third is 7,8,9

Again, if insufficient values are provided, zeros will be added

Page 17: Arrays. Why array? Lots of times we want to store a large number of data of same type Ex, 30 students’ midterm exam score

Multi-Dimensional Arrays Example

What does the following code do?

Demo of flipping a square matrix

for (i = 1; i < size; i++) { for (j =0; j < i; j++) {

temp = square[i][j]; square[i][j] = square[j][i]; square[j][i] = temp; } }