{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# Lec2 - Lecture 2 Arrays Vectors Pointers PIC 10B Todd...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 2: PIC 10B Todd Wittman Ch. 9 : Arrays b An array is a list of the same data type. The size of an array is fixed. Declare an array with [ ] after the variable name. const int size = 10; //Must be const! string droids[size]; b We access an individual element of array a with a[i]. Remember arrays start at position 0. for (int i=0; i < size; i++) droids[i] = "R2D2"; b We can create 2D arrays to store data in rows and columns. int randoms[10][5]; //10 rows x 5 columns for (int i=0; i < 10; i++) for (int j=0; j < 5; j++) randoms[i][j] = 1+rand()%100; b What does the code above do?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Arrays in Functions b In the function parameters, denote a parameter as an array with blank brackets [ ]. b Generally have to pass the size of the array as a parameter also. void printArray (string names[ ], int size) { for (int i=0; i < size; i++) cout << names[i] << "\n"; return; } b The call to a function just passes the array name. string heroes[4] = {"Luke", "Leia", "Han", "Chewbacca"}; printArray (heroes,4); b Arrays are always passed by reference, so don't bother with an &. This is done to save memory by preventing local copies of the array variables. 2D Arrays b To pass a 2D array, need to specify the dimensions. Best to declare dimensions as global constants. const int table_rows = 20; const int table_cols = 40; void printTable (double table [table_rows] [table_cols]) { for (int i = 0; i < table_rows; i++) { for (int j=0; j < table_cols; j++) { cout << setw(10) << table [i] [j]; } cout << "\n"; } return; } Call this function in main (or wherever) with: printTable (table);
3 Ch. 9 : Vectors b Arrays are limited because they can't change size. b Unless you want a 2D array, I would suggest using a vector . It's more flexible and has some nice member functions. b To use vectors, need library: #include <vector> b The basic form of a vector declaration is: vector<data_type> variable_name (size); b For example: vector<string> heroes(4); //Not [] b We can still access the element in position i of vector v with v[i]. heroes[3] = "Chewbacca";

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 9

Lec2 - Lecture 2 Arrays Vectors Pointers PIC 10B Todd...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online