Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Arrays Department of Computer Science

2 C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an Array is a fixed size sequenced collection of elements of the same data type” OR “ it is a sequenced collection of related data items that share a common name” Example: Array name student to represent a set of students in a class. The students can be referred individually by writing a number called Index or subscript in brackets [ ] followed by the array name. i.e. : students[50].

3 1- dimensional or single dimensional arrays: A list of items can be given with one variable name using only one subscript and such a variable is called as single subscripted variable or a one dimensional array For example : int number[4];refers to 4 memory (storage) locations, if we want to store the following numbers namely {10,20,30,40} then we have as shown in fig 2 number [0] number[1] number [2] number[3] 10 20 30 40 number [0] number[1] number [2] number[3]

4 Declaration of 1- dimensional arrays Arrays must be declared before they are used. The general form of declaration is given by type variable-name[size]; Where the type specifies the data type of the element. size gives the maximum number of elements that can be stored Examples: int class[50]; float amount[20];

5 Initialization of 1- dimensional arrays Arrays must be initialized otherwise they refer to garbage values. The array can be initialized in the following 2 ways 1.At compile time 2.At run time Compile time initialization: type array-name[size]={list of values}; Where the values are seperated by commas. Examples: int number[5]={1,2,3,4,5}; If the number of values are less than the number of elements, the remaining elements will be set to zero automatically by the complier float amount[20];

6 Reading/ writing single dimensional arrays for(i=0; i< n; i++) scanf(“%d”,&a[i]); for(i=0; i< n; i++) printf(“%d”,a[i]);

7 Algorithm sum_of_pos_neg This algorithm calculates the sum of positive & negative numbers and the average of all the numbers. Step 1: [Start] Step 2: [Input the number of items] read n Step 3: [Read N elements from keyboard] for i=0 to n-1 read a[i] end for Step 4: [Initialization] psum=nsum=0 Step 5: [Find the sum of +ve and –ve no.s] for i=0 to n-1 in steps of 1 do if (a[i] >=0) psum=psum+a[i] else nsum=nsum+a[i] end for Step 6: [compute the average] avg=(psum+nsum)/n Step 7: [Output the sum] write(psum,nsum,avg) Step 8: [Finished] stop

8 Searching Searching is the process of finding the location of the specified element in a list. The specified element is often called the search key. If the process of searching finds a match of the search key with a list element value, the search is said to be successful ; otherwise, it is unsuccessful. The two most commonly used search techniques are: Sequential search [linear search] Binary search Sequential search [Linear search] A Linear search is a simple searching technique. In this technique we search for a given key item in the list in linear order i.e; one after the other. The item to be searched is often called key item.

9 For example: if key =10 and the list is 20,10,40,25 after searching we say that key is present. If key =100 after searching we say that key is not present. Procedure: let us take an example. Assume 10 is the item to be searched in the list of items 50,40,30,60,10. observe from above figure that, 10 has to be compared with a[0], a[1], a[2], a[3], and a[4] as shown below: During search if item ==a[0] or if item ==a[1] or if item ==a[2] or if item==a[3] or if item ==a[4] The search is successful 5040302010 for(i=0; i< 5; i++) { if (item==a[i]) { printf(“successful”); exit(0); }

10 Algorithm Linear_ search This algorithm is used to search for an item in a given list. Step 1: [Start] Step 2: [Input the number of items] read n Step 3: [Read N elements from keyboard] for i=0 to n-1 read a[i] end for Step 4:[Input the item to be searched] read key Step 5:[Search for the element to be searched (key)] for i=0 to n-1 if (key=a[i]) write(“successful”) stop end if end for write(“ unsuccessful”); Step 6: [Finished] stop

11 Advantages / Disadvantages of Linear Search: 1.Very simple. 2.Works well with small arrays/ when the size of the array is small. 3.Used when the elements are not sorted/ works when the array is unsorted. Disadvantages: 1.Not efficient / in efficient.

12 Binary Search Technique This searching technique requires the array to be in sorted order either in ascending or descending order. Procedure: This method divides the given array into 2 halves and considers that Portion in which the item (search element) is present. The above process is repeated until the item is located or the entire array is searched to find that item is not present

13 Binary Search Technique To locate the given key element in an array, the following variables are Used: 1. low = location of first element in the selected portion 2. mid= location of the middle element in the array (center) 3. high= location of the last element 4. key/item=search element 5. n = number of elements in the given array

14 Binary Search Technique Procedure: 1. Initialize variables low and high to 0 and n-1 low=0, high=n-1. 2. Find the middle element mid=(low+high)/2 3. Compare the key item with the element a[mid] at the middle of the array- the following possible situations arise a. if key < a[mid], then the key lies in the first half of the array, therefore low=0(remains the same) high=mid-1 b. if key > a[mid], then the key lies in the second half of the array, therefore low=mid+1 high=n-1(remains the same) c. if item=a[mid], then the key item is found and the location is equal to mid, STOP the searching process. 4. Repeat steps 2 & 3, until either the key item is found or until scanning of entire array is completed 5. If low > high, it indicates that the entire array has been scanned and the item is not present in the array, stop the scanning process

15 Let us take up a example in which an array a consists of 13 elements, where in the key item is 27(search element). 481013172022252730313539 0123456789101112 Low =0 High=12 Mid1=(0+12)/2=6 i.e. 22

16 252730313539 789101112 Since key item is 27 which is greater than the middle element, consider the second half of the array by setting low = mid1+1 = 7 and high=remains the same(12) Mid2=(low+high)/2 (7+12)/2=9 = 30 Since the key element is 27 which is < 30 Choose the first half of the array by making the following settings Low=remains the same (7) High= mid2-1=(9-1)=8

17 2527 78 Mid3=(low+high)/2=(7+8)/2=7=25 Since the key element is 27 which is >25 Choose the second half of the array by making the following settings Low=mid3+1=7+1=8 High= remains the same=8

18 27 8 Mid4=(low+high)/2=(8+8)/2=8=27 Since the key element is 27 which is a[mid4]=27 The item is found

19 Bubble sort Technique This is the simplest of all sorting techniques that requires passing through the array sequentially several times. Thus while sorting an array in ascending order, the largest element is pushed to last location(n-1) after the first pass. Subsequent largest element is pushed to last but one location(n-2) after the second pass and so on. In general the Bubble Sort technique requires (n-1) passes to sort an array with n elements.

20 Bubble sort Technique – PASS 1 Consider an array of 5 elements that are to be sorted in ascending order, it requires 4 passes. 139752 01234 9 752 97 52 975 2 9752 01234 Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] Exchange a[2] & a[3] since a[2] > a[3] Exchange a[3] & a[4] since a[3] > a[4] 1 st Largest element is at location 4

21 Bubble sort Technique – PASS 2 975213 01234 7952 7592 7529 01234 Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] Exchange a[2] & a[3] since a[2] > a[3] 2 nd Largest element is at location 3

22 Bubble sort Technique – PASS 3 752913 01234 5729 5279 01234 Exchange a[0] & a[1] since a[0] > a[1] Exchange a[1] & a[2] since a[1] > a[2] 3 rd Largest element is at location 2

23 Bubble sort Technique – PASS 4 527913 01234 2579 01234 Exchange a[0] & a[1] since a[0] > a[1] The array is sorted in ascending order

24 Selection sort Technique In this method, successive elements chosen in order are placed into sorted positions.

25 Selection sort Technique The strategy given below is used to sort an array with n elements in descending order. 1.To place the largest element at location 0, find the location loc of the largest element in the array and exchange the elements a[0] & a[loc]. 2.To place the next largest element at location 1, find the location loc of the largest element among the succeeding elements from location 2 to location n-1 and swap the elements a[1] and a[loc]. The elements at locations i and loc are exchanged using the following Code: temp=a[i]; a[i]=a[loc]; a[loc]=a[i];

26 Selection sort Technique Consider an array a with the following elements a To place an appropriate element at location 0: Find the location loc of the largest element among the elements from locations 1 to n-1 and exchange the elements a[0] with a[loc] Initially let loc=0 swap a[0] & a[4] 1537106 1 5 3 7 6 0 1 2 3 4 5 a [1] >a [loc] : loc=1 a [2] < a [loc] : loc remains as 1 a [3] > a [loc] : loc=3 a [4] > a [loc] : loc=4 a [5] < a [loc] : loc remains as 4 10 5 3 7 1 6 0 1 2 3 4 5

27 Selection sort Technique Let loc=1 swap a[1] & a[3] 0 1 2 3 4 5 a [2] < a [loc] : loc remains as 1 a [3] > a [loc] : loc=3 a [4]< a [loc] : loc remains as 3 a [5] < a [loc] : loc remains as 3 10 7 3 5 1 6 0 1 2 3 4 5 5 3 7 1 6

28 Selection sort Technique Let loc=2 swap a[2] & a[5] 0 1 2 3 4 5 a [3] > a [loc] : loc=3 a [4]< a [loc] : loc remains as 3 a [5] > a [loc] : loc =5 10 7 6 5 1 3 0 1 2 3 4 5 7 3 5 1 6

29 Selection sort Technique Let loc=3 swapping not required 0 1 2 3 4 5 a [4]< a [loc] : loc remains as 3 a [5] < a [loc] : loc =5 10 7 6 5 1 3 0 1 2 3 4 5 7 6 5 1 3

30 Selection sort Technique Let loc=4 swap a[4] & a[5] 0 1 2 3 4 5 a [5] > a [loc] : loc =5 10 7 6 5 3 1 0 1 2 3 4 5 7 6 5 1 3 Thus it can be seen that the array is sorted in descending order.

31 Horner’s Method – evaluation of a polynomial While evaluating a polynomial function numerous multiplications, additions etc are required. By writing the polynomial in a particular form the number of computations required can be reduced as shown below in a example The polynomial function requires 10 multiplications and 4 additions Given f(x)=10x 4 + 6x 3 + 4x 2 + 5x +20 The above polynomial can be re written as f(x)=(10x 3 + 6x 2 + 4x + 5)x +20 =((10x 2 + 6x + 4)x + 5)x+ 20 =(((10x+ 6)x+ 4)x+ 5)x+ 20. This requires / needs 4 multiplications and 4 additions

32 Horner’s Method – Procedure 1.Store the coefficients a0,a1,a2,…..an in the array [a]. 2.Store the successive values generated while evaluating the Horner’s series in the array [b], such as b[0] = a[0] b[1] = b[0] * x + a[1] b[2] = b[1] * x + a[2] b[3] = b[2] * x + a[3] b[n] = b[n-1] * x + a[n] The successive coefficients b[0], b[1], b[2]……….b[n], can be calculated using the for loop as given below b[0]=a[0]; for (i=1; i<n; i++) b[ i ] = b[ i-1 ] * x + a[ i ]

33 Mean, variance and Standard Deviation sum=0; for(i=0;i<n;i++) { sum=sum+x[i]; } mean=sum/n; Variance & Deviation can be calculated using: sum=0; for(i=0;i<n;i++) { sum=sum+(x[i]-mean) * (x[i]-mean); } variance=sum/n; deviation=sqrt(variance);

34 2-dimensional Arrays Arrays with 2 sets of square brackets [ ] [ ] are called 2 dimensional arrays 2-dimensional arrays are used when data items are arranged in row-wise and column wise in a tabular fashion. Declaration of 2 dimensional arrays data_type array name[exp1][exp2]; Where data type = basic data types Array name = name of the array exp1, exp2= constant expressions that are enclosed within square brackets and no variables are allowed. Ex: int a[3][4];

35 Reading & Writing 2- dimensional Arrays: /* read the elements of matrix*/ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { scanf(“%d”,&a[ i ][ j ]); /* to read m x n */ }

36 Reading & Writing 2- dimensional Arrays: /* printing the elements of matrix*/ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { printf(“%d ”,a[ i ][ j ]); /* to print m x n */ } printf(“\n”); }

37 Addition of 2 matrices a & b and storing the result in c for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { c[ i ][ j ]= a[ i ] [ j ] + b[ i ][ j ]; }

38 Subtract matrix b from a and storing the result in c for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { c[ i ][ j ]= a[ i ] [ j ] - b[ i ][ j ]; }

39 Sum of Elements of a given Matrix /* a[i ] [ j ] is added with sum whose value is initialized to 0 in the beginning */ sum=0; for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { sum= sum+ a[ i ] [ j ]; }

40 Transpose of a given Matrix /* let a & b be 2 matrices, matrix b is said to be the transpose of a when its rows and columns are interchanged */ i.e. a [ i ] [ j ]=b[ j ] [ i ] for (i=0;i< m; i++) /* m rows */ { for (j=0;j< n; j++) /*n columns */ { b[ j ] [ i ] = a [ i ] [ j ]; }

41 Trace of a given Matrix /* The Trace of a matrix is the sum of the elements of principal diagonal elements in a given matrix – rectangular matrix */ sum = 0; for (i=0;i< n; i++) { sum = sum + a [ i ] [ i ]; }

42 Norm of a given Matrix /* The norm of a matrix is the square root of sum of the squares of all the elements in a given matrix */ sum = 0; for (i=0;i< m; i++) for (j=0;j< n; i++) sum = sum + a [ i ] [ j ] * a [ i ] [ j ] ; norm=sqrt(sum);

43 Product of 2 matrices a & b and storing the result in c /* multiplication of 2 matrices is possible iff the number of columns of first matrix and number of rows of the second matrix are same */ i.e. = let m x n be the size of the 1 st matrix and p x q be the size of the 2 nd matrix, if n=p then multiplication is possible */ for (i=0;i< m; i++) /* m rows */ { for (j=0;j< q; j++) /*n columns */ { sum=0; for (k=0;k< n; k++) { sum=sum + a[ i ] [ k ] * b[ k ][ j ]; } c[ i ][ j ]=sum; } If(n!=p) { printf(“ multiplication is not possible”); exit(0); } printf(“ multiplication is possible”);

44


Download ppt "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."

Similar presentations


Ads by Google