Professional Documents
Culture Documents
Lecture #8
Traversal
Traversal in an array means printing the elements of the array one by one. This means you are
traversing through the elements of the array one after the other. A simple program for traversal in
an array is shown below.
© LPU :: CAP267 Data Structures :: Dr. Amanpreet Singh
3 Traversal of Array
# include<iostream>
using namespace std;
int main()
{
int arr[10] = {1,5,7,9,2,4,6,8,10,15};
int i;
cout<<"The array elements are \n";
for(i = 0 ; i < 10 ; i++)
{ Output:
cout<<arr[i]<<" ";
The array elements are
} 1 5 7 9 2 4 6 8 10 15
return 0;
} © LPU :: CAP267 Data Structures :: Dr. Amanpreet Singh
4 Insertion:
The original array elements are : The array elements after insertion :
arr[0] = 1 arr[0] = 1
arr[1] = 2 arr[1] = 2
arr[2] = 3 arr[2] = 33
arr[3] = 4 arr[3] = 3
arr[4] = 5 arr[4] = 4
arr[5] = 6 arr[5] = 5
arr[6] = 6
Deletion operation is used to delete an element from the array. A simple program to perform deletion in an
array is shown below. for(i=0; i<n; i++)
{
#include <iostream>
if(arr[i]==elem)
using namespace std; {
int main() for(j=i; j<(n-1); j++)
{ arr[j] = arr[j+1];
int arr[ ] = {7,4,5,9,8,15}; found=1;
int n = sizeof(arr)/sizeof(arr[0]); n--;
int elem = 9, found=0; }
}
int i, j;
if(found==0)
cout<<"The original array elements are :\n"; cout<<"\nElement doesn't found in the Array!"<<endl;
for(i = 0; i<n; i++) else
{ {
cout<<"arr:"<<i<<"="<<arr[ i ]<<endl; cout<<"The array elements after deletion :\n";
} for(i = 0; i<n; i++)
{
cout<<"arr"<<i<<"="<<arr[i]<<endl;
}
}
return 0;
} © LPU :: CAP267 Data Structures :: Dr. Amanpreet Singh
7
The original array elements are : The array elements after deletion :
arr[0] = 7 arr[0] = 7
arr[1] = 4 arr[1] = 4
face[2] = 5 arr[2] = 9
arr[3] = 9 arr[3] = 8
arr[4] = 8 arr[4] = 15
arr[5] = 15
A search operation is used to search for an element in the array. It can also be used to search
for an element greater than or less than the specified element. A simple program to perform
this operation is shown below.
while(j <= 5)
{
#include <iostream>
if( face[ j ] == item )
using namespace std;
{
int main()
flag=1;
{
break;
int face[ ] = {7,4,5,9,8,15};
}
int j=0, flag, item = 9;
j++;
flag=0;
}
cout << "The original array elements are :\n";
if(flag==1)
for(int i = 0; i <= 5; i++)
cout << "Found element " << item << " at index " << j << endl;
{
else
cout << "face[" << i << "] = " << face[ i ] << endl;
cout<<"Not Found";
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
// Reverse an integer array
int myArray[] = {1, 2, 3, 4, 5};
int size = sizeof(myArray) / sizeof(myArray[0]); Output:
int i;
for(i=size-1;i>=0;i--) 54321
{
cout<<myArray[i]<<"\t";
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int size1 = 5;
int size2 = 3;
Updating refers to updating an existing array element at a particular value to a new element value.
Thank You