Arrays 3 - Searching and Finding Frequency
Arrays 3 - Searching and Finding Frequency
Lecture 3
Objectives
• Searching a number in Array
• Finding index of key element
• Finding frequency of key element
• Find and replace (one and all)
• Calculating sum and average
Searching in Array
• The process of finding a particular element in an array is called
searching.
• The linear search compares each array element with the search key.
Code for searching a key element in array
#include <iostream>
using namespace std;
int main()
{
const int size = 5;
int arr[size] = {3,21,5,33,9};
int key = 0, flag = 0;
cout<<"Enter a number you want to search in array: ";
cin>>key;
for(int i=0; i<size; i++)
{
if(arr[i]==key)
{
flag = 1;
break;
}
}
if(flag == 1)
cout<<"number found";
else
cout<<"number not found";
return 0;
}
• In this code we are using a loop to sequentially step through an array,
starting with the first element.
• It compares each element with the key being searched for and stops
when that key is found or the end of the array is reached.
• If we found the key element, we will set our flag and stops with the
help of break statement. It will save extra comparisons.
Finding Index of key element
• In searching algorithm we were only indicate the user about the
presence of key element.
• But now we have to indicate the user about the location of key element
if found.
• If the search key is a member of the array, typically the location of the
search key is reported to indicate the presence of the search key in the
array. Otherwise, a sentinel value is reported to indicate the absence of
the search key in the array
Code for Finding Index of key element
#include <iostream>
using namespace std;
int main()
{
const int size = 5;
int arr[size] = {3,21,5,33,9};
int key = 0, index = -1;
cout<<"Enter a number you want to search in array: ";
cin>>key;
for(int i=0; i<size; i++)
{
if(arr[i]==key)
{
index = i;
break;
}
}
if(index >= 0)
cout<<"number is at index: "<<index;
else
cout<<"number not found";
return 0;
}
Finding frequency of key element
• In this Program we will count the occurrences of key element in an
array.
• The idea is simple, we initialize the variable count as 0 and traverse
array in linear fashion.
• For every element that matches with key element, we increment
count.
• After traversing the whole array we will print the count.
• Below is the implementation of the approach.
Code for Finding frequency of key element
#include <iostream>
using namespace std;
int main()
{
const int size = 5;
int arr[size] = {3,21,5,33,9};
int key = 0, count = 0;
cout<<"Enter a number you want to search in array: ";
cin>>key;
for(int i=0; i<size; i++)
{
if(arr[i]==key)
{
count++;
}
}
cout<<“count of your entered number is: "<<count;
return 0;
}
Find and Replace