• No results found

Arrays Declarations and Initialization One dimensional Arrays Two dimensional Arrays Multi dimensional Arrays Character Arrays

N/A
N/A
Protected

Academic year: 2022

Share "Arrays Declarations and Initialization One dimensional Arrays Two dimensional Arrays Multi dimensional Arrays Character Arrays"

Copied!
27
0
0

Loading.... (view fulltext now)

Full text

(1)

Arrays

Derived Data types

Arrays

► Declarations and Initialization

► One dimensional Arrays

► Two dimensional Arrays

► Multi dimensional Arrays

► Character Arrays

One dimensional

Two dimensional

1

(2)

More than one Dimension

Two dimensional arrays also called as matrix Declaration:

type variable_name[size1][size2];

size1 –>Number of rows in matrix size2 –> Number of columns in matrix

Examples:

int number[4][3]; /* 12 elements */

float number[3][2]; /* 6 elements */

char name[10][20]; /* 200 chars */

(3)

Initialization of a 2-D Array

int a[2][3]={1,2,3,4,5,6};

int a[2][3]={{1,2,3}, {4,5,6}};

int a[][3]={{1,2,3}, {4,5,6}}

int a[2][3]={0}

How values will be assigned in each case??

Following initializations are not allowed int a[3][]={2,4,6,8,10,12};

int a[][]={2,4,6,8,10,12};

Note: If the first bracket pair is empty, then compiler take the size from the number of inner brace pairs

3

(4)

Memory Map for 2-D Arrays

Kept in memory as a linear sequence of variables.

Two methods for storing-

Row major

Column major Example:

int a[3][3];

Row major storage:

a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2], a[2][0], a[2][1], a[2][2]

Column major storage:

a[0][0], a[1][0], a[2][0], a[0][1], a[1][1], a[2][1], a[0][2],

a[1][2], a[2][2]

(5)

String Initialization:

char str[9] = “I like C”;

same as

char str[9]={‘I’,‘ ‘,’l’,‘i’,’k’,’e’,‘ ‘,’C’,’\0’};

5

(6)

Arrays of Strings

Declaration:

char name[5][30];

Five strings each contains maximum thirty characters.

Initialization:

char[5][10]={“One”,”Two”,”Three”,”Four”,”Five”

};

Other valid declarations

char[][]={“One”,”Two”,”Three”,”Four”,”Five”};

char[5][]={“One”,”Two”,”Three”,”Four”,”Five”};

(7)

Operation on Arrays

► Following operation can be performed on Arrays:

► Traverse (traverse whole array)

► Insertion and Deletion

► Searching (Linear or Binary)

► Merging (combining two arrays )

► Sorting (Ascending or descending)

7

(8)

Insertion

Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array.

Following can be a situation with array insertion −

Insertion at the beginning of an array

Insertion at the given index of an array

Insertion after the given index of an array

Insertion before the given index of an array

(9)

Insertion : Algorithm

LA is a linear array with N elements and K is a positive integer such that K<=N.

Following algorithm inserts new element ITEM at K

th

position in LA.

INSERT(LA, N, K, ITEM)

1. Set J = N-1 (Initialize counter)

2. Repeat while J>= K

3. Set LA[J+1] = LA[J] (move J

th

element downwards) 4. Set J = J-1 (Decrement counter)

5. Set LA[K] = ITEM (insert new element) 6. Set N= N+1 (reset No of element)

7. Exit 9

(10)

Deletion

► Deletion refers to removing an existing element from the array and re-organizing all elements of an array.

► Deletion at the End:

► Deleting an element at the “end” of the array can be done easily by reducing the size of array by one.

► Deletion Somewhere in the middle:

► Deleting an element somewhere from middle requires each

subsequent element be moved one location upward (location with

smaller subscript) to fill up the array.

(11)

Deletion: Algorithm

LA is a linear array with N elements and K is a positive integer.

Following algorithm deletes the K

th

element and assigns it to a variable ITEM .

DELETE(LA, N, K, ITEM)

1.

Set ITEM=LA[k] (initialize the position of element to be deleted)

2.

Repeat for j = K to N-1

Set LA[j] = LA[j+1] (Move J+1st element towards left/upward)

[End of Loop.]

3. Set N=N-1 (Decrement the size of array by one)

4. Exit.

11

(12)

Searching

This method finds out whether the data entered by the user is present in an array or not.

There are two searching method:

(i) Linear or Sequential search

(ii) Binary search

(13)

Search: Linear Search

► In Linear search, we search an element or value in a given array by traversing the array from the starting, till the desired element or value is found.

► It compares the element to be searched with all the elements present in the array and when the element is matched successfully, it returns the index of the element in the array, else it return not found.

► Linear Search is applied on unsorted or unordered lists, when there are fewer elements in a list.

13

(14)

Algorithm steps

Given array A containing N elements. This algorithm finds the location LOC of Item in array A. If Item is not there in A then it return unsuccessful search.

LINEAR( A, N, Item, LOC)

1. Set LOC:=-1, Set J=0 //initialize counter

2. Repeat for J=0 to N-1 // search for an item if A[j]==Item

LOC=j [End of Loop]

3. If LOC==-1 then Item not found else

Item= A[LOC]

(15)

Question:

WAP to enter any string. Search a character ‘e’ in the inputted string and replace it with character ‘ u’.

15

(16)

Binary Search

Binary search uses a recursive method to search an array to find a specified value

The array must be a sorted array:

a[0]≤a[1]≤a[2]≤. . . ≤ a[finalIndex]

If the value is found, its index is returned

If the value is not found, -1 is returned

Note: Each execution of the recursive method reduces the search space by about a

half

(17)

17

• Binary Search is used with sorted array or list.

• In binary search, we follow the following steps:

1. We start by comparing the element to be searched with the element in the middle of the list/array.

2. If we get a match, we return the index of the middle element.

3. If we do not get a match, we check whether the element to be searched is less or greater than in value than the middle element.

4. If the element/number to be searched is greater in value than the middle number, then we pick the elements on the right side of the middle element(as the list/array is sorted, hence on the right, we will have all the numbers greater than the middle number), and start again from the step 1.

5. If the element/number to be searched is lesser in value than the

middle number, then we pick the elements on the left side of the

middle element, and start again from the step 1.

(18)
(19)

19

(20)
(21)
(22)

So , the result is Element Found at index 7.

(23)

Note:

Binary Search is useful when there are large number of elements in an array and they are sorted.

So a necessary condition for Binary search to work is that the list/array should be sorted.

23

(24)

Binary Search Algorithm

1. Set beg=0,end=N-1, mid=int(beg+end)/2 [initialize variables]

2. Repeat 3 and 4 while(beg<=end) and a[mid]!=item.

3. If(item<a[mid])

Set end=mid-1;

Else

Set beg=mid+1

4.

Set mid=int(beg+end)/2

[ end of step 2 loop]

5. if(a[mid]==item) Set loc = mid Else

Set loc =NULL

(25)

Which search method is better

Linear Search is slower, inefficient and works on unsorted list. If the data we are searching is not present in the list, we come to know at the end of the list.

Thus, Binary search is far better than Linear search

25

(26)

Question 1

Let A be an n * n square matrix array. Write algorithm which

a. Finds the number NUM of nonzero elements in A.

b. Finds the product PROD of the diagonal elements ( a

00

, a

11

, a

22

…..a

nn

)

(27)

REVIEW

References

Related documents

If the inspiration of the itinerary is from listening to experiences family friends, the decision making still becomes biased since it is some other person’s experience, moreover

The Episcopal Church mission in the Philippines was already consolidated before the War through instruments of unity instituted to help the office of the

Samples were deposited from diagnosed, early inflammatory bowel disease (IBD) patients at Akershus University Hospital (Ahus), Oslo, Norway.. These were the children from the

ARTICLE 23-A REQUIRES EMPLOYERS TO CAREFULLY CONSIDER THE FOLLOWING EIGHT FACTORS TO DETERMINE WHETHER OR NOT TO HIRE AN APPLICANT WITH A PRIOR CONVICTION: 1\ New York

Data types of the columns must be compatible with the array type: indices must be smallint for short arrays and int for max arrays. The value type must match the element type of

Firstly, as their English language proficiency course ran alongside the courses at the faculty and their ongoing research, the participants became too occupied with their

Array databases [6] provide flexible, scalable services on massive multi-dimensional arrays, consisting of storage management and processing functionality for multi-dimen-

La violencia y la corrupción en el país se han revertido contra los mismos habitantes y se ha salido del control de las élites políticas, que en un principio eran quienes