Array.

Slides:



Advertisements
Similar presentations
One Dimensional Arrays
Advertisements

Programming and Data Structure
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Dr. Sajib Datta  We can also have arrays of arrays, also known as multidimensional arrays.  E.g., A two-dimensional array is an array of several.
Lecture - 1 on Data Structures. Prepared by, Jesmin Akhter, Lecturer, IIT,JU Data Type and Data Structure Data type Set of possible values for variables.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
C++ for Engineers and Scientists Third Edition
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
ARRAYS, RECORDS AND POINTER
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 9: Advanced Array Concepts
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
A First Book of ANSI C Fourth Edition
Computer programming Lecture 5. Lecture 5: Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character arrays.
Lecture 4. RAM Model, Space and Time Complexity
Chapter 7 One-Dimensional Arrays 7.1 Arrays in C One of the more useful features of C is the ability to create arrays for storing a collection of related.
Chapter 2 ARRAYS.
Arrays.
Data Strcutures.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Data Structure Introduction.
Lecture -3 on Data structures Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Array Data structures are classified as either linear or nonlinear.
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.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 3.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
Structured Programming Approach Module VIII - Additional C Data Types Arrays Prof: Muhammed Salman Shamsi.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
CCSA 221 Programming in C CHAPTER 7 WORKING WITH ARRAYS 1.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
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.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Data Structure and Algorithms
INTRODUCTION OF ARRAY. Topics To Be Discussed………………………. Introduction Types of array One Dimensional Array Internal representation of one-dimensional array.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Dr. Sajib Datta Feb 11,  Example of declaring and initializing an array. ◦ double someData[3]; /* declare the array someData that will.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1. Traversing a linear array Here A is a linear array with lower bound LB and upper bound UB. This algorithm traverses A applying an operation PROCESS.
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.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Dr. Sajib Datta Sep 10,  #include  void main()  {  int a = 25;  int b = 0;  int c = -35;  if( a || b ) ◦ printf("Test1\n");  else.
1-d Arrays.
Data Structures I (CPCS-204)
Lecture 7 Arrays 1. Concept of arrays Array and pointers
CHP-2 ARRAYS.
Operation performed by Linear Structure
Program to search an element of array using linear search.
Arrays.
Array 9/8/2018.
Review of Arrays and Pointers
Chapter 7 Arrays PROGRAMMING IN ANSI C.
ARRAYS, RECORDS AND POINTER
Data Structures (CS212D) Week # 2: Arrays.
Arrays Week 2.
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

Array

Primitive \ Fundamental DATA STRUCTURE D S Primitive \ Fundamental Non - Primitive char int float double Linear Non - Linear Array Stack Queue Link List Tree Graph

Linear Array An array is a list of a finite number n of homogenous data elements. Elements of array are referenced by an index set that consist of n consecutive numbers. Elements of array are stored in successive memory locations. N is the length or size of the array. Length = UB – LB + 1 where UB – Upper Bound LB – Lower Bound

Linear Array Representation of elements of an array A can be as follows: Subscript Notations: A1 , A2 , A3 , ……… , An Parenthesis Notation: A(1), A(2), A(3), …… , A(n) [ Used in FORTAN, PL\1 & BASIC) Bracket Notation: A[1], A[2], A[3],….. , A[n] Generally subscript & bracket notations are used. k in A[k] is subscript or an index & A[k] is subscripted variable.

Linear Array… The elements of array are stored in successive memory cells. The computer need not to keep track of the address of every element but keeps the track of the address of the first element of the array. Denoted : Base (A) By using this address Base(A), computer calculates the address of any element of A .

Linear Array…. Formula for calculating address is : Loc (A[k]) = Base (A) + w (k – lower bound) or = Base (A) + w * k where: w – no. of words per memory cell for the array. Loc(A[k]) – Address of the element A[k] of the array. Base(A) - Base address of A.

Declaration of Linear Array Syntax : <Data type> <Array name> [size]; Where: Array name – denotes the name of the array & can be any valid C identifier. Data type – data type of the element of array. size - specifies the no. of elements that can be stored in the array. It can be a positive integer constant or constant integer expression.

Declaration of Linear Array… Examples : int age[10]; float sale[10]; Char grade[10]; When the array is declared, the compiler allocates space in memory sufficient to hold all the elements of the array, so the size of the array should be known at the compile time.

Declaration of Linear Array… The symbolic constant can be used to specify the size of the array. Example: # define SIZE 10 main() int size 15; float sale[SIZE]; int marks[size]; The use of symbolic constant to specify the size of array makes it convenient to modify the prig. If the size has to be changed only at one place, i.e. #define directive

Accessing Linear Array Element The elements of an array can be accessed by specifying the array name followed by subscript in brackets. In C the array subscript starts from 0. The last valid subscript is one less than the size of the array i.e. n-1 The subscript can be any expression that yields an integer value like integer constant, integer variable, integer expression or return value (int) from a function call.

Accessing Linear Array Element… Example : If a & b are two arrays of size 5, 10 int a[5]; float b[10]; int I; scanf (“%d”, & a[1]); printf (“%f”, b[3]); a[4] = 20; a[4]++; b[5]+ = 400; sum = a[0] + a[1] + a[2] + a[3] + a[4]; i = 2; scanf (“%f”, & a[i]); printf (“%f”, b[i]); printf (“%f”, b[i++]);

Processing Linear Array For processing arrays generally we use a for loop 7 the loop variable is used at the place of subscript. The initial value of loop variable is taken as ‘0’ as array The loop variable is increased by 1 each time so that we can access & process the next element in the array. The total no. of passes in the loop will be equal to the no. of elements in the array & in each pass we will process 1 element.

Processing Linear Array… Reading values in a: for (i = 0; i<10; i++) scanf(“%d”, &a[i]); Displaying values of a: for (i=0; i<10; i++) printf(“%d”, a[i]); Adding all the elements of a: sum = 0; sum + a[i];

Processing Linear Array… WAP to input values into an array & display them. main( ) { int a[5], i; for (i=0; i<5; i++) printf (“Enter the value for a[%d] : “, i); scanf (“%d”, & a[i]); } printf (“The array elements are : \n”); printf (“%d\t”, a[i]); printf(“\n”) ;

Initialization of Linear Array After declaration, the elements of a local array have garbage value while the elements of global & static array are automatically initially to 0. Syntax : <data_type> <array_name> [size] = { value1, value2,….., valueN); Example: int marks [5] = { 50,85,70,65,95}; We can’t copy all the elements of an array to another array by simply assigning it to the other array. Example: int a[5] = {1,2,3,4,}; int b[5]; b = a; /*not valid/ But we have to copy all the elements of array 1 by 1 by using for loop : for(i=0; i<5; i++) b[i] = a[i];

Initialization of Linear Array… Program to find the largest & smallest no. in an array. main() { int i , a[10] = {2,5,4,1,8,9,11,6,3,7}; int small, int large; for (i=1; i<10; i++) if(a[i] < small) small = a[i]; if(a[i] > large) large = a[i]; } printf(“Smallest = %d, Largest = %d\n”, small,large);

Initialization of Linear Array… Program to reverse the elements of an array. main() { int i, j, temp,a[10] = {1,2,3,4,5,6,7,8,9,10}; for (i =0 ; j = 9; i< j ; i++, j-- ) temp = a[i]; a[i] = a[j]; a[j] = temp; } printf(“After reversing, the array is : “); for ( i = 0; i< 10; i++) printf(“%d “, a[i]); printf(“\n”);

Operations on Linear Arrays Traversal Operation Search Operation Insert Operation Delete Operation Sort Operation Merge Operation

Operations on Linear Arrays… Traversing is the process of visiting each element of the array exactly once. Elements of Linear Array can be accessed directly but we have to vary index from lower bound to upper bound in steps of one to access individual elements in order. For an array of size n, for loop executes n times & thus traversal operation on array will be O(n) operation

Operations on Linear Arrays… Program for traversing the elements of given array. main( ) { int i , int a[10], ; printf (“ Enter the elements of the array which you want to traverse”); for ( i = 0; i < 10 ; i++) scanf (“%d”, & a[i]); } printf (“the traverse array is”); for (i = 0; i<10; i++) printf (“%d\n”, a[i]);

Operations on Linear Arrays… Searching is the process of finding the location of given element in the array. There are 2 approaches to search operation: Linear search: If the elements are in random order, then Linear search technique is used. In worst case O(n) operations Binary search : If the array elements are in sorted order, then it’s preferable to use Binary search. The complexity of binary search in O(log2n).

Program to find the element in the given array. #include<stdio.h>   main() { int array[100], search, c, number; printf("Enter the number of elements in array\n"); scanf("%d",&number); printf("Enter %d numbers\n", number); for ( c = 0 ; c < number ; c++ ) scanf("%d",&array[c]); printf("Enter the number to search\n"); scanf("%d",&search);

for ( c = 0 ; c < number ; c++ ) { if ( array[c] == search ) / for ( c = 0 ; c < number ; c++ ) { if ( array[c] == search ) /* if required element found */ printf("%d is present at location %d.\n", search, c+1); break; } if ( c == number ) printf("%d is not present in array.\n", search); return 0;

Program to find the element in the sorted array. #include<stdio.h>   main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); printf("Enter value to find\n"); scanf("%d",&search); first = 0;

last = n - 1; middle = (first+last)/2; while( first <= last ) { if ( array[middle] < search ) first = middle + 1; else if ( array[middle] == search ) printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; if ( first > last ) printf("%d is not present in the list.\n", search); return 0;

Operations on Linear Arrays… Insertion refers to the operation of adding an element to existing list of elements. After insertion the size of the array is increased by factor of 1. Insertion is possible only if the memory space allocated is large enough to accommodate the additional element. The complexity of insertion operation is O(n).

Operations on Linear Arrays… Program to insert an element at position k. main( ) { int *n , int item, int k, int k, int a[10] , int j; j = *n – 1; while ( j >= k){ a[j+1] = a[j]; j--; } a[k] = item; (*n)++;

Program to insert an element at position k in the sorted array Program to insert an element at position k in the sorted array. #include<stdio.h> main() { int array[100], position, c, n, value; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); printf("Enter the location where you wish to insert an element\n"); scanf("%d", &position); printf("Enter the value to insert\n"); scanf("%d", &value);

for ( c = n - 1 ; c >= position - 1 ; c-- ) array[c+1] = array[c]; array[position-1] = value; printf("Resultant array is\n"); for( c = 0 ; c <= n ; c++ ) printf("%d\n", array[c]); return 0; }

Operations on Linear Arrays… Sorting is the process of arranging the elements of the array in some logical order. This logical order can be ascending or descending incase of numeric values or dictionary order in case of alphanumeric value. One of the popular technique is Bubble sort The complexity of bubble sort is O(n2).

Program to sort the array ascending order. #include<stdio.h>   main() { int array[100], n, c, d, swap; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); for ( c = 0 ; c < ( n - 1 ) ; c++ ) for ( d = 0 ; d < n - c - 1 ; d++ )

if ( array[d] > array[d+1] ) { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0;

Operations on Linear Arrays… Merging is the process of combining the elements of 2 similar arrays into a single array. One approach is to join them end to end & then sort the combined array, but this approach is not efficient & economical. Best approach is to compare the elements of the given array & based on this comparison , decide which element should come first in the third array. The merging algorithm runs in linear time.

Program two merge 2 arrays into one array. void merging ( int*a, int m, int *b, int n, int *c) { int na, nb, nc; na = nb = nc = 0; while ( ( na < m) && (nb < n)) if (a[na] < b[nb]) c[nc] = a[na++]; else c[nc] = a[nb++]; nc++; } if (na = = m) /* list ‘a’ is exhausted*/ while (nb < n) c[nc++] = b[nb++]; else if ( nb == n) /* list b is exhausted*/ while (na < m ) c[nc++] = a[na++];

Array Applications Given a list of test scores, determine the maximum and minimum scores. Read in a list of student names and rearrange them in alphabetical order (sorting). Given the height measurements of students in a class, output the names of those students who are taller than average.

Limitations of Linear Arrays The prior knowledge of number of elements in the linear array is necessary. These are static structures. Static in the sense that whether memory is allocated at compilation time or run time, the memory used by by them can’t be reduced or extended. As the elements are stored in consecutive locations, the insertions & deletion in the arrays are time consuming.

Multidimensional Arrays Most programming languages allow two-dimensional and three-dimensional arrays, i.e., arrays where elements are referenced, respectively, by two and three subscripts. In fact, some programming languages allow the number of dimensions for an array to be as high as 7. A two dimensional m×n array A is a collection of m.n data elements such that each element is specified by a pair of integers (such as J, K), called subscripts, with the property that 1 ≤ J ≤ m and 1 ≤ K ≤ n

Multidimensional Arrays (Contd.) The element of A with first subscript j and second subscript k will be denoted by AJ,K or A[J,K] Two dimensional arrays are called matrices in mathematics and tables in business applications; hence two dimensional arrays are sometimes called matrix arrays.

Multidimensional Arrays (Contd.) There is a standard way of drawing a two-dimensional m×n array A where the elements of A form a rectangular array with m rows and n columns and where the element A[J, K] appears in row J and column K. Columns 1 2 3 4 A[1, 1] A[1, 2] A[1, 3] A[1, 4] A[2, 1] A[2, 2] A[2, 3] A[2, 4] A[3, 1] A[3, 2] A[3, 3] A[3, 4] Rows Two-dimensional 3×4 array A

Multidimensional Arrays (Specification) Suppose A is a two-dimensional m×n array. The first dimension of A contains the index set 1, …….., m, with lower bound 1 and upper bound m; and the second dimension of A contains the index set 1, 2, …….., n, with lower bound 1 and upper bound n. the length of a dimension is the number of integers in its index set. The pair of lengths m×n (read “m by n”) is called the size of the array.

Multidimensional Arrays (Length) The length of a given dimension (i.e., the number of integers in its index set) can be obtained from the formula Length = upper bound – lower bound + 1

Representation of Two-Dimensional Arrays in memory Let A be a two-dimensional m×n array. Although A is pictured as a rectangular array of elements with m rows and n columns, the array will be represented in memory by a block of m.n sequential memory locations. Specifically, the programming language will store the array A either Column by column, what is called column major order, or Row by row, in row major order. The figure shows these two ways when A is a two-dimensional 3×4 array. We emphasize that the particular representation used depends upon the programming language, not the user.

Representation of Two-Dimensional Arrays in memory Subscript (1, 1) (2, 1) Col 1 (3, 1) (1, 2) (2, 2) Col 2 (3, 2) (1, 3) (2, 3) Col 3 (3, 3) (1, 4) (2, 4) Col 4 (3, 4) A A Subscript (1, 1) (1, 2) Row 1 (1, 3) (1, 4) (2, 2) Row 2 (2, 3) (2, 4) (3, 1) (3, 2) Row 3 (3, 4) a) Column major order b) Row major order

2 Dimensional Arrays Like linear array, 2-D array also keeps track of the address of first element only i.e. the base address of the array. Using this base address, the computer computes the address of the element in the ith row & jth col. , i.e. loc(a[i][j]), using the following formula: Column Major Order: loc(a[i][j]) = base(a) + w[m(j – lbc)+ (i- lbr)] (in general) loc(a[i][j]) = base(a) + w(m *j +i) ( in c/c++) Row Major Order: loc(a[i][j]) = base(a) + w[n(i – lbr)+ (j- lbc)] (in general) loc(a[i][j]) = base(a) + w(n *i +j) ( in c/c++)

c program to transpose a matrix #include<stdio c program to transpose a matrix #include<stdio.h> #include<conio.h> main() { int m, n, c, d, matrix[10][10], transpose[10][10]; printf("Enter the number of rows and columns of matrix "); scanf("%d%d",&m,&n); printf("Enter the elements of matrix \n"); for( c = 0 ; c < m ; c++ ) for( d = 0 ; d < n ; d++ ) scanf("%d",&matrix[c][d]); } transpose[d][c] = matrix[c][d]; printf("Transpose of entered matrix :-\n"); for( c = 0 ; c < n ; c++ ) for( d = 0 ; d < m ; d++ ) printf("%d\t",transpose[c][d]); printf("\n"); getch(); return 0;

Thank You