BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18) 1
LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D) and Two Dimensional (2 D) 3. Write declaration, initialization and assignment 4. Manipulate data in arrays (operations on arrays) 5. Explore the applicability of arrays 2
WHAT IS AN ARRAY? Array of bugs An array is a derived data type. Derived data type is derived from standard data type. An array only stores a group of values of the same data type. Example: A group of integer values. Memory locations to store values in an array are called elements. Elements are stored in consecutive memory locations. 3
WHY USE ARRAY? By using an array we can store several different values of the same data type with just ONE identifier, without having to declare several different identifiers. Table below shows how the marks of 100 students, are stored in two (2) different ways. NOT using array Declaration statement 100 IDENTIFIERS: double m1, m2,, m100; Memory Layout USE RANDOM LOCATIONS.. m2 m5 m100 m1. m96 m8 m45 m12 1 IDENTIFIER: USE CONSECUTIVE LOCATIONS Using array double m[100];.. m[0] m[1] m[2] m[3]. m[96] m[97]m[98] m[99] 4 elements
HOW TO USE ARRAY? An array must be declared before it is used. Array is declared using [ ] operator. Example: int ARY[5]; double SALARY[10][12]; A specific element in an array is accessed by using the array name and a subscript (also known as index). First element in an array uses 0 as subscript. The last element in an array uses n-1 as subscript, where n is the number of elements in the array. 5
ARRAY TERMINOLOGY In this array declaration: int tests[5]; int is the data type of the array elements tests is the name of the array 5, in [5], is the size declarator, and it shows the number of elements in the array. It MUST be an integer constant > 0. The size of an array is (number of elements) * (size of each 6 element). Example: int tests[5] is an array of 20 bytes (5 elements * 4 bytes), assuming 4 bytes for an int.
SIZE DECLARATORS Named constants are commonly used as size declarators. Example: const int SIZE = 5; int tests[size]; SIZE is a named constant with value 5 This simplifies program maintenance when the size of the array needs to be changed. 7
TYPES OF ARRAY : THE MEANING OF DIMENSION Types of array: One dimensional (1-D), Two dimensional (2-D), etc. The dimension of an array is the number of subscripts needed to select an element. A user can view a one-dimensional array as a list of data, a twodimensional array as a rectangle of data, a three-dimensional array as a block of data, etc. 8
THE DIMENSIONS OF ARRAY : A USER S VIEW 1-D array: with 10 elements. 2-D array: with 20 elements (4 x 5) 3-D array with: 24 elements(2x3x4) 3-Dimensional 9
1-D ARRAY : DECLARATION AND MEMORY LAYOUT Declaration Syntax: data_type array_name[size]; (Note: size declarator - is an integer constant > 0 ) Example: int ARY[5]; ARY is the name of an array that consists of FIVE elements. ARY elements will be placed one after another in the memory as follows. ARY first element second element third element fourth element fifth element 10
ARY 1-D ARRAY : MEMORY LAYOUT SUBSCRIPT [0] [1] [2] [3] [4]????? first element second element third element fourth element fifth element 1-D array needs ONE subscript to select an element from the array. The above elements (memory locations) of array ARY will be accessed (selected) individually as follows: ARY[0], ARY[1], ARY[2], ARY[3], ARY[4] first element second element third element fourth element fifth element 11
12 1-D ARRAY : DECLARATION AND MEMORY LAYOUT
1 D ARRAY DECLARATION IN C++ PROGRAM : EXAMPLES #include <iostream> a) #define SIZE 20 b) using namespace std; int main() { int Marks[SIZE]; char Names[20]; } other C++ statements : #include <iostream> using namespace std; const int SIZE = 20; int main() { int Marks[SIZE]; char Names[20]; } other C++ statements : 13 * SIZE : is a size declarator; it must be a constant. ** It is advisable to use named constant as size declarator. This makes program maintenance easier when the size of the array needs to be changed.
BASIC OPERATIONS ON ARRAY Some basic operations performed on arrays are: Initializing elements of array Input data to an array Output data stored in an array Finding the largest and/or smallest element Computations on elements of array Each operation requires ability to step through the elements of the array. Easily accomplished by a for loop. 14 14
1 D ARRAY INITIALIZATION Initial values are given to the array elements during array declaration. They are enclosed within braces and separated by commas. Examples on array initialization: char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; bool anskey[] ={true, true, false, true, false, false}; char word[] = "Hello"; vowels 'a' 'e' 'i' 'o' 'u' anskey true true false true false false word 'H' 'e' 'l' 'l' 'o' '\0' 15
1 D ARRAY INITIALIZATION int scores[9] = {23,45,12,67,95,45,56,34,83}; 16
17 17 1 D ARRAY INITIALIZATION : SOME VARIATIONS
1-D ARRAY : ACCESSING ARRAY ELEMENTS Subscripts are used to access individual elements of an array. General format to access an array element: array_name[subscript] Example: const int size = 5; double number[size]; for (int i=0; i<=4; ++i) number[i] = i + 0.5; From the above statements, each element of the array is accessed and assigned with a value as follows : 18 number 0.5 1.5 2.5 3.5 4.5
1-D ARRAY : ACCESSING ARRAY ELEMENTS Array elements can be accessed and used as regular variables, such as the following: numbers[0] = 79.5; cout << numbers[0]; cin >> numbers[1]; numbers[4] = numbers[0] + numbers[1]; Arrays must be accessed via individual elements: cout << numbers; // not legal We can copy an array to another array with the same size and type but it is not legal to assign one array to another as shown below : Example: 19 int num1[5]={1,2,3,4,5}; int num2[5]; num2 = num1; //error
CONT ASSIGNING VALUES TO 1-D ARRAY Example : to copy elements of array num1 into array num2. int num1[5] = {1,2,3,4,5}, num2[5]; for(int i =0 ; i<5; i++) { num2[i]= num1[i]; //correct } 20
MORE EXAMPLES : ASSIGNING VALUES TO 1-D ARRAY int num[5]; int list[10]; 21
INPUT DATA TO 1-D ARRAY Beside Assignment or Initialization, another way to fill the array is by inputting values (read) Can be done using a loop the most appropriate is the for loop. int scores[9]; cout<< Input 10 integers:\n ; for (i=0;i<9;i++) { cin >> scores[i]; } Output: Input 10 integers: 23 45 12 67 95 45 56 34 83 22 22 Ten values given as input
DISPLAY DATA STORED IN 1-D ARRAY for (i=0; i<9; i++) { cout <<scores[i]<< \n ; } Output: 23 23 23 45 12 67 95 45 56 34 83
EXAMPLE OF 1-D ARRAY FLOWCHART int main() { for ( int i = 0; i < 20; i++) cin >> numbers[i]; for ( int i = 0; i < 20; i++) cout << numbers[i]; 24 }
#include <iostream> #include <iomanip> using namespace std; EXAMPLE : INPUT AND OUTPUT OF 1-D ARRAY int main() { int i, a[5]={2,4,6,8,10}, b[5], c[5]; cout<< Enter 5 numbers:\n ; for(i=0; i<5; i++) cin >> b[i]; cout<< setw(15)<< ary1 << setw(10) << ary2 << setw(10) << ary3 << endl; 25 } for(i=0; i<5; i++) { c[i]= a[i] + b[i]; cout<< setw(15) << a[i] << setw(10) << b[i] << setw(10) << c[i] <<endl; } return 0; 25
Output : Enter 5 numbers: 1 2 3 4 5 ary1 ary2 ary3 2 1 3 4 2 6 6 3 9 8 4 12 10 5 15 26 26
EXAMPLE : DETERMINE THE MINIMUM VALUE #include <iostream> using namespace std; void main() { int i, score[5], min; } 27 cout<< Enter 5 scores:\n ; for(i=0; i<5; i++) cin >> score[i]; min = score[0]; Output : for(i=1; i<5; i++) { if(score[i] < min ) min = score[i]; } cout<< The lowest score is << min; Enter 5 scores: 85 60 55 78 95 The lowest score is 55 27
OPERATIONS ON ARRAY : MORE EXAMPLES 28
EXCHANGING VALUES IN 1-D ARRAY : THE INCORRECT WAY Problem: To exchange the values between numbers [1] and numbers [3]. What happens if these TWO statements are used? 29 29 RESULT Problem NOT Solved.
EXCHANGING VALUES IN 1-D ARRAY : THE CORRECT WAY - USING TEMPORARY VARIABLE Problem: To exchange the values between numbers [1] and numbers [3]. What happens if these THREE statements are used? 30 30 RESULT Problem Solved.
#include <iostream> using namespace std; PROGRAM TO EXCHANGING VALUES (THE CORRECT WAY) int main() { int temp; int numbers[5] = {3,7,12,24,45}; cout << "Before exchange the value :"<< endl; for(int i=0; i<5; i++) cout << numbers[i] << ' '; cout<<"\nafter exchange the value :"<<endl; for(int i=0; i<5; i++) cout << numbers[i] << ' '; 31 } cout << endl; return 0; 31
TWO-DIMENSIONAL ARRAYS A two dimensional array stores a fixed number of data as a collection of rows and columns. Sometimes called matrices or tables. Each element of a two-dimensional array has a row position and a column position. The declaration of a two-dimensional array requires a row size and a column size. Declaration syntax: data_type array_name[row_size][column_size]; 32 32 o where row_size and column_size are expressions with positive integer values, and specify the number of rows and the number of columns, respectively, in the array. o Note :number of elements in the array = row_size X column_size
DECLARATION OF 2-D ARRAY & LAYOUT First dimension specifies the number of rows in the array Second dimension specifies the number of columns in each row A consecutive block of 50 (row size X column size) consecutive memory locations are allocated. 33 33
34 34 2-D ARRAY : DECLARATION AND LAYOUT The statement int table [5][4]; means array table is a twodimensional array with 20 elements (5 rows and 4 columns). The diagram shows the user s view of array table. R O W S U B S C R I P T [0] [1] [2] [3] [4] 1st element COLUMN SUBSCRIPT [0] [1] [2] [3] Array_name 4th element 8th element 12th element 16th element 20th element
MEMORY & USER S LAYOUT OF 2-D ARRAY Question: What is the row size and column size for the array with the following layout? 35 35
EXAMPLE: DECLARATION OF 2-D ARRAY AND LAYOUT int data[2][3]; row column [ 0 ] [ 1 ] [ 0 ] [ 1 ] [ 2 ]?????? data 36
2-D ARRAY: DECLARATION AND INITIALIZATION Two-dimensional arrays can be initialized when they are declared: Example: 37 37 2-D array initialization values are enclosed within braces and separated by commas. Elements of each row could be enclosed within another braces and separated by commas. For a 2-D array, if elements of a row are not specified, unspecified ones are set to 0.
2-D ARRAY: DECLARATION WITH INITIALIZATION double t[2][2] = { {0.1,0.2}, {1.1, 1.2} }; [ 0 ] [ 1 ] [ 0 ] [ 1 ] 0.1 0.2 1.1 1.2 t 38 38
2-D ARRAY: DECLARATION WITH INITIALIZATION Initialization : Some variations int table [5][4] = {0,1,2,3,10,11,12,13,20,21,22,23,30,31,32, 31,40,41,42,43}; int table [5][4] = {{0,1,2,3},{10,11,12,13},{20,21,22,23}, {30,31,32,31},{40,41,42,43}}; int table [5][4] = {{0,1},{10},{20,21,22},{30},{40,41,42,43}}; 39 39
2-D ARRAY : ACCESSING ARRAY ELEMENTS The name of the array holds the address of the first element of the array. 2-D array needs TWO subscripts to select an element from it.to access (select) an element in a two-dimensional array, you must specify the name of the array followed by: a row subscript, and a column subscript General format to access a 2-D array element: array_name[row_subscript][column_subscript] Nested for loops are often used when accessing elements of 40 a two-dimensional array. 40
EXAMPLE : ASSIGNING VALUE TO ARRAY ELEMENT. 41
EXAMPLE : ASSIGNING VALUE TO ARRAY ELEMENTS. Let us assume that we want to assign our 5 x 4 array as shown below. 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 The following code will perform the assignment : int table[5][4]; for(int r = 0;r < 5;r++) for(int c = 0;c < 4;c++) table[r][c]= r * 10 + c ; 42 42
EXAMPLE : ASSIGNING VALUE TO ARRAY ELEMENTS. To assign the fifth row to 0: To assign the entire array to 0: 43 43
EXAMPLE : ASSIGNING VALUE TO ARRAY ELEMENTS. int v[rsize][csize]; for (int i=0; i<rsize; ++i) //every row for (int j=0; j<csize; ++j )//every col v[i][j] = i+j; [ 1 ] [ 2 ] [ 0 ] [ 1 ] [ 2 ] 0 1 1 2 2 3 44 44 V
EXAMPLE : INPUT DATA VALUES TO 2-D ARRAY ELEMENTS. double table[rsize][csize]; for (int i=0; i<rsize; ++i) //every row for (int j=0; j<csize; ++j )//every col cin >> table[i][j]; for(int r=0;r<5;r++) for(int c=0;c<4;c++) cin >> table[r][c]; 45 45
COMPUTATION AND OUTPUT The for statement is useful when performing computations on arrays. The counter variable of the for statement can be used as an array subscript. Computations can be easily performed on an entire two-dimensional array, or on a sub set of the array. 46 46
COMPUTATIONS Compute the average of an array with n rows and m columns. for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { sum += array[i][j]; } } average = sum/(n*m); 47 47
COMPUTATIONS Compute the average of the nth row of a twodimensional array with r rows and c columns. for(int col=0; col < c; ++col) { sum += array[n][col]; } rowaverage = sum/c; 48 48
OUTPUT Two dimensional arrays are often printed in a row by row format, using nested for statements. When printing the row values of an array, be sure to print: whitespace (blank space) between the values in a row. a newline character at the end of each row. 49 49
DISPLAYING DATA VALUE OF ARRAY ELEMENTS. int table [5][4] = {{0,1,2,3},{10,11,12,13},{20,21,22,23}, {30,31,32,31},{40,41,42,43}}; for(int r=0;r<5;r++) { for(int c=0;c<4;c++) cout << table[r][c] << ; cout << endl; } 50 50
#include <iostream> #include <iomanip> using namespace std; EXAMPLE: TWO DIMENSIONAL ARRAY int main() { int i,j, a[4][3]; for(i = 0; i < 4; i++) { cout << "Enter 3 numbers for row " << i+1 << " : "; for(j = 0; j < 3; j++) cin >> a[i][j]; cout << endl; } cout<<"elements of array are : "<<endl; 51 } for(i = 0; i < 4; i++) { for(j = 0; j < 3; j++) cout << setw(5) << a[i][j] ; cout << endl; } return 0; 51
EXERCISES 1) Find the output of the following codes: int row = 3; int col = 3; int mark[row][col] = {{1,2,3}, {4,5,6}, {7,8,9}}; cout<<mark[1][1]<<endl; cout<<mark[2][1]<<endl; cout<<mark[3][3]<<endl; 5252 52 52
2) Find the output of these codes: 53 #define ROW 3 #define COL 3 int main() { int i, j; int xyz[row][col] = {{1,2,3}, {4,5,6},{7,8,9}}; for (i = 0; i < ROW; i++) for (j = 0; j < COL; j++) cout << xyz[i][j]<<endl; return 0; } // end main
3) Problem : Write a program to enter five numbers. The program then displays the numbers in the reverse order of entry. This means that the last number will be displayed first, followed by the fourth, and so on. Use array in your program. - END - 54