Download presentation
Presentation is loading. Please wait.
1
CS149D Elements of Computer Science
Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture 22: 11/14/2002 Lecture 22: 11/14/2002 CS149D Fall 2002
2
Outline Arrays (section 5.1) Declaration and initialization
Accessing array elements Arrays and data files Lecture 22: 11/14/2002 CS149D Fall 2002
3
Arrays 1 variable can store 1 data value.
How about if we want to deal with 100 integers or 100 doubles (100 measurements) at the same time? Declare 100 variables (How about 1000?) One Solution We use an array to store a number of elements of the same data type A one-dimensional array is a number of successive memory locations, each of which can store an item of data of the same type and which are all referenced through the same variable name. Example a values array How many array elements (array size)? First element is values[0] Last element is values[5] values[0] values[1] values[2] values[3] values[4] values[5] Lecture 22: 11/14/2002 CS149D Fall 2002
4
Arrays Declaration and Initialization
Syntax to declare an array Data Type Array_Name [Array Size]; int values[6]; array index ranges from 0 to 5 (6-1) double elements[5]; array index ranges from 0 to ? Can initialize array when defined int values[6] = {0,1,2,3,4,5}; values[0] values[1] values[2] values[3] values[4] values[5] Initialization sequence shorter than array size int values[6] = {0}; values[0] values[1] values[2] values[3] values[4] values[5] values[0] values[1] values[2] values[3] No size, but an initialization sequence int values[] = {0,1,2,3}; Lecture 22: 11/14/2002 CS149D Fall 2002
5
Accessing Array elements1/2
Fill an array with numbers 0,2,4,6,8,10,12 (0*2, 1*2,3*2, …) //define array const int SIZE = 7; // Why did we choose SIZE as 7? int values[SIZE]; //assign values to array elements for (int k = 0; k < SIZE ; k++) values[k] = k *2; //print array for (int k = 0 ; k < SIZE ; k++) cout << values[k] << “\t”; Lecture 22: 11/14/2002 CS149D Fall 2002
6
Accessing Array elements2/2
Printing an array in reverse order for (int k = SIZE - 1 ; k >= 0 ; k--) cout << values[k] << “\t”; No check is performed that array index lies within the bounds of the array! int values[5]; // index bounds from 0 to 4 cout << values[5]; //What happens in this case? Reading from a file and assigning to array elements A file with 2 fields per line (id grade) id is an int and grade is a float const int SIZE = 20; int id[20]; float grade[20]; fstream gradesf; gradesf.open(“GradesFile”,ios::in); for (k=0 ; k < SIZE; k++) gradesf >> id[k] >> grade[k]; Lecture 22: 11/14/2002 CS149D Fall 2002
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.