1 / 28

CSIS 113A

CSIS 113A. Lecture 10 Arrays. What is an array. A contiguous group of homogeneous elements Might be easier to think of it as a series of like data that can be accessed using one name ie. Grades, Scores, temperatures This our first aggregate type Combine atomic types to make a new type

shawn
Download Presentation

CSIS 113A

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. CSIS 113A Lecture 10 Arrays Glenn Stevenson CSIS 113A MSJC

  2. What is an array • A contiguous group of homogeneous elements • Might be easier to think of it as a series of like data that can be accessed using one name ie. Grades, Scores, temperatures • This our first aggregate type • Combine atomic types to make a new type • Atomic, int, float, double, etc Glenn Stevenson CSIS 113A MSJC

  3. Array Depicted Glenn Stevenson CSIS 113A MSJC

  4. Declaring Arrays • Declare the array  allocates memoryint score[5]; • Declares array of 5 integers named ‘score’ • Similar to declaring five variables:int score[0], score[1], score[2], score[3], score[4] • Individual parts called many things: • Indexed or subscripted variables • ‘Elements’ of the array • Value in brackets called index or subscript • Numbered from 0 to size - 1 Glenn Stevenson CSIS 113A MSJC

  5. Accessing Arrays • Access using index/subscript • cout << score[3]; • Note two uses of brackets: • In declaration, specifies SIZE of array • Anywhere else, specifies a subscript • Size, subscript need not be literal • int score[MAX_SCORES]; • score[n+1] = 99; • If n is 2, identical to: score[3] Glenn Stevenson CSIS 113A MSJC

  6. Access Depicted Glenn Stevenson CSIS 113A MSJC

  7. Arrays & Memory Glenn Stevenson CSIS 113A MSJC

  8. Initialize At Declaration • Just like any other variables, arrays can be initialized at declaration time. • A little trickier Glenn Stevenson CSIS 113A MSJC

  9. A simple program #include <iostream> using namespace std; int main(){double d[] = {3.44, 2.22, 1.22, 5.55, 1.89, 99.99};    for(int i = 0; i < 6; i++)      cout << d[i] << endl; } Glenn Stevenson CSIS 113A MSJC

  10. for-loops with Arrays • Natural counting loop • Naturally works well ‘counting thru’ elementsof an array • Example:for (idx = 0; idx<5; idx++){cout << score[idx] << “off by “ << max – score[idx] << endl;} • Loop control variable (idx) counts from 0 – 5 Glenn Stevenson CSIS 113A MSJC

  11. Major Array Pitfall • Array indexes always start with zero! • Zero is ‘first’ number to computerscientists • C++ will ‘let’ you go beyond range • Unpredictable results • Compiler will not detect these errors! • Up to programmer to ‘stay in range’ Glenn Stevenson CSIS 113A MSJC

  12. Major Array Pitfall Example • Indexes range from 0 to (array_size – 1) • Example:double temperature[24]; // 24 is array size// Declares array of 24 double values calledtemperature • They are indexed as:temperature[0], temperature[1] … temperature[23] • Common mistake:temperature[24] = 5; • Index 24 is ‘out of range’! • No warning, possibly disastrous results Glenn Stevenson CSIS 113A MSJC

  13. Defined Constant as Array Size • Should try to use defined/named constant forarray size • Example:const int NUMBER_OF_STUDENTS = 5;int score[NUMBER_OF_STUDENTS]; • Improves readability • Improves versatility • Improves maintainability Glenn Stevenson CSIS 113A MSJC

  14. Uses of Defined Constant • Use everywhere size of array is needed • In for-loop for traversal:for (idx = 0; idx < NUMBER_OF_STUDENTS; idx++){ // Manipulate array} • In calculations involving size:lastIndex = (NUMBER_OF_STUDENTS – 1); • When passing array to functions (later) • If size changes  requires only ONEchange in program! Glenn Stevenson CSIS 113A MSJC

  15. Filling An Array #include <iostream>#include <ctime> using namespace std; int main(){int array[20];    srand(time(0));// Fill the array!!   for(int i = 0; i < 20; i++)      array[i] = rand() % 101; // print the array   for(int i = 0; i < 20; i+=2)      cout << array[i] << "\t" << array[i+1] << endl;   return 0;} Glenn Stevenson CSIS 113A MSJC

  16. Indexed Variables as Arguments • Indexed variable handled same as simplevariable of array base type • Given this function declaration:void myFunction(double par1); • And these declarations:inti; double n, a[10]; • Can make these function calls:myFunction(i); // i is converted to doublemyFunction(a[3]); // a[3] is doublemyFunction(n); // n is double Glenn Stevenson CSIS 113A MSJC

  17. Subtlety of Indexing • Consider:myFunction(a[i]); • Value of i is determined first • It determines which indexed variable is sent myFunction(a[i*5]); • Perfectly legal, from compiler’s view • Programmer responsible for staying‘in-bounds’ of array Glenn Stevenson CSIS 113A MSJC

  18. Entire Arrays as Arguments • Formal parameter can be entire array • Argument then passed in function callis array name • Called ‘array parameter’ • Formal parameter entire array is placed void foo(int ar[]){} Int main(){int myArray[5]; foo(myArray); return 0;} Glenn Stevenson CSIS 113A MSJC

  19. Arguments To Functions • Arrays get passed to function by reference. • In actuality, it is a copy of the base address (Address of Element 0) of the array that gets passed. Glenn Stevenson CSIS 113A MSJC

  20. #include <iostream>#include <ctime> using namespace std; void fillArray(int ar[], int size);void printArray(int ar[], int size); int main(){int array[20];    fillArray(array, 20);   printArray(array, 20); return 0;}void fillArray(int ar[], int size){   srand(time(0));// Fill the array!!   for(int i = 0; i < size; i++)      ar[i] = rand() % 101; }void printArray(int ar[], int size){    for(int i = 0; i < size; i+=2)       cout << ar[i] << "\t" << ar[i+1] << endl; } Glenn Stevenson CSIS 113A MSJC

  21. Depicted Glenn Stevenson CSIS 113A MSJC

  22. Passing Array Pitfall • It is possible to write pass the end of the array • BAD things may happen • Compiler will issure NO warnings or errors • Could cause your program to crash unexpectedly • Best to see example Glenn Stevenson CSIS 113A MSJC

  23. #include <iostream>#include <ctime> using namespace std; void fillArray(int ar[], int size); int main(){int array[20];    fillArray(array);return 0;}void fillArray(int ar[]){   srand(time(0));// Fill the array!!   for(int i = 0; i < 21; i++)      ar[i] = rand() % 101; } Glenn Stevenson CSIS 113A MSJC

  24. Pass the Size • In C++ when you pass an array, you should also pass the size so the function knows how many it can act on. • Makes function generic void fillArray(int ar[], int size){} Glenn Stevenson CSIS 113A MSJC

  25. #include <iostream>#include <ctime> using namespace std; void fillArray(int ar[], int size);void printArray(int ar[], int size); int main(){int array[20];    fillArray(array, 20);   printArray(array, 20); return 0;}void fillArray(int ar[], int size){   srand(time(0));// Fill the array!!   for(int i = 0; i < size; i++)      ar[i] = rand() % 101; }void printArray(int ar[], int size){   for(int i = 0; i < size; i+=2)       cout << ar[i] << "\t" << ar[i+1] << endl; } Glenn Stevenson CSIS 113A MSJC

  26. Returning Arrays • As it stands right now arrays cannot be returned from a function • The are created on the stack and get destroyed when function returns • We will learn how to do it later on Glenn Stevenson CSIS 113A MSJC

  27. Read Only Arrays • Passing arrays can be dangerous because the function they are passed to can always modify them. • In the previous program, the printArray function only needs the ability to read the variables. • Since it is only printing the array, it shouldn't be given permission to modify it. • In these instances, you want to use the const keyword. Glenn Stevenson CSIS 113A MSJC

  28. #include <iostream>#include <ctime> using namespace std; void fillArray(int ar[], int size);void printArray(const int ar[], int size); int main(){int array[20];    fillArray(array, 20);   printArray(array, 20); return 0;}void fillArray(int ar[], int size){   srand(time(0));// Fill the array!!   for(int i = 0; i < size; i++)      ar[i] = rand() % 101; }void printArray(const int ar[], int size){   for(int i = 0; i < size; i+=2)       cout << ar[i] << "\t" << ar[i+1] << endl; } Glenn Stevenson CSIS 113A MSJC

More Related