170 likes | 384 Views
APS105. Arrays. Collecting Elements. How to collect elements of the same type? Eg: ., marks on assignments: Eg: a solution in math: x 1 , x 2 , x 3 , x 4 , x 5 , x 6 Eg: a (bad) solution in C: int mark1, mark2, mark3, mark4, mark5, mark6;
E N D
APS105 Arrays
Collecting Elements • How to collect elements of the same type? • Eg: ., marks on assignments: • Eg: a solution in math: x1, x2, x3, x4, x5, x6 • Eg: a (bad) solution in C: int mark1, mark2, mark3, mark4, mark5, mark6; • not very efficient, can’t manipulate marks in a loop • Awkward to add more marks a better solution: arrays!
Declaring an Array in C • General form: <type> <identifier>[<size>]; • Example: .
Initializing Arrays • General form: <type> <identifier>[] = {<value_list>}; • Examples: .
Init. Arrays with Length and Values • if length is greater than number of values: • remaining values default to zeros • if length is less than number of values: • error message (from the compiler) • Examples: .
An array with indices starting at 1 • C always starts arrays at index 0 • but sometimes this is inconvenient • or makes our code harder to read • Solution: • waste some entries to allow better indexing • Example: store t1=0.5,t2=0.25,t3=0.125 .
Maniuplating Arrays #define MAX 10 double list[MAX]; // set all elements to 1.0 .
Maniuplating Arrays #define MAX 10 double list[MAX]; // sum all the elements .
Maniuplating Arrays • Given an array: • Write a program to reverse the order of elements
Maniuplating Arrays double list[MAX]; // reverse the order of elements .
Array Identifiers as Pointers • Consider: int x[] = {9,7,2}; . Memory
Array Identifiers as Arguments • Since array identifiers are really pointers • can now easily pass an array as an argument • Example: .
Example: Swap • write a function to swap two array locations . Memory
Array Parameters and Size • Passing an array as a param gives no size • hence the function does not know array size • if needed, array size must be passed separately • Example: a function that sums an array: .