Array What it is. How to use it How to declare it How to initialize it.

  • Published on
    20-Dec-2015

  • View
    216

  • Download
    3

Transcript

<ul><li> Slide 1 </li> <li> Array What it is. How to use it How to declare it How to initialize it </li> <li> Slide 2 </li> <li> What is an array? Consecutive group of memory locations that all have the same name and data type grades[0] grades[1] grades[2] grades[3] grades[4] 100 85 50 65 88 name position or subscript value </li> <li> Slide 3 </li> <li> Referencing elements in an array grades[0] grades[1] grades[2] grades[3] grades[4] 100 85 50 65 88 To calculate the sum of the first 2 elements int sum = grades[0] + grades[1]; To change the value of the last element to 92 grades[4] = 92; position = subscript </li> <li> Slide 4 </li> <li> Declaring an array Must tell compiler name, size and data type int grades[5]; char letters[26], numbers[10]; #define ARRAY_SIZE 5 int grades[ARRAY_ SIZE]; const int array_size 5; int grades[array_size]; May only use constants to declare the size of an array. </li> <li> Slide 5 </li> <li> Initializing an array int counters[5]; // Initialize array for (int i = 0; i &lt; 5; i++) counters[i] = 0; Note that i goes from 0 to 4 for a 5 element array not 1 to 5. </li> <li> Slide 6 </li> <li> Initializing an array with a declaration int grades [5] = {100, 85, 50, 65, 88} or int grades [] = {100, 85, 50, 65, 88} char numbers[] = {0, 2, 3, 4, 5, 6, 7, 8, 9} int n[10] = {0} // entire array is initialized to 0 </li> <li> Slide 7 </li> <li> Common programming errors Forgetting to initialize an array Too many initializers int grades [5] = {100, 85, 50, 65, 88, 99} // error!! Forgetting that the subscript range is 0 to (size - 1) and not 0 to size. int grades[5]; grades[5] = 2; // error!! </li> <li> Slide 8 </li> <li> Exercises Answer the following questions regarding an array called fractions. 1) Define a constant variable array_size and initialize it to 10. 2) Declare an array with arraysize elements of type float and initialize the elements to 0.0. 3) Name the fourth element from the beginning of the array. 4) Assign the value 1.667 to the 9th element in the array. 5) Print all the elements of the array using a for repetition structure. </li> <li> Slide 9 </li> <li> More Exercises Find the error in the following code segments 1) int k = 4; char a1[k]; 2) int a2[5] = {1, 2, 3, 4, 5, 6} 3) int a[5]; for (int i = 0; i grades[i]; } // Display grades for (i = 0; i &lt; 5; i++) { cout </li> <li> Scalability const int array_size = 5; int grades[array_size]; // Initialize array for (int i = 0; i &lt; array_size; i++) grades[i] = 0; // Read in 5 grades. for (i = 0; i &lt; array_size; i++) { cout &gt; grades[i]; } // Display grades for (i = 0; i &lt; array_size; i++) { cout </li></ul>