150 likes | 337 Views
Structured data type: array. CHAPTER: 12. Introducing Arrays. Array is a collection of variables of the same data type that are referenced by a common name. . An Array of 10 Elements of type double. NEED FOR ARRAYS. Problem: How to store numerous values of same data type.
E N D
Structured data type: array CHAPTER: 12
Introducing Arrays Array is a collection of variables of the same data type that are referenced by a common name. An Array of 10 Elementsof type double
NEED FOR ARRAYS • Problem: • How to store numerous values of same data type. • E.g. store 100 numbers and find max. of those. • Can we store like: • int a, b, c, d, e……. z, A, B, C ……. Z, aa, ab, ac…. az, Aa, Ab, Ac…. Av; • Solution: • int a[100]; // an array
Types of Arrays • Single Dimensional Arrays • Multi Dimensional Arrays
Declaring Array Variables • Form: datatype arrayname[arraySize]; • Example: double myList[10]; • Each element in the array is referred to by an index. myList[0]references the first element in the array. myList[9]references the last element in the array.
The Length of Arrays • Once an array is created, its size is fixed. It cannot be changed. You can find its size using sizeof(arrayName); For example, sizeof(myList) returns 10
Initializing Arrays • Using a loop: for (int i = 0; i < sizeof(myList); i++) myList[i] = i; // cin>>myList[i]; • Declaring, creating, initializing in one step: double myList[] = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.
Declaring, creating, initializing Using the Shorthand Notation double myList[] = {1.9, 2.9, 3.4, 3.5}; This shorthand notation is equivalent to the following statements: double myList[4]; myList[0] = 1.9; myList[1] = 2.9; myList[2] = 3.4; myList[3] = 3.5;
CAUTION Using the shorthand notation, you have to declare, create, and initialize the array all in one statement. Splitting it would cause a syntax error. For example, the following is wrong: double myList[]; myList = {1.9, 2.9, 3.4, 3.5};
Memory Representation of 1-D Arrays • Example: double myList[10];
Printing Arrays Arrays are easily printed using for loops. However, formatting the output may require some thought. Determine the output in each case shown below. Example 1: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int j = 0; j < 12; j++) cout << Grades[ j ] << endl; Example 2: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int j = 0; j < 12; j+=3) cout << Grades[ j ] << Grades[j+1] << Grades[j+2] << endl;
Example 3: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int Row = 0; Row <= 2; Row++) for (int Col = 0; Col <=3; Col++) cout << Grades[ 4*Row+Col ] << endl; Example 4: int Grades[12]={78,80,82,84,86,88,90,92,94,96,98,100}; for (int Row = 0; Row <= 2; Row++) { for (int Col = 0; Col <=3; Col++) cout << Grades[ 4*Row+Col ]; cout << endl; }
Home Assignment Write a program to accept a list of numbers (e.g. 10 numbers) from user and search for a specific number given by user.