Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7 Arrays 1. Concept of arrays Array and pointers

Similar presentations


Presentation on theme: "Lecture 7 Arrays 1. Concept of arrays Array and pointers"— Presentation transcript:

1 Lecture 7 Arrays 1. Concept of arrays Array and pointers
2-dimensional arrays Applications of arrays

2 1. concepts of array An array is a collection of similar data elements. These data elements have the same data type Elements of arrays are stored in consecutive memory locations Array elements are accessed by an index/subscript Arrays are declared using the following syntax: type name[max_length]; max_length - total number of array elements

3 concepts by example int a[10]; // int type, name a, length // declare a consecutive memory space of 10*4 bytes // access by a[index], index from 0 to 9, a[0], …, a[9] // smallest index 0, maximum index 9, length -1 sizeof(a) // the total number of bytes of array a, i.e., 40 sizeof(a[0]) // the number of bytes of a[0] int max_len = sizeof(a)/sizeof(a[0]); // the length of array a[2] = 10; // assign value to array element a[2] int b = a[2]; // get the value from array element 1st element a[0] 2nd element a[1] 3rd element a[2] 4th element a[3] 5th element a[4] 6th element a[5] 7th element a[6] 8th element a[7] 9th element a[8] 10th element a[9]

4 Initializing arrays int a[5];
// no initialization, the elements holds what it was there int a[5] = { 4, 1, 7, 2, 1 }; // each array element gets a value int a[5] = { 4, 1, 0 }; /* initilize first three elements, last three elements are 0 */ int a[5] = { 0}; // all elements are 0 */ int a[] ={1, 2, 3, 4, 5}; // auto declare size 5 and initialization

5 Traversal array elements
Use loop to access all the elements of an array. Commonly use for loop, the subscript must be an integral value or an expression that evaluates to an integral value. Example: int i, marks[10]; for(i=0;i<10;i++) marks[i] = -1;

6 Example Output: list[0] = 1, address = list[1] = 2, address = list[2] = 3, address = list[3] = 4, address = list[4] = 5, address = #include <stdio.h> #define SIZE 5int list[ SIZE ]; /* array of int's */ int main(){ int i; for (i=0;i < SIZE; i++ ) { list[ i ] = i + 1; printf("list[%d] = %d, address = %lu\n",i,list[i], &list[i]); } return 0;

7 Usage examples Inputting values from keyboard int i, marks[10];
for(i=0;i<10;i++) scanf(“%d”, &marks[i]); Copy value from another array int i, arr1[10], arr2[10]; for(i=0;i<10;i++) arr2[i] = arr1[i]; Input value from command line arguments int main(int argc, char *args[]) { int i, n = argc - 1; marks[n]; for(i=0;i<n;i++) marks[i] = atoi(args[i + 1]); return 0; }

8 Example: Read and Display N Numbers using Array
#include<stdio.h> int main() { int i=0, n, marks[20]; printf("\nEnter the number of elements:"); scanf("%d",&n); printf("\nEnter the elements: "); for(i=0;i<n;i++) { printf("\n marks[%d] = ", i); scanf("%d", &marks[i]); } printf("\n The array elements are "); for(i=0;i<n;i++) printf("marks[%d] = %d\t", i, marks[i]); return 0; Enter the number of elements:2 Enter the elements: marks[0] = 2 marks[1] = 4 The array elements are marks[0] = 2 marks[1] = 4

9 Passing Arrays to Functions
Passing data values main() { int arr[5] ={1, 2, 3, 4, 5}; func(arr[3]); } void func(int num) printf("%d", num); Passing addresses main() { int arr[5] ={1, 2, 3, 4, 5}; func(&arr[3]); } void func(int *num) printf("%d", *num); Passing the entire array main() { int arr[5] ={1, 2, 3, 4, 5}; func(arr); } void func(int arr[5]) int i; for(i=0;i<5;i++) printf("%d", arr[i]);

10 Example: Pass array to function
#include<stdio.h> void inc(int[]); int main( void ) { int i, x[3]; for( i = 0; i < 3; i++ ) x[i] = i; printf("Before increase\n"); for( i = 0; i < 3; i++ ) printf("x[%i] = %i\n", i, x[i] ); inc(x); // pass reference/name printf("After increase\n"); return 0; } /* main */ void inc(int a[]) { int i; for(i = 0; i < 3; i ++ ) a[i]++; } /* add */ Before increase x[0] = 0 x[1] = 1 x[2] = 2 After increase x[0] = 1 x[1] = 2 x[2] = 3

11 3. Pointers and Arrays Concept of array is very much bound to the concept of pointer. Name of an array is actually a pointer that points to the first element of the array. int *ptr, a[10]; ptr = &a[0]; If pointer variable ptr holds the address of the first element in the array, then the address of the successive elements can be calculated by writing ptr++. int *ptr = &a[0]; ptr++; printf (“The value of the second element in the array is %d”, *ptr);

12 Example The following are equivalent int *p; p = &a[0];
int a[10]; The following are equivalent int *p; p = &a[0]; int *p = &a[0]; int *p = a ; *p =  a[0] = 1 (p+1)  &a[1] (p+i)  & a[i] *(p+i)  a[i]

13 The following three are equivalent main(){ int i, a[SIZE]; for (i = 0; i < SIZE; i++) scanf("%d",&a[i]); printf("\n"); for (i = 0; i < SIZE; i++) printf("%d",a[i]); } for (i = 0; i < SIZE; i++) printf("%d", *(a+i) ); int i,*p, a[SIZE]; for (p = a; p < (a+SIZE); p++) printf("%d",*p); (1) (2) (3) (1), (2) and (3) do the same thing (1) and (2) are of the same efficiency (3) is the most efficient one, with less computation for index and addressing

14 Sort (selection) void sort(int x[], int n) { int i, j, k, t;
for (i = 0; i<n-1; i++){ k = i; for (j = i + 1; j < n; j++) if (x[j] > x[k]) k = j; if (k!=i){ t = x[i]; x[i]=x[k]; x[k] = t; // swap } void sort_pointer(int *x, int n) { if (*(x+j) > *(x+k)) k = j; t = *(x+i); *(x+i) = *(x+k); *(x+k) = t; //swap }} #include <stdio.h> Void sort(int *, int); void sort_pointer(int *, int); int main(){ int a[10] = {5, 9, 0, 8, 7, 4, 6, 3, 2, 1}; int i, *p = a; for (i = 0; i<10; i++) printf("%d ", *p++); printf("\n"); p = a; //sort(p, 10); sort_pointer(p, 10); for (p = a; p < a+10; p++) printf("%d ", *p); return 0; }

15 Arrays of Pointers An array of pointers can be declared as:
int *ptr[10]; The above statement declares an array of 10 pointers where each of the pointer points to an integer variable. int *ptr[10]; int p=1, q=2, r=3, s=4, t=5; ptr[0]=&p; ptr[1]=&q; ptr[2]=&r; ptr[3]=&s; ptr[4]=&t; printf(“\n %d”, *ptr[3]); // what it print?

16 3. Two-dimensional Arrays
A two-dimensional array is specified using two subscripts where one subscript denotes row and the other denotes column. C looks at a two-dimensional array as an array of one-dimensional arrays. A two-dimensional array is declared as data_type array_name[row_size][column_size]; First/row Dimension Second/column Dimension

17 Two-dimensional Arrays
Therefore, a two dimensional m×n array is an array that contains m×n data elements and each element is accessed using two subscripts, i and j, where 0<= i<=m and 0<= j<=n Example: int marks[3][5]; Rows/Columns Col 0 Col 1 Col2 Col 3 Col 4 Row 0 marks[0][0] marks[0][1] marks[0][2] marks[0][3] marks[0][4] Row 1 marks[1][0] marks[1][1] marks[1][2] marks[1][3] marks[1][4] Row 2 marks[2][0] marks[2][1] marks[2][2] marks[2][3] marks[2][4] Two Dimensional Array

18 Memory Representation of a 2D Array
The 2-D array is stored by row-major order in memory. In the row-major order the elements of the first row are stored before the elements of the second and third rows. That is, the elements of the array are stored row by row where n elements of the first row will occupy the first nth locations. (see demo) (0, 0) (0, 1) (0, 2) (0, 3) (1, 0) (1, 1) (1, 2) (1, 3) (2, 0) (2, 1) (2, 2) (2, 3)

19 Initializing Two-dimensional Arrays
A two-dimensional array is initialized in the same was as a single dimensional array is initialized. For example, int marks[2][3]={90, 87, 78, 68, 62, 71}; int marks[2][3]={{90,87,78},{68, 62, 71}};

20 Individual elements of the array mat can be accessed using either:
Pointers and 2D Arrays Individual elements of the array mat can be accessed using either: mat[i][j] or *(*(mat + i) + j) or*(mat[i]+j); Pointer to a one-dimensional array can be declared as: int arr[]={1,2,3,4,5}; int *parr; parr=arr; Similarly, pointer to a two-dimensional array can be declared as: int arr[2][2]={{1,2},{3,4}}; int (*parr)[2];

21 Pointers for 2-D arrays int a[2][3]; int *p; p = &a[0][0];

22 Pointers for 2-D arrays int a[row][col]; int *p = &a[0][0]; (p+i*col+j)  &a[i][j]; *(p+i*col+j)  a[i][j];

23 Passing 2D Arrays to Functions
Passing individual elements 2D Array for Inter Function Communication Passing a row Passing the entire 2D array There are three ways of passing two-dimensional arrays to a function. First, we can pass individual elements of the array. This is exactly same as we passed element of a one-dimensional array.

24 Passing 2D Arrays to Functions
Passing a row Calling function main() { int arr[2][3]= ( {1, 2, 3}, {4, 5, 6} }; func(arr[1]); } Called function void func(int arr[]) int i; for(i=0;i<3;i++) printf("%d", arr[i] * 10); Passing the entire 2D array To pass a two dimensional array to a function, we use the array name as the actual parameter. (The same we did in case of a 1D array.) However, the parameter in the called function must indicate that the array has two dimensions.

25 Example: transpose of a matrix
Pass by matrix name void transpose(int n, int m[][n]) { // need declare n first int *p = m, i = 0, j = 0, temp; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { temp = m[i][j]; m[i][j] = m[j][i]; m[j][i] = temp; } } // call int mat[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}: transpose(3, mat);

26 Example: transpose of a matrix
Pass by single pointer void transpose(int *m, int n) { int *p = m, i = 0, j = 0, temp; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { temp = *(p + i * n + j); *(p + i * n + j) = *(p + j * n + i); *(p + j * n + i) = temp; //swap(p + i * n + j, p + j * n + i); } // call int mat[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int *p = &mat[0][0]; transpose(p, 3);

27 Multi-dimensional Arrays
A multi-dimensional array is an array of arrays. Like we have one index in a single dimensional array, two indices in a two-dimensional array, in the same way we have n indices in a n-dimensional array or multi-dimensional array. Conversely, an n dimensional array is specified using n indices. An n dimensional m1 x m2 x m3 x ….. mn array is a collection of m1×m2×m3× ….. ×mn elements. In a multi-dimensional array, a particular element is specified by using n subscripts as A[I1][I2][I3]…[In], where I1<=M1 I2<=M I3 <= M3 ……… In <= Mn

28 Multi-dimensional Arrays

29 Initializing Multi-dimensional Arrays
A multi-dimensional array is declared and initialized the same way as we declare and initialize one- and two-dimensional arrays.

30 Pointers and Three-dimensional Arrays
A pointer to a three-dimensional array can be declared as: int arr[2][2][2]={1,2,3,4,5,6,7,8}; int (*parr)[2][2]; parr=arr; We can access an element of a three-dimensional array by writing: arr[i][j][k]= *(*(*(arr+i)+j)+k)

31 4. Applications of Arrays
Arrays are widely used to implement mathematical vectors, matrices and other kinds of rectangular tables. Many databases include one-dimensional arrays whose elements are records. Arrays are also used to implement other data structures like heaps, hash tables, queues, stacks and string. We will read about these data structures in the subsequent chapters. Arrays can be used for dynamic memory allocation.

32 Use array to store data elements
Use array to store a sequence of data upper_bound is the index of the last element lower_bound is the index of the first element in the array length = upper_bound – lower_bound + 1 99 67 78 56 88 90 34 85 marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[ marks[7]] Here, lower_bound = 0, upper_bound = 7 Therefore, length = 7 – = 8

33 Array Operations Traversal array Inserting an element in an array
Searching an element in an array Deleting an element from an array Merging two arrays Sorting an array in ascending or descending order

34 Array operations Searching an element key in an array, return position
for( i = lower_bound; i <= upper_bound; i++) if (key == a[i]) return i; // time complexity O(n) Inserting an element in an array (check textbook page 78) Insert at end, time complexity O(1) Insert at a given position, need shift, O(n) Deleting an element from an array (check textbook page 81) Given position, need shift

35 Array operations Merging two arrays (check textbook page 83-85)
Given arrays a1 and a2, merge a2 into a1. Sorting an array in ascending or descending order (page 84) Many sorting algorithms, e.g. selection sort, quick sort


Download ppt "Lecture 7 Arrays 1. Concept of arrays Array and pointers"

Similar presentations


Ads by Google