170 likes | 304 Views
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. Arrays allow you to group individual elements together into a single data structure, with a single name
E N D
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 • Arrays 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 them • The code are compact
Declaring Array • Compiler need to know: • Type • Name • Size Example: int score[16]; const in size=16; double score[size]; char name[20];
Accessing array • We can access individual elements of the array using brackets after the array name • Examples: • 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 used • int 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 arrays • cin >> 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
Caution • You must be very careful with your array accesses • Causes 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 variable int myArray[20]; int myNum = 0; … myArray[20] = 5; // you probably just changed the // value of myNum Array index start from 0.
Initializing array • Initializing arrays • We like to initialize all of our variables when we declare them • Likewise, it is good to initialize arrays • Global scope: Automatically initialized to zero (or equivalent) • Local scope: Not automatically initialized • Methods of initializing arrays • You can initialize when you declare them • int primes[5] = {3, 5, 7, 11, 13}; //full initialization • You can even leave off the array size • int nums[ ] = {0, 1, 2, 3, 4}; //implicit iniitalization • If 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 • You can use a loop to initialize the array for (i = 0; i < arraySize; i++) { myArray[i] = -1; }
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];
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; }
Constant arrays • const int studentID[3] = {1234, 4321, 2341}; • The values of the array are constant and cannot be changed • Which of the following would be legal? • int x = studentID[2]; • studentID[1] = studentID[2]; • studentID[0]++; • cout << studentID[2];
Character arrays • char myName[10]; • Character arrays work just like any other array • The 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 string • char 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 string • cout << myProfession; // will print “engineer” • cin >> myProfession; // will read a string into the array • Demo of a C string without null
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
Exercise • You can also treat character arrays just like any array • int word[5] = “ball”; • word[0] = ‘f’; // “ what you got ? ” • word[1] = ‘i’; // “ what you got?” • word[3] = ‘e’; // “ what you got?” • Demo of program: arrayinit.cpp in puTTy
Multi-Dimensional Arrays • C++ allows you to represent multi-dimensional data with multi-dimensional arrays • Typically 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 each • Actually the compiler just allocates 100 contiguous elements in memory, but computes proper offsets
1 dimensional array: array[5] 2 dimensional array: array [3][2]
Multi-Dimensional Arrays • Using a multi-dimension array • We 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
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; } }