Page 60 - DCAP407_DATA_STRUCTURE
P. 60
Unit 3: Arrays
Output:
Enter the number of elements to insert in an array:
6
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
Enter element 6: 60
Enter the element to be searched:
40
Element is found at position 4
In this example:
1. First, the header files are included using #include directive.
2. An array named M with an element storage capacity of 20 is declared.
3. The variable i, ele, and num are declared.
4. The user enters the number of elements to be inserted in the array M.
5. The first for loop accepts the input and stores the elements in the array M.
6. Then, the user enters the element to be searched in the array M.
7. The second for loop checks if the condition M[i] is equal to the search
element entered. If the condition is true, then the position of the element in
the array M is displayed. Otherwise, the program displays a message
“Element not found”.
8. The getch() prompts the user to press any key and then the program is
terminated.
Write an algorithm to search an element in an array using binary search technique.
3.3.4 Traversing Operation
Traversing an array refers to moving in inward and outward direction to access each element in an
array. To traverse an array, one can use for loop. The array elements are accessed using an array index
or a pointer of type similar to that of array elements. To access the elements using a pointer, the pointer
must be initialized with the base address of the array. Traversing operation also involves printing the
elements in an array.
Algorithm for Traversal Operation
Let X be an array of size N. You need to traverse through the array and perform the required operations
on each element of the array. Let the required operation be OP. Here, i is the array index and the lower
bound starts with 0. The algorithm for traversing a given array is as follows:
1. Start
2. read X[N], i=0
3. repeat for I = 0, 1, 2…..N
OP on X[i]
4. Stop
LOVELY PROFESSIONAL UNIVERSITY 53