100 likes | 256 Views
Engineering 1020. Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010. ENGI 1020: Arrays. We've seen variables a data container of a certain type than holds a single value and is assigned a label Arrays are an extension of variables
E N D
Engineering 1020 Introduction to Programming Peter King peter.king@mun.ca www.engr.mun.ca/~peter Winter 2010
ENGI 1020: Arrays We've seen variables a data container of a certain type than holds a single value and is assigned a label Arrays are an extension of variables a data container or a certain type that can hold many values and is assigned a label An array is a compound variable
ENGI 1020: Arrays Like a variable: int a; Arrays are declared: int b[10]; Where, the number in the square brackets represents the number of values held by the array
ENGI 1020: Arrays int c[10]; double x[22]; char letters[30]; c is an array of 10 integers. x is an array of 22 doubles letters is an array of 30 characters
ENGI 1020: Arrays Think of arrays as a list of homogenous variables Each element is a variable of the type declared Each element can be accessed and changed (they are variable) The entire array resides in memory, which each element in a successive address
ENGI 1020: Arrays Working with arrays: Initialization: int fib[10] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
ENGI 1020: Arrays Element access: int fib[10] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55}; cout << “The first element is: “ << fib[0]; int sum = fib[1] + fib[3] + fib[7]; fib[5] = 12;
ENGI 1020: Arrays IMPORTANT if you declare an array of size n int arry[n]; The elements are indexed 0 to n-1 int nums[9]; has no element 9, just 0,1,2,3,4,5,6,7,8
ENGI 1020: Arrays The size of the array and indexes must be carefully managed Referencing an element outside of the array index is an error. Arrays can be a great way to pass around related data to functions
ENGI 1020: Arrays Online examples using in functions search/sort operations Things you can't do with arrays