cs103 unit 5 arrays
play

CS103 Unit 5 - Arrays Mark Redekopp 2 ARRAY BASICS 3 Motivating - PowerPoint PPT Presentation

1 CS103 Unit 5 - Arrays Mark Redekopp 2 ARRAY BASICS 3 Motivating Example Suppose I need to store the int main() { grades for all students so I can int score1, score2, score3; cin >> score1 >> score2 >> score3; then


  1. 1 CS103 Unit 5 - Arrays Mark Redekopp

  2. 2 ARRAY BASICS

  3. 3 Motivating Example • Suppose I need to store the int main() { grades for all students so I can int score1, score2, score3; cin >> score1 >> score2 >> score3; then compute statistics, sort // output scores in sorted order them, print them, etc. if(score1 < score2 && score1 < score3) • I would need to store them in { /* score 1 is smallest */ } variables that I could access and /* more */ use } – This is easy if I have 3 or 4 students int main() { – This is painful if I have many int score1, score2, score3, students score4, score5, score6, score7, score8, score9, • Enter arrays score10, score11, score12, score13, score14, score15, – Collection of many variables /* ... */ referenced by one name score139, score140; cin >> score1 >> score2 >> score3 – Individual elements can be >> score4 >> score5 >> score6 accessed with an integer index /* ... */

  4. 4 Arrays: Informal Overview • Informal Definition: Just as an apartment building is known by 1 – Ordered collection of variables of the same type address but many apartment numbers, an • Collection is referred to with one name array has one name but can use integer indices • Individual elements referred to by an to access individual elements offset/index from the start of the array [in C, first element is at index 0] int data[20]; data[0] = 103; data[1] = -1; char A[3] = "hi"; data[2] = data[0]+1; A[0] A[1] A[2] data[0] data[1] data[2] data[19] … 860 861 862 863 120 124 128 196 ‘h’ ‘i’ … 00 09 05 04 … 103 -1 104 404 Memory Memory This Photo by Unknown Author is licensed under CC BY-SA

  5. 5 Arrays char A[3] = “hi”; • Formal Def: A statically-sized, contiguously allocated ‘h’ 0 A[0] collection of homogenous data elements ‘i’ 1 A[1] • 2 00 A[2] Collection of homogenous data elements … 3 – Multiple variables of the same data type Memory • Contiguously allocated in memory char c = A[0]; // ’h’ – One right after the next int D[20]; • Statically-sized 200 AB ABABAB D[0] – Size of the collection must be a constant and can’t be 204 ABABABAB ?? D[1] changed after initial declaration/allocation … 208 ABABABAB ?? • 212 ABABABAB ?? Collection is referred to with one name Memory • Individual elements referred to by an offset/index from the start of the array [in C, first element is at index 0] D[1] = 5; 200 AB ABABAB D[0] 204 00 00 00 05 ?? D[1] … Memory

  6. 6 Example: Arrays • Track the score of 3 players int score[3]; • Homogenous data set (amount) for 200 AB ABABAB score[0] 204 ABABABAB ?? score[1] multiple people…perfect for an array 208 ABABABAB ?? score[2] – int score[3]; 212 ABABABAB ?? 216 ABABABAB ?? • Recall, memory has garbage values by 220 ABABABAB ?? 224 ABABABAB ?? default. You will need to initialized each 228 ABABABAB ?? element in the array 232 ABABABAB ?? 236 ABABABAB ?? … … Memory

  7. 7 Example: Arrays • Track the score of 3 players int score[3]; • Homogenous data set (amount) for 200 00 00 00 00 score[0] 204 00 00 00 00 ?? score[1] multiple people…perfect for an array 208 00 00 00 00 ?? score[2] – int score[3]; 212 ABABABAB ?? 216 ABABABAB ?? • Must initialize elements of an array 220 ABABABAB ?? 224 ABABABAB ?? – for(int i=0; i < 3; i++) 228 ABABABAB ?? score[i] = 0; 232 ABABABAB ?? 236 ABABABAB ?? … … Memory

  8. 8 Arrays • Track the score of 3 players int score[3]; • Homogenous data set (amount) for 200 00 00 00 05 score[0] 204 00 00 00 08 ?? score[1] multiple people…perfect for an array 208 00 00 00 03 ?? score[2] – int score[3]; 212 ABABABAB ?? 216 ABABABAB ?? • Must initialize elements of an array 220 ABABABAB ?? 224 ABABABAB ?? – for(int i=0; i < 3; i++) 228 ABABABAB ?? score[i] = 0; 232 ABABABAB ?? 236 ABABABAB ?? • Can access each persons amount and … … perform ops on that value Memory – score[0] = 5; score[1] = 8; score[2] = score[1] - score[0]

  9. 9 ARRAY ODDS AND ENDS

  10. 10 Static Size/Allocation • For now, arrays must be declared as fixed size (i.e. a constant known at compile time) int X[10]; – Good: 200 AB ABABAB X[0] • int x[10]; 204 ABABABAB ?? X[1] • #define MAX_ELEMENTS 100 208 ABABABAB ?? X[2] int x[MAX_ELEMENTS]; 212 ABABABAB ?? • const int MAX_ELEMENTS = 100; 216 ABABABAB ?? int x[MAX_ELEMENTS]; 220 ABABABAB ?? … 224 ABABABAB ?? – Bad: 228 ABABABAB ?? 232 ABABABAB ?? • int mysize; 236 ABABABAB ?? X[9] cin >> mysize; … … int x[mysize]; Memory • int mysize = 10; Compiler must be able to int x[mysize]; figure out how much memory to allocate at compile-time

  11. 11 Initializing Arrays • Integers or floating point types can be initialized by placing a comma separated list of values in curly braces {…} – int data[5] = {4,3,9,6,14}; – char vals[8] = {64,33,18,4,91,76,55,21}; – int vals[100] = {1,2,3}; • If not enough values provided, the remaining elements will be initialized to 0 • If accompanied w/ initialization list, size doesn’t have to be indicated (empty [ ]) – double stuff[] = {3.5, 14.22, 9.57}; // = stuff[3] • However the list must be of constants, not variables: – BAD: double z = 3.5; double stuff[] = {z, z, z};

  12. 12 Understanding array addressing and indexing ACCESSING DATA IN AN ARRAY

  13. 13 Exercise • Consider a train of box cars – The initial car starts at point A on the number line – Each car is 5 meters long • Write an expression of where the i-th car is located (at what meter does it start?) • Suppose a set of integers start at memory address A, write an expression for where the i-th integer starts? • Suppose a set of doubles start at memory address A, write an expression for where the i-th double starts? 0 th car 1st car 2nd car A

  14. 14 More on Accessing Elements • Assume a 5-element int array – int x[5] = {8,5,3,9,6}; 100 00 00 00 08 x[0] • When you access x[2], the CPU calculates where that 104 00 00 00 05 x[1] 108 00 00 00 03 x[2] item is in memory by taking the start address of x (i.e. 112 00 00 00 09 x[3] 100) and adding the product of the index, 2, times the 116 00 00 00 06 x[4] size of the data type (i.e. int = 4 bytes) 120 a4 34 7c f7 124 d2 19 2d 81 – x[2] => int. @ address 100 + 2*4 = 108 … – x[3] => int. @ address 100 + 3*4 = 112 Memory – x[i] @ start address of array + i * (size of array type) Compiler must be • C does not stop you from attempting to access an able to figure out how much memory to element beyond the end of the array allocate at compile- – x[6] => int. @ address 100 + 6*4 = 124 (Garbage!!) time Fun Fact 1: If you use the name of an array w/o square brackets it will evaluate to the starting address in memory of the array (i.e. address of 0 th entry) Fun Fact 2 : Fun Fact 1 usually appears as one of the first few questions on the midterm.

  15. 15 Intermediate-Level Array Topics

  16. 16 Passing arrays to other functions ARRAYS AS ARGUMENTS

  17. 17 Passing Arrays As Arguments // Function that takes an array • Syntax: int sum( int data[] , int size); 1 int sum( int data[] , int size) – Step 1 : In the prototype/signature: { int total = 0; Put empty square brackets after for(int i=0; i < size; i++){ total += data[i]; the formal parameter name if it is } return total; an array (e.g. int data[] ) } – Step 2 : When you call the int main() { int vals[100]; function, just provide the name of /* some code to initialize vals */ 2 int mysum = sum( vals , 100); the array as the actual parameter cout << mysum << endl; // prints sum of all numbers • In C/C++ using an array name return 0; without any index evaluates to the } starting address of the array

  18. 18 Pass-by-Value & Pass-by-Reference • What are the pros and cons of emailing a document by: – Attaching it to the email – Sending a link (URL) to the document on some cloud service (etc. Google Docs) • Pass-by-value is like emailing an attachment – A copy is made and sent • Pass-by-reference means emailing a link to the original – No copy is made and any modifications by the other party are seen by the originator

  19. 19 Arrays And Pass-by-Reference void dec(int); • Single (scalar) variables are int main() { int y = 3; passed-by-value in C/C++ dec( y ); cout << y << endl; return 0; – Copies are passed } void dec( int y ) { y --; } • Arrays are Single variables (aka scalars) are passed-by-value but arrays are passed-by-reference • passed-by-reference void init(int x[], int size); int main() – Links are passed { int data[10]; init( data, 10 ); – This means any change to the cout << data[9] << endl; // prints 0 return 0; array by the function is visible } void init( int x[], int size ) upon return to the caller { // x is really a link to data for(int i=0; i < size; i++){ x[i] = 0; // changing data[i] } }

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend