Lecture 7 Arrays 1. Concept of arrays Array and pointers

Slides:



Advertisements
Similar presentations
Chapter 7: Arrays In this chapter, you will learn about
Advertisements

Programming and Data Structure
Main Index Contents 11 Main Index Contents Pointer Illustration Pointer Illustration Vertical / Horizontal View. Vertical / Horizontal View. Data Addresses.
Chapter 9: Arrays and Strings
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction of Arrays. Arrays Array form an important part of almost all programming language. It provides a powerful feature and can be used as such.
Chapter 8 Arrays and Strings
Array.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Chapter 8 Arrays and Strings
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
Arrays- Part 2 Spring 2013Programming and Data Structure1.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Arrays as Function Arguments Array can be used as a function argument. E.g., #include int sum(int b[], int n) { int i, res; res = 0; for(i = 0; i < n;
© Oxford University Press All rights reserved. CHAPTER 7 POINTERS.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
Arrays. Arrays are objects that help us organize large amounts of information.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
1 2-d Arrays. 2 Two Dimensional Arrays We have seen that an array variable can store a list of values Many applications require us to store a table of.
MAHENDRAN. Session Objectives Explain Declaration,Initialization of Array Explain Types of Array One Dimensional,Two Dimensional and Multi Dimensional.
Arrays in C. What is Array? The variables we have used so far can store a single value. Array is a new type of variable capable of storing many values.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
Arrays Chapter 7.
Department of Computer Science Western Michigan University
Lecture 5 Pointers 1. Variable, memory location, address, value
Pointers verses Variables
EGR 2261 Unit 10 Two-dimensional Arrays
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Lectures linked lists Chapter 6 of textbook
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
CHP-2 ARRAYS.
Hassan Khosravi / Geoffrey Tien
Today’s Material Arrays Definition Declaration Initialization
Array 9/8/2018.
Visit for more Learning Resources
INC 161 , CPE 100 Computer Programming
Hassan Khosravi / Geoffrey Tien
Module 2 Arrays and strings – example programs.
14th September IIT Kanpur
Buy book Online -
C Passing arrays to a Function
Pointers and Arrays S.Bhuvaneshwari Assistant Professor/CSE
Lecture 10 Arrays.
CS111 Computer Programming
Review of Arrays and Pointers
(Numerical Arrays of Multiple Dimensions)
2-d Arrays.
Data Structures (CS212D) Week # 2: Arrays.
Multidimensional array
Arrays Week 2.
By Yogesh Neopaney Assistant Professor Department of Computer Science
C++ Array 1.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Arrays.
Presentation transcript:

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

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

concepts by example int a[10]; // int type, name a, length 10 // 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]

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

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;

Example Output: list[0] = 1, address = 4214888 list[1] = 2, address = 4214892 list[2] = 3, address = 4214896 list[3] = 4, address = 4214900 list[4] = 5, address = 4214904 #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;

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; }

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

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]);

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

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);

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 = 1  a[0] = 1 (p+1)  &a[1] (p+i)  & a[i] *(p+i)  a[i]

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

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; }

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?

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

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

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)

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}};

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];

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

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];

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.

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.

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);

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);

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<=M2 I3 <= M3 ……… In <= Mn

Multi-dimensional Arrays

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.

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)

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.

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[6 marks[7]] Here, lower_bound = 0, upper_bound = 7 Therefore, length = 7 – 0 + 1 = 8

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

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

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