1 / 17

APS105

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;

graham
Télécharger la présentation

APS105

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. APS105 Arrays

  2. 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!

  3. Declaring and Initializing Arrays

  4. Declaring an Array in C • General form: <type> <identifier>[<size>]; • Example: .

  5. Initializing Arrays • General form: <type> <identifier>[] = {<value_list>}; • Examples: .

  6. 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: .

  7. 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 .

  8. Manipulating Arrays

  9. Maniuplating Arrays #define MAX 10 double list[MAX]; // set all elements to 1.0 .

  10. Maniuplating Arrays #define MAX 10 double list[MAX]; // sum all the elements .

  11. Maniuplating Arrays • Given an array: • Write a program to reverse the order of elements

  12. Maniuplating Arrays double list[MAX]; // reverse the order of elements .

  13. Arrays as Pointers

  14. Array Identifiers as Pointers • Consider: int x[] = {9,7,2}; . Memory

  15. Array Identifiers as Arguments • Since array identifiers are really pointers • can now easily pass an array as an argument • Example: .

  16. Example: Swap • write a function to swap two array locations . Memory

  17. 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: .

More Related