DSA Lab#02
DSA Lab#02
Objective:-
The objective of this Lab is to understand the various operations on arrays in C++.
Software Tools:-
Dev C++
Theory:-
We have already studied different operations that can be performed on array data
structures. We would be using the knowledge we learned there to implement
different operation on arrays.
Algorithm:-
(Traversing a Linear Array) Here LA is a linear Array with lower Bound LB and upper
Bound UB. This algorithm traverses LA.
Applying an operation PROCESS to each element of LA.
1. [Initialize counter] Set K=LB.
2. Repeat Step 3 and 4 while K≤UB.
3. [Visit element] Apply PROCESS to LA[K].
4. [Increase Counter] Set K=K+1.
End of Step 2 Loop
5. Exit
HIET
Example Program:-
#include <iostream>
using namespace std;
int main()
{
int arr[5]={3, 15, 60, 45, 37};
//traversing
for (int k = 0; k < 5; k++)
{
cout<<arr[k]<<endl;
}
}
Similarly deleting the element at the “end” of an array presents no difficulties but
deleting the element somewhere in the middle of the array would require that each
subsequent element be moved one location upward in order to fill up the array.
HIET
Algorithm:-
(Inserting into Linear Array) INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K≤N.
This algorithm inserts an element ITEM into the Kth position in LA.
Example Program:-
#include <iostream>
using namespace std;
int main()
{
int array[100], k, j, n, val;
cout<<"Enter number of elements in array"<<endl;
cin>>n;
cout<<"Enter the elements"<<endl;
for (j = 0; j < n; j++)
{
cin>>array[j];
}
cout<<"Enter the location where you want to insert the new element"<<endl;
cin>>k;
cout<<"Enter the value of element to be inserted"<<endl;
cin>>val;
for (j = n - 1; j >= k - 1; j--)
HIET
{
array[j+1] = array[j];
}
array[k-1] = val;
cout<<"The New array after insertion: "<<endl;
for (j = 0; j <= n; j++)
{
cout<<array[j]<<endl;
}
return 0;
}
Algorithm:-
(Deletion from a Linear Array) DELETE(LA, N, K)
Here LA is a linear array with N elements and K is a positive integer such that pos≤N.
This algorithm deletes an element ITEM from the Kth position in LA.
Lab Task:-
Write C++ program to implement all the above described algorithms and display
the output for each.
HIET